在(看似)无限循环中耗尽浮点精度 [英] Exhausting floating point precision in a (seemingly) infinite loop

查看:69
本文介绍了在(看似)无限循环中耗尽浮点精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下Python脚本:

I've got the following Python script:

x = 300000000.0
while (x < x + x):
    x = x + x
    print "exec: " + str(x)
print "terminated" + str(x)

这个看似无限的循环,如果x是一个浮点数,则很快终止.但是,如果我改为将x更改为300000000,它将陷入无限循环(在测试中运行的时间超过一分钟).

This seemingly infinite loop, terminates pretty quickly if x is a floating point number. But if i change x to 300000000 instead, it gets into an infinite loop (runs longer than a minute in my test).

我认为这与以下事实有关:它耗尽了可以在内存中表示的浮点数的精度.有人可以提供更详细的解释吗?

I think this is to do with the fact that it's exhausting the precision of a floating point number that can be represented in memory. Can someone provide a more detailed explanation why this is?

推荐答案

  • x 初始化为 300000000 时,整个程序都会使用整数数学.
  • x 初始化为 300000000.0 时,将使用浮点数学.
    • When you initialize x to 300000000, integer math is used throughout the program.
    • When you initialize x to 300000000.0, floating-point math is used instead.
    • 在Python中,整数可以任意增大.(更准确地说,它们受可用内存的限制.)这意味着程序的整数版本需要很长时间才能终止.

      In Python, integers can grow arbitrarily large. (More accurately, they're limited by the available memory.) This means that the integer version of your program takes a very long time to terminate.

      最大的 float 大约是 1.8e308 .循环的浮点版本大约需要进行1000次迭代才能超过该值,此时 x 被设置为正无穷大,程序终止.

      The largest float is about 1.8e308. It takes about 1000 iterations of the floating-point version of the loop to exceed that value, at which point x gets set to positive infinity, and the program terminates.

      这篇关于在(看似)无限循环中耗尽浮点精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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