[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
## Re: floating-point bug?

**From**: |
Eli Zaretskii |

**Subject**: |
Re: floating-point bug? |

**Date**: |
Thu, 11 Nov 2004 06:21:15 +0200 |

>* From: "Linda Riewe" <address@hidden>*
>* Date: Wed, 10 Nov 2004 15:21:53 -0800*
>* Cc: *
>* *
>* BEGIN {*
>* *
>* x = 3000 * 8.87*
>* y = 8.87 * 3000*
>* a = 3 * 8870*
>* b = 0.3 * 88700*
>* z = 26610.00*
>* w = 26610*
>* print "a=" a " b=" b " w=" w " x=" x " y=" y " z=" z*
>* print "x == y " ((x == y) ? "true" : "false")*
>* print "x == z " ((x == z) ? "true" : "false")*
>* print "x == a " ((x == a) ? "true" : "false")*
>* print "x == b " ((x == b) ? "true" : "false")*
>* print "x == w " ((x == w) ? "true" : "false")*
>* }*
>* *
>* but instead, it prints:*
>* *
>* > gawk -f tryit*
>* a=26610 b=26610 w=26610 x=26610 y=26610 z=26610*
>* x == y true*
>* x == z false*
>* x == a false*
>* x == b false*
>* x == w false*
Welcome to the wonderful world of floating-point computations, where
comparing numbers for equality is a risky business.
These values are not ``equal'' because small differences in fractional
digits (that don't show when you use `print', but will probably show
if you use `printf' with sufficient number of digits after the decimal
point) make them different.
The way to compare floating-point numbers is to do something like
this:
print "x == y " (abs(x - y) < eps ? "true" : "false")
where abs() is a function that returns the absolute value of its
argument, and eps is a small (machine-dependent) number, like 1.e-15.