OverflowError:(34,“结果太大") [英] OverflowError: (34, 'Result too large')

查看:628
本文介绍了OverflowError:(34,“结果太大")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到溢出错误(OverflowError:(34,结果太大")
我想将pi计算为100个小数,这是我的代码:

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

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浮点数既不具有精确度,也不具有无限大小.当k = 349时,16.**k太大了-几乎是2 ^ 1400.幸运的是,decimal库允许任意精度并可以处理大小:

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

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))...)

这篇关于OverflowError:(34,“结果太大")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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