Python 溢出错误:(34,'结果太大')

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20201706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:51:45  来源:igfitidea点击:

OverflowError: (34, 'Result too large')

pythonoverflowdecimalpi

提问by user3033766

I'am getting an overflow error(OverflowError: (34, 'Result too large')
I want to calculate pi to 100 decimals here's my code:

我收到溢出错误(OverflowError: (34, 'Result too large')
我想将 pi 计算为 100 位小数,这是我的代码:

def pi(): 
    pi = 0 
    for k in range(350): 
        pi += (4./(8.*k+1.) - 2./(8.*k+4.) - 1./(8.*k+5.) - 1./(8.*k+6.)) / 16.**k 
    return pi 
print(pi())

采纳答案by Peter DeGlopper

Python floats are neither arbitary precision nor of unlimited size. When k = 349, 16.**kis much too large - that's almost 2^1400. Fortunately, the decimallibrary allows arbitrary precision and can handle the size:

Python 浮点数既不是任意精度也不是无限大小。当 k = 349 时,16.**k太大了 - 几乎是 2^1400。幸运的是,该decimal库允许任意精度并且可以处理大小:

import decimal
decimal.getcontext().prec = 100
def pi():
    pi = decimal.Decimal(0)
    for k in range(350):
        pi += (decimal.Decimal(4)/(decimal.Decimal(8)*decimal.Decimal(k+1))...)

回答by Martijn Pieters

You reached the limits of your platform's floatsupport, probably after k = 256:

您达到了平台float支持的极限,可能是在k = 256以下情况之后:

>>> k = 256
>>> (4./(8.*k+1.) - 2./(8.*k+4.) - 1./(8.*k+5.) - 1./(8.*k+6.)) / 16.**k
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: (34, 'Result too large')
>>> k = 255
>>> (4./(8.*k+1.) - 2./(8.*k+4.) - 1./(8.*k+5.) - 1./(8.*k+6.)) / 16.**k
3.19870064997e-313

See sys.float_infofor the exact limitations, but you are unlikely to run into a current CPU and OS combination that'll give you 100 significant digits in any case; my MacBook Pro with 64-bit OS X will only support 15.

查看sys.float_info确切的限制,但您不太可能遇到在任何情况下都会为您提供 100 位有效数字的当前 CPU 和操作系统组合;我的 64 位 OS X MacBook Pro 只支持 15。

Use the decimalmoduleto go beyond your hardware limitations.

使用该decimal模块超越您的硬件限制。

from decimal import Decimal, localcontext

def pi(): 
    with localcontext() as ctx:
        ctx.prec = 100  # 100 digits precision
        pi = Decimal(0) 
        for k in range(350): 
            pi += (Decimal(4)/(Decimal(8)*k+1) - Decimal(2)/(Decimal(8)*k+4) - Decimal(1)/(Decimal(8)*k+5) - Decimal(1)/(Decimal(8)*k+6)) / Decimal(16)**k 
    return pi 

回答by Bence

16.**256 is too large to be stored in double precision float. I suggest that you run your cycle for less, like range(250), because larger k values will not contribute to the first hundred digits anyway.

16.**256 太大,无法存储在双精度浮点数中。我建议你少运行你的循环,比如 range(250),因为更大的 k 值无论如何都不会影响前一百位数字。

Another thing you might try is to multiply by 16.*(-k) instead of dividing by 16.*k. This number will be rounded to zero for large k, therefore will not give you runtime errors.

您可能会尝试的另一件事是乘以 16.* (-k) 而不是除以 16.*k。对于大 k,此数字将四舍五入为零,因此不会给您带来运行时错误。

I suggest that you use numpy.power instead of **, it handles overflows better. For example, in your code numpy.power(16.,256) would evaluate to inf, and dividing a finite number by inf gives zero, which avoids runtime errors just like the method suggested in the previous paragraph.

我建议你使用 numpy.power 而不是 **,它可以更好地处理溢出。例如,在您的代码中 numpy.power(16.,256) 将评估为 inf,并且将有限数除以 inf 得到零,这避免了运行时错误,就像上一段中建议的方法一样。

回答by u7420336

I use python3.6 AMD64,I also meet this problem,this is because python built-in floatis double-precision-float,it's 64 bit,in most progamming task,64 bit is enough,but in some extra task,it's not enough(like scitific computing,big data compute)

我使用python3.6 AMD64,我也遇到这个问题,这是因为python内置float是双精度浮点数,它是64位,在大多数编程任务中,64位就足够了,但在一些额外的任务中,这还不够(如科学计算、大数据计算)