HP-UX Floating-Point Guide

Chapter 3 71
Factors that Affect the Results of Floating-Point Computations
How Basic Operations Affect Application Results
How Basic Operations Affect
Application Results
To understand why floating-point calculations can yield different results,
you need to know how a system performs the most basic operations: add,
subtract, multiply, divide. Recall from “Inexact Result (Rounding)” on
page 53 that these operations always round their results to the nearest
representable floating-point value using an algorithm specified by the
rounding mode, and that this rounding introduces a rounding error
into the result of the operation.
For example, suppose you run the following program. Two operations
that are mathematically equivalent may produce different results:
Sample Program: rounderr.f
PROGRAM ROUNDERR
REAL A, B, C, D, E, F
PRINT *, 'Enter 4 reals:'
READ *, A, B, C, D
E = (A + B) * (C + D)
F = (A * C) + (A * D) + (B * C) + (B * D)
IF (E .EQ. F) THEN
WRITE (*, 20) E, ' equals ', F
ELSE
WRITE (*, 20) E, ' not equal to ', F
WRITE (*, *) 'Math error!'
ENDIF
20 FORMAT(F, A, F)
END
Depending on the values read for A, B, C, and D, the program will indeed
print “Math error!”, although, of course, no error has actually occurred—
only legitimate rounding errors:
$ f90 rounderr.f
rounderr.f
program ROUNDERR
21 Lines Compiled
$ ./a.out
Enter 4 reals:
1.1 2.2 3.3 4.4
25.4100018 not equal to 25.4099998
Math error!