我收到溢出错误(OverflowError:(34,“结果太大”)) 我想将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浮点数既不精确,也不具有无限大小。当k = 349时,16.**k太大了-几乎是2 ^ 1400。幸运的是,该decimal库允许任意精度并可以处理大小:
16.**k
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))...)