python 2.7 if语句为0.05 == 0.05提供错误输出

时间:2018-03-03 12:06:32

标签: python python-2.7

对于我的任务,我必须检查计算值是否在0.5的0.05之内。要做到这一点,我想从另一个中减去一个,取绝对值并检查是否小于或等于0.05应该做的伎俩。但是,当我尝试这段代码时。

one hundred point 25

返回一个非常奇怪的输出。

x = abs(0.5 - 0.55)

if x <= 0.05:
    print 'x is', x, 'x = yes'
else:
    print 'x is', x, 'x = no'

y = abs(0.4 - 0.45)

if y <= 0.05:
    print 'y is', y, 'y = yes'
else:
    print 'y is', y, 'y = no'

其中y被视为0.05但x未被视为0.05,但根据python,两个值均等于0.05。 我做错了吗?

3 个答案:

答案 0 :(得分:1)

默认情况下,它会生成长浮动值

试试这个: -

x = round(abs(0.5 - 0.55),2)
y = round(abs(0.4 - 0.45),2)

答案 1 :(得分:1)

>>> x = abs(0.5 - 0.55)
>>> x
0.050000000000000044
>>> y = abs(0.4 - 0.45)
>>> y
0.04999999999999999

这就是浮动的行为方式。 Most programming languages are like this.通常在比较浮点数时,检查是否在允许的值误差内更安全,而不是检查相等性:

>>> x = abs(0.5 - 0.55)
>>> allowed_error = 0.000001
>>> abs(x - 0.05) <= allowed_error
True

Python3.5添加了相关的math.isclose

答案 2 :(得分:0)

我会以这种方式使用Decimal:

from decimal import Decimal
x1 = abs(0.5 - 0.55)
x2 = Decimal(abs(0.5 - 0.55)).quantize(Decimal(10) ** -2)

print (x1)
print (x2)

输出:

0.050000000000000044
Decimal('0.05')

然后你的测试就可以了。