其他分享
首页 > 其他分享> > 我的’==’运算符不起作用

我的’==’运算符不起作用

作者:互联网

这是基本问题:

test = 24.02000 - 24
print "test: %f" % test
if (test == 0.02):
    print "OK"

输出:

test: 0.20000

还应该打印“确定”.

但是,如果我这样做:

test = 0.02
print "test: %f" % test
if (test == 0.02):
    print "OK"

我得到:

test: 0.020000  
OK

我是否在这里缺少某些东西,或者这真的是一个错误吗?

解决方法:

这是由于浮点不精确,因为计算机处理的是base-2,而计算机的处理是base-10:

>>> 24.02000 - 24
0.019999999999999574

要解决此问题,可以使用round:

test = 24.02000 - 24
print "test: %f" % test
if (round(test, 2) == 0.02):   #round the float to a certain degree of precision and then do the comparison
    print "OK"

[OUTPUT]
test: 0.020000
OK

如果要比较高精度,可以更改round的第二个参数:

(round(test, 5) == 0.2)

标签:equality,python
来源: https://codeday.me/bug/20191029/1961182.html