问题描述
我正在尝试计算(3e28选择2e28)/2 ^(3e28).我尝试scipy.misc.comb计算3e28选择2e28,但这给了我inf.当我计算2 ^(3e28)时,它引发了OverflowError:(34,结果太大").如何计算或估计(3e28选择2e28)/2 ^(3e28)?
I'm trying to calculate (3e28 choose 2e28)/2^(3e28). I tried scipy.misc.comb to calculate 3e28 choose 2e28 but it gave me inf. When I calculate 2^(3e28), it raised OverflowError: (34, 'Result too large'). How can I compute or estimate (3e28 choose 2e28)/2^(3e28)?
推荐答案
结合对数,使用斯特林近似值(在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.
这篇关于使用python计算非常大的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!