且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用python计算非常大的数字

更新时间:2023-02-19 22:27:48

结合对数,使用斯特林近似值(在1e10 +范围内非常准确):

Use Stirling's approximation (which is very accurate in the 1e10+ range), combined with logarithms:

(3e28 choose 2e28) / 2^(3e28) = 3e28! / [(3e28 - 2e28)! * 2e28!] / 2^(3e28)
= e^ [log (3e28!) - log((3e28-2e28)!) - log(2e28!) - 3e28 * log(2)]

然后从那里应用斯特林近似值:

and from there apply Stirling's approximation:

log n! ~= log(sqrt(2*pi*n)) + n*log(n) - n

您将得到答案.

以下是此近似值的精确度示例:

Here's an example of how accurate this approximation is:

>>> import math
>>> math.log(math.factorial(100))
363.73937555556347
>>> math.log((2*math.pi*100)**.5) + 100*math.log(100) - 100
363.7385422250079

对于100 !,它在日志空间中的偏移量不到0.01%.

For 100!, it's off by less than 0.01% in log-space.