How To Compare Float Value In In Django
Solution 1:
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**-6defare_floats_equal(a,b):
returnabs(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.
Solution 2:
That's because of rounding errors. Never compare floats with ==
, always use this template:
def floats_are_the_same(a,b): return abs(a-b) < 1e-6
if floats_are_the_same(value, 17.4):
....
i.e. check that the value is close to some desired value. This is because float arithmetic almost always has rounding errors:
>>>17.1 + 0.3
17.400000000000002
See also: What is the best way to compare floats for almost-equality in Python?
Post a Comment for "How To Compare Float Value In In Django"