gpt4 book ai didi

python - 溢出错误 : (34, 'Result too large' )

转载 作者:太空狗 更新时间:2023-10-29 17:52:21 26 4
gpt4 key购买 nike

我遇到溢出错误(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())

最佳答案

Python float 既不是任意精度也不是无限大小。当 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))...)

关于python - 溢出错误 : (34, 'Result too large' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20201706/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com