How to compare float value in in Django [duplicate]

允我心安 提交于 2019-12-12 03:36:12

问题


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


回答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**-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.




回答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?



来源:https://stackoverflow.com/questions/15000021/how-to-compare-float-value-in-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!