Search code examples
mathluafloating-pointsqrt

Why isn't 2 equal to √2 * √2?


I noticed that according to Lua, 2 ~= math.sqrt(2) ^ 2

print(2 == math.sqrt(2) ^ 2) --> false
print(2, math.sqrt(2) ^ 2) --> 2  2

Why is this happening?


Solution

  • Most floating point numbers can't be stored precisely in Lua's number type (C's double by default). math.sqrt(2) is one of them.

    If you try:

    print(2 - math.sqrt(2) ^ 2)
    

    Output: -4.4408920985006e-016 which is a very small number, but still, making the two numbers not exactly equivalent.


    This floating point precision problem exists not only in Lua, but also in many other languages. As @Thilo comments, you can use a small "delta" when comparing for equality in practice. You might be interested in: C FAQ: What's a good way to check for ``close enough'' floating-point equality?.