奇怪的 python while 循环行为 <比较 [英] Strange python while loop behavior with < comparison

查看:42
本文介绍了奇怪的 python while 循环行为 <比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对这段代码感到困惑:

I'm confused with this snippet of code:

t=0
while  t<5:  #currently loop runs for 10 seconds
    print "in loop",t
    if (t<5):
        print "true"
    t=t+0.01

在循环的最后一次运行中打印:

prints in the last run through of the loop:

in loop 5.0 
true

现在,如果在最后一次通过循环时 t = 5.0 是真的,那么 t < 不应该是条件.5 在if 语句中不被满足?此外,它不应该甚至不运行 t=5 的循环,因为它也应该在 while 条件下失败吗?

Now if it is true that t = 5.0 on the last pass through the loop, shouldn't the condition that t < 5 in the if statement not be met? And furthermore, shouldn't it not even be running through the loop for t=5 since it should have also failed the while condition?

推荐答案

5 不一定是 5:

t=0
while  t<5:  #currently loop runs for 10 seconds
    print "in loop",t, repr(t)
    if (t<5):
        print "true"
    t=t+0.1

生产

in loop 0 0
true
in loop 0.1 0.1
true
in loop 0.2 0.2
true
in loop 0.3 0.30000000000000004

[...]

in loop 4.8 4.799999999999999
true
in loop 4.9 4.899999999999999
true
in loop 5.0 4.999999999999998
true

0.1 不能用二进制精确表示.

0.1 can't be represented exactly in binary.

[啊,我刚刚注意到我用的是 0.1 而不是 0.01,就像你一样.嗯,这是同样的问题.]

[Ah, I just noticed that I used 0.1 instead of 0.01, like you did. Well, it's the same issue.]

两个浮点工作原理"参考:经典绅士.

Two "how floating point works" references: classical and gentler.

这篇关于奇怪的 python while 循环行为 &lt;比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆