Comparing floats in python(or any language that relies on the underlying hardware representation of floats) is always going to be a tricky business. The best way to do it, is to define a tolerance within which you would consider two numbers to be equal(say, 10^-6
) and then check if the absolute difference between the numbers is less than your tolerance.
Code:
TOLERANCE=10**-6
def are_floats_equal(a,b):
return abs(a-b) <= TOLERANCE
PS: if you really really want exact, arbitrary-precision, calculations with your floating point numbers, use the decimal module. Incidentally that page has some good examples of the failure points of regular floats. However, be aware that this is incredibly slower than using regular floats so don't do this unless you really really need it.