Consider this program
float a = 0.7f;
if (a < 0.7)
{
Console.WriteLine("Less");
}
The output is Less
. Why??
Answer
Because 0.7
does not have an exact representation as a float
or a double
: it is not an exact sum of negative powers of 2.
It happens that the closest representation of 0.7
as a is float
approximately 0.69999998807907104492
, while the closest double
representation is 0.69999999999999995559
. As you can see, double
is slightly greater, which explains the behavior of your program.
Here is a small demo that you could run to see the values on your system:
printf("%20.20f %20.20f\n", 0.7, (float)0.7);
The takeaway lesson here is that you should not expect double
and float
representations of mathematically equal numbers to compare for equality correctly. Only a small subset of fractional numbers are representable in floating point system as exact numbers.
Since the overwhelming majority of fractions would be approximated, it is a good idea to do the comparisons with some level of tolerance. For example, instead of writing if (a == 0.7)
you should write if (abs(a - 0.7) < 1E-8)
No comments:
Post a Comment