sympy用于计算π的数字背景是什么?
我知道SymPy在后台使用mpmath,从而可以使用任意精度算术来执行计算。这样,一些特殊常数,如e、pi、oo,被视为符号,并且可以以任意精度进行评估。
但是Sympy如何确定任意数量的小数位?它是如何进行数值计算的?
mpmath使用Chudnovsky公式(https://en.wikipedia.org/wiki/Chudnovsky_algorithm)计算π。
π的近似值由一个无穷级数计算,其项按照(1/151931373056000)^n递减,因此每个项大约增加14.18位数字。这使得可以选择一定数量的项N,以达到所需的精度。
实际计算是使用整数算术完成的:也就是说,对于prec位精度,计算了pi * 2^(prec)的近似值。
以下是代码,从mpmath/libmp/libelefun.py中提取(https://github.com/fredrik-johansson/mpmath/blob/master/mpmath/libmp/libelefun.py):
# Constants in Chudnovsky's series
CHUD_A = MPZ(13591409)
CHUD_B = MPZ(545140134)
CHUD_C = MPZ(640320)
CHUD_D = MPZ(12)
def bs_chudnovsky(a, b, level, verbose):
"""
Computes the sum from a to b of the series in the Chudnovsky
formula. Returns g, p, q where p/q is the sum as an exact
fraction and g is a temporary value used to save work
for recursive calls.
"""
if b-a == 1:
g = MPZ((6*b-5)*(2*b-1)*(6*b-1))
p = b**3 * CHUD_C**3 // 24
q = (-1)**b * g * (CHUD_A+CHUD_B*b)
else:
if verbose and level < 4:
print(" binary splitting", a, b)
mid = (a+b)//2
g1, p1, q1 = bs_chudnovsky(a, mid, level+1, verbose)
g2, p2, q2 = bs_chudnovsky(mid, b, level+1, verbose)
p = p1*p2
g = g1*g2
q = q1*p2 + q2*g1
return g, p, q
@constant_memo
def pi_fixed(prec, verbose=False, verbose_base=None):
"""
Compute floor(pi * 2**prec) as a big integer.
This is done using Chudnovsky's series (see comments in
libelefun.py for details).
"""
# The Chudnovsky series gives 14.18 digits per term
N = int(prec/3.3219280948/14.181647462 + 2)
if verbose:
print("binary splitting with N =", N)
g, p, q = bs_chudnovsky(0, N, 0, verbose)
sqrtC = isqrt_fast(CHUD_C<<(2*prec))
v = p*CHUD_C*sqrtC//((q+CHUD_A*p)*CHUD_D)
return v
isqrt_fast()
,用于计算大整数的平方根。如果可用,MPZ是所使用的大整数类型:gmpy.fmpz,否则使用Python内置的长整型。 @constant_memo
装饰器缓存了计算出的值(在数值计算中经常需要重复使用pi,因此将其存储起来是有意义的)。>>> pi_fixed(53) * 10**16 // 2**53
mpz(31415926535897932)