equality operator bug

Carlo de Falco carlo.defalco at gmail.com
Wed Jun 10 12:14:01 CDT 2009


On 10 Jun 2009, at 18:57, bug-octave-request at octave.org wrote:

> Description:
>
> -----------
>
>
>
>  * At times, the equality operator returns '0' when it should return '
> 1'.  Of course, this doesn't happen all the time.  Only some numbers
> cause the error.  This same problem causes find(x == constant ) to  
> also
> work improperly.
>
>
>
> Repeat-By:
>
> ---------
>
>
>
>  * A = 1.48 +.001
>
>      returns A = 1.4810
>
>
>
>    A == 1.481
>
>      returns 0 (false)

This is not a bug, it's just the way floating point numbers work, some  
numbers cannot
be represented exactly in binary floating-point (cfr. [1]):

 >> a=1.48 + .001
a =  1.4810
 >> format long
 >> a == 1.481
ans = 0
 >> a - 1.481
ans = -2.22044604925031e-16
 >> eps
ans =  2.22044604925031e-16

It's never safe to compare floating point numbers with "==",
you should rather do something like

 >> abs (a - 1.481) <= eps
ans =  1

HTH,
c.

P.S. FWIW if you try your example in matlab you should get the exact  
same results

[1] http://en.wikipedia.org/wiki/Floating_point


More information about the Bug-octave mailing list