Python虽然循环不稳定

时间:2012-08-27 18:20:35

标签: python while-loop

从未见过这样的事情。简单的循环:

t_end = 100.0
t_step= 0.1
time = 0

while time<=t_end:
    time+=t_step
    print time

最后3个印刷值:

...
99.9
100.0
100.1

看起来对我来说。

现在,我将t_step更改为0.01:

t_end = 100.0
t_step= 0.01
time = 0

while time<=t_end:
    time+=t_step
    print time

最后3个印刷值:

...
99.98
99.99
100.0

问题:为什么当time = t_end = 100.0时,它不会进入最后一个循环?

什么是替代解决方案?

3 个答案:

答案 0 :(得分:10)

因为这个100.0(总和的结果)可以大于100.0,所以你手工编写。你不应该将浮点数进行比较......

你应该读到这个:

What Every Computer Scientist Should Know About Floating-Point Arithmetic

可能的解决方案:

>>> t_end = 100.0
>>> t_step = 0.01
>>> total = int(t_end/t_step)
>>> for x in itertools.accumulate((t_step for i in range(total + 1))):
    print(x)

所以最后一个元素是: 100.01000000001426

答案 1 :(得分:6)

Floating point round-off error。这就是我最后三个价值所得到的:

99.98000000001424
99.99000000001425
100.00000000001425

答案 2 :(得分:3)

这源于浮点计算的不准确性。您依靠==运算符来比较两个浮点值,这是不行的。你所看到的'100.0'实际上可能就是'100.000000000314'

相关问题