HP C A.06.05 Reference Manual
Expressions and Operators
Relational Operators (>, >=, <, ==, !=)
Chapter 5 129
if (func())
proceed
;
else
error handler
;
Dangers of Comparing Floating-Point Values
You may get unexpected results if you compare floating-point values for equality because
floating-point representations are inexact for some numbers. For example, the following
expression, though algebraically true, will evaluate to false on many computers:
(1.0/3.0 + 1.0/3.0 + 1.0/3.0) == 1.0
This evaluates to 0 (false) because the fraction 1.0/3.0 contains an infinite number of decimal
places (3.33333…). The computer is only capable of holding a limited number of decimal
places, so it rounds each occurrence of 1/3. As a result, the left side of the expression does not
equal exactly 1.0.
This problem can occur in even more subtle ways. Consider the following code:
double divide(double num, double denom)
{
return num/denom;
}
int main(void)
{
double c, a = 1.0, b = 3.0;
c = a/b;
if (c != divide(a, b))
printf("Fuzzy doubles\n");
}
Surprisingly, the value stored in c may not equal the value returned by divide(). This
anomaly occurs due to the fact that some computers can represent more decimal places for
values stored in registers than for values stored in memory. Because the value returned by
divide() is never stored in memory, it may not be equal to the value c, which has been rounded
for memory storage.
NOTE To avoid bugs caused by inexact floating-point representations, you should
refrain from using strict equality comparisons with floating-point types.