0

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 value from 17.40 to 17 it works fine, please tell me how can i compare the float value

Rohit Goel
  • 3,396
  • 8
  • 56
  • 107

2 Answers2

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?

Community
  • 1
  • 1
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
  • 1
    There aren't always rounding errors. A float is made up of bits, each representing a unit twice as small as the one to the left, all taken to some exponent. So, if you have a number that can be represented as a sum of binary fractions (e.g. 1.75 = 1 + 0.5 + 0.25), you can have an exact float. However, a decimal like 0.1 cannot be represented as a sum of a finite number binary fractions, and thus the float is a tiny bit off. – Inductiveload Feb 21 '13 at 10:44
2

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.

entropy
  • 3,134
  • 20
  • 20