python中float的比较方式

print float(lastpayment)-temp,'and',float(self.pyament)

if (float(lastpayment)-temp) == float(self.pyament):
print "success: "+self.pyament+" == "+tempStr
else:
print "failed: "+self.pyament+" == "+tempStr

代码如上。
结果如下:
1602.7 and 1602.7
failed: 1602.7 == 4059.5+-37.7+-1565.0
float(lastpayment)-temp和float(self.pyament)打印出来都是1602.7
为什么不是相等的?
是python对于float类型有别的比较方法吗?

python比较浮点数相等,由于存在精度的关系,要用math模块的isclose方法
两数相差小于1e-9的话,则认为两个浮点数相等。
math.isclose(a, b, rel_tol=1e-9)
>>> import math
>>> math.isclose(1.0, 1.0000000001)
True
精度可以修改:
>>> math.isclose(1.0, 1.0000000001, rel_tol=1e-10)
False
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-09-19
浮点数不精确,如果想要使用精确小数,请用decimal
如果要比较浮点数a和b
-0.00000001 < a - b < 0.00000001这样比较本回答被提问者和网友采纳
第2个回答  2015-11-09
请把代码贴全
相似回答