简体   繁体   English

需要说明为什么以下代码跨越无穷大

[英]Need explanation why the following code spans for infinity

I am a beginner to python and was wondering why the code spans for infinity when it should've been stopped at 1. 我是python的初学者,想知道为什么本应在1处停止时代码跨越无限。

def main():
    i = 0.0
    while i != 1.0:
        print("i =", i)
        i += 0.1
main()

This is a well known problem in Python. 这是Python中一个众所周知的问题。

Your variable i never becomes exactly 1, but instead becomes 0.9999999999999999. 您的变量i永远不会精确变为1,而是变为0.9999999999999999。

Do instead: 改为:

def main():
    i = 0.0
    while i <= 1.0:
        print("i =", i)
        i += 0.1

In the general case, of course you shouldn't compare floats by equality, but there's more to it: when you're adding like this you get floating point accumulation error. 当然,在一般情况下,您不应该平等地比较浮点数,但是还有更多的东西:当您像这样添加时,会出现浮点累积错误。

You can use an integer counter instead and apply multiplication every time to avoid that. 您可以改用整数计数器,并每次都应用乘法来避免这种情况。

def main():
    i = 0.0
    count = 0
    while i < 1.0:
        print("i =", i)
        count += 1
        i = count*0.1

main()

I have replaced i != 1.0 by i < 1.0 because that's all you need, but it even works with != (although I don't recommend that) now because there's no accumulation error anymore the way it's computed with the integer counter. 我已将i != 1.0替换为i < 1.0因为这是您所需要的,但它甚至可以与!= (尽管我不建议这样做),因为现在不再存在使用整数计数器计算错误的累积错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM