Why is Lua arithmetic not equal to itself?

Possible duplicate:
What is a simple example of a floating point / rounding error?

When I execute the following Lua code:

a = 5.6
b = 14 * 0.4
c = 11.2 / 2
d = 28 * 0.2
print( a == b )
print( a == c )
print( a == d )
print( b == c )
print( b == d )
print( c == d )

I get the following results:

false
true
false
false
true
false

Can someone explain why 14 * 0.4 and 28 * 0.2 are not equal to 5.6?

thank

+4
source share
1 answer

You are dealing with the natural inaccuracy of binary floating point numbers. Your number amay be 5.5999999999999996, and your result bmay be 5.6000000000000005, which are not equal.

In fact, this is the same calculation as Python:

>>> 5.6
5.5999999999999996
>>> 14 * 0.4
5.6000000000000005

This behavior is common to all binary floating point implementations.

+12
source

All Articles