如何更精确地执行二项式系数和阶乘计算?
How to perform binomial-coefficient and factorial calculation with more precision?
我正在将以下 python 计算的结果与 Mathematica 进行比较:https://www.wolframalpha.com/input?i=sum+%28500+choose+r+%29%28-1%29%5Er+%2F%28r%21%29+%2C+r%3D0+to+500
import numpy as np
from decimal import *
import scipy.special
from scipy.special import factorial
getcontext().prec = 30
i = 500
sum(np.array([scipy.special.comb(Decimal(i), (r), exact=True)*pow(-1, r)/Decimal(factorial(r, exact=False)) for r in range(i+1)]))
在 i = 400
之前,两种计算都给出了几乎相同的值,但在那之后未能收敛,即使我通过 decimal
模块在我的 python 代码中设置了任意精度。用 Mathematica 计算似乎是正确的。我可以知道,对于更大的 i
,我们如何在 python 中获得与 Mathematica 相同的结果?
问题是阶乘中有 exact=False。
>>> import numpy as np
>>> from decimal import *
>>> import scipy.special
>>> from scipy.special import factorial
>>> getcontext().prec = 30
>>>
>>> i = 500
>>> sum(np.array([scipy.special.comb(Decimal(i), (r), exact=True)*pow(-1, r)/Decimal(factorial(r, exact=False)) for r in range(i+1)]))
Decimal('-7.13859062099388393889008217957')
>>> sum(np.array([scipy.special.comb(Decimal(i), (r), exact=True)*pow(-1, r)/Decimal(factorial(r, exact=True)) for r in range(i+1)]))
Decimal('0.196589352363439561009074161963')
我正在将以下 python 计算的结果与 Mathematica 进行比较:https://www.wolframalpha.com/input?i=sum+%28500+choose+r+%29%28-1%29%5Er+%2F%28r%21%29+%2C+r%3D0+to+500
import numpy as np
from decimal import *
import scipy.special
from scipy.special import factorial
getcontext().prec = 30
i = 500
sum(np.array([scipy.special.comb(Decimal(i), (r), exact=True)*pow(-1, r)/Decimal(factorial(r, exact=False)) for r in range(i+1)]))
在 i = 400
之前,两种计算都给出了几乎相同的值,但在那之后未能收敛,即使我通过 decimal
模块在我的 python 代码中设置了任意精度。用 Mathematica 计算似乎是正确的。我可以知道,对于更大的 i
,我们如何在 python 中获得与 Mathematica 相同的结果?
问题是阶乘中有 exact=False。
>>> import numpy as np
>>> from decimal import *
>>> import scipy.special
>>> from scipy.special import factorial
>>> getcontext().prec = 30
>>>
>>> i = 500
>>> sum(np.array([scipy.special.comb(Decimal(i), (r), exact=True)*pow(-1, r)/Decimal(factorial(r, exact=False)) for r in range(i+1)]))
Decimal('-7.13859062099388393889008217957')
>>> sum(np.array([scipy.special.comb(Decimal(i), (r), exact=True)*pow(-1, r)/Decimal(factorial(r, exact=True)) for r in range(i+1)]))
Decimal('0.196589352363439561009074161963')