Reputation:
I have to use bit/integer ops to figure out the epsilon for a given value in C. I know in terms of bit patterns that computing the next neighbor involves incrementing the mantissa, and if that overflows, to increment the exponent - but I'm not sure where to begin in terms of calculating the epsilon.
I can't use floating point math - so I need to generate the bit pattern directly. This makes it trickier because I cannot subtract.
Here's my understanding (based on some research I've done here on SO): the range changes obviously as the numbers get bigger, but I'm not sure how to use FLT_EPSILON
to generate the right numbers. For 2^2x numbers, perhaps it is (FLT_EPSILON - 1) * number
?
Upvotes: 2
Views: 3260
Reputation: 2096
due to IEEE 754 format you need 1 in mantissa and 127 shifted to 23
float x;
*((int*) &x) = 1;
*((int*) &x) = *((int*) &x) | 104 << 23;
printf("%.12f\n", FLT_EPSILON);
printf("%.12f\n", x);
Upvotes: 2
Reputation: 6793
If your epsilon is simply the value of one LSB increment to the mantissa, the value should be 2^(exp-23). So if your input is [s][exp][mantissa]
your epsilon should be [0][exp-23][0]
. Sure enough, when given an input of 1.0 ([0][127][0]
), the result is [0][104][0]
= 2^-23 = FLT_EPSILON
.
Upvotes: 4