为什么python在某些情况下不能判断1.0等于1,而其他情况可以?

Hao*_*ang 0 python

有一个python代码如下:

import sys
import fileinput, string
K = 3
f = raw_input("please input the initial "+str(K)+" lamba: ").split()

Z = []
sumoflamba = 0.0
for m in f:
    j = m.find("/")
    if j!=-1:
            e=float(m[:j])/float(m[j+1:])
    else:
            e = float(m)
    sumoflamba+=e
    if e==0:
            print "the initial lamba cannot be zero!"
            sys.exit()
    Z.append(e)
print sumoflamba
if sumoflamba!=1:
    print "initial lamba must be summed to 1!"
    sys.exit()
Run Code Online (Sandbox Code Playgroud)

当我用 0.7、0.2、0.1 运行它时。它将打印警告并退出!但是,当我使用 0.1、0.2、0.7 运行它时。它工作正常。0.3、0.3、0.4 也可以正常工作。我不知道......有人可以解释一下吗?对于所有这些情况,“print sumoflamda”将给出 1.0。

Ali*_*fee 5

几乎 Lattyware 提供的链接解释了 - 但简而言之,您不能指望在没有明确说明精度的情况下,相等比较可以在浮点中工作。如果您将值四舍五入或将其转换为整数,您将获得可预测的结果

>>> f1 = 0.7 + 0.2 + 0.1
>>> f2 = 0.1 + 0.2 + 0.7
>>> f1 == f2
False
>>> round(f1,2) == round(f2,2)
True
Run Code Online (Sandbox Code Playgroud)