While many people will tell you to always compare floating point numbers with epsilon (and this is usually a good idea, although this should be a percentage of the compared values, not a fixed value), that you are not really using constants here.
Your specific problem is this:
float a = 0.7;
uses the double constant 0.7 to create a single precision (losing some precision), while:
if (a == 0.7)
will compare two double-precision numbers ( a moves first).
The accuracy that was lost when turning double 0.7 to float a is not restored when a moves backward to double.
If you change all these 0.7 values to 0.7f (to force a float, not a double), or if you just make a double, it will work fine - I rarely use float at present, unless I have a massive array of them and must save space.
You can see this in action with:
#include <stdio.h> int main (void){ float f = 0.7; // double converted to float double d1 = 0.7; // double kept as double double d2 = f; // float converted back to double printf ("double: %.30f\n", d1); printf ("double from float: %.30f\n", d2); return 0; }
which will output something like (slightly modified to show the difference):
double: 0.6999999|99999999955591079014994 double from float: 0.6999999|88079071044921875000000 \_ different beyond here.
paxdiablo
source share