HP-UX Floating-Point Guide
Chapter 3 85
Factors that Affect the Results of Floating-Point Computations
Floating-Point Coding Practices that Affect Application Results
Sample Program: fpeq.c
#include <stdio.h>
int main(void)
{
union {
double x;
int a[2];
} u1, u2;
u1.x = 1.2 - 0.1;
u2.x = 1.1;
if (u1.x == u2.x)
printf("1.2 - 0.1 equals 1.1\n");
else {
printf("1.2 - 0.1 is NOT equal to 1.1.\n");
printf("1.2 - 0.1 = %x%x\n1.1 = %x%x\n",
u1.a[0], u1.a[1], u2.a[0], u2.a[1]);
}
}
From an algebraic viewpoint, this routine should print that 1.2 − 0.1
equals 1.1. In fact, though, when executed on a Series 700 machine, the
output is
1.2 - 0.1 is NOT equal to 1.1.
1.2 - 0.1 = 3ff1999999999999
1.1 = 3ff199999999999a
This anomaly occurs because the numbers 0.1 and 1.1 cannot be
represented exactly in IEEE-754 double-precision format. Both values,
1.1 and (1.2 − 0.1), are very close to the real number 1.1, but neither is
exact.
A better technique in most circumstances is to test that two values lie
within a relative proximity to each other. For example, the Fortran test
IF( X .EQ. Y )
could be replaced by
IF( ABS(X - Y) .LE. EPSILON )
where EPSILON is a sufficiently small floating-point value. This test
establishes whether X is within +/-EPSILON of Y.