Python:浮点数无限长(精度浮点数)

Python: Float infinite length (Precision float)

我的代码:

def calc_pi(acc):
     pos = False
     sum = 4.0
     for i in range(2, acc):
          if not pos:
               sum -= 4.0/(2*i-1)
               pos = True
          else:
               sum += 4.0/(2*i-1)
               pos = False
     return float(sum)

print(calc_pi(5000))

当然,我正在尝试计算圆周率,其中有超过 10 个小数位。但是 Python 似乎四舍五入到 10。有没有简单的方法来防止它这样做?像一百万个小数点后的数字?

谢谢!

可以使用标准库提供的Decimalclass

来自文档:

Unlike hardware based binary floating point, the decimal module has a user alterable precision (defaulting to 28 places) which can be as large as needed for a given problem:

  >>> from decimal import *
  >>> getcontext().prec = 6
  >>> Decimal(1) / Decimal(7)
  Decimal('0.142857')
  >>> getcontext().prec = 28
  >>> Decimal(1) / Decimal(7)
  Decimal('0.1428571428571428571428571429')

Python 的内置浮点数通常是 64 位 IEEE754 浮点数(通常称为 "double")。

你想要的不是浮点表示,而是实际上可以(二进制)数字扩展的东西,就像 python 的整数类型可以任意增长。

因此,我敦促您查看小数整数表示,并进行数学运算以表示其中的数字。

您可以使用 Chudnovsky algorithm to calculate 100,000,000 decimal places of π. See also related questions 1000-digits-of-pi-in-python and .

如果不想实现自己的算法,可以使用mpmath包。对于 Chudnovsky 级数的小数点后大约 1000000 位:

from mpmath import mp
mp.dps = 1000000  # number of digits
print(mp.pi)   # calculate pi to a million digits (takes ~10 seconds)