Skip to content Skip to sidebar Skip to footer

How To Compare Float Value In In Django

Hi i need to compare the float value in my project i am using the folowing code if style_score.style_quiz_score ==float(17.40): but it not works for this but when i change the va

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"