I am trying to find out the precision level for various floating point formats in C (i.e. float, double and long double). Here is the code I’m using at the moment:
#include <stdio.h>
#define N 100000
int main(void)
{
float max = 1.0, min = 0.0, test;
int i; /* Counter for the conditional loop */
for (i = 0; i < N; i++) {
test = (max + min) / 2.0;
if( (1.0 + test) != 1.0) /* If too high, set max to test and try again */
max = test;
if( (1.0 + test) == 1.0) /* If too low, set min to test and try again */
min = test;
}
printf("The epsilon machine is %.50lf\n", max);
return 0;
}
This gives the value of roughly ~2^-64 as expected. However when I change the decelerations to doubles or ‘long doubles’ I get the same answer I should get a smaller value but I don’t. Anybody got any ideas?
A guess why you’re getting the same answer:
Here 1.0 is a double constant, so it’s promoting your float to a double and performing the addition as a double. You probably want to declare a temporary float here to perform the addition, or make those float numeric constants (
1.0fIIRC).You might also be falling into the excess-precision-in-temporary-floats problem and might need to force it to store the intermediates in memory to reduce to the correct precision.
Here’s a quick go at redoing your range search method but computing the test in the correct type. I get an answer that’s slightly too large, though.