首页 > 解决方案 > Write a Python program to verify the Stirling approximation

问题描述

A very important equations in statistical mechanics is Stirling approximation for large num-bers, lnN! =NlnN−N (N >>1). Write a Python program to verify this approximation. More specifically, evaluate the ratio lnN!/NlnN−N for N= 1000000.

Here is my program, but I can't get it to work. It doesn't give me an error, just Python breaks. I haven't been taught a lot of numpy, so I haven't been using that.

from math import log
N = 1000000
N_factorial=1
for i in range(1,N + 1):
       N_factorial = N_factorial*i
a = log(N_factorial)
b = N*log(N)-N
print(a/b)

标签: python

解决方案


You can just use the math.factorial() function:

>>> import math
>>> n = 1000000
>>> math.log(math.factorial(n))/(n*math.log(n)-n)
1.0000006107204127

However, using the logarithm product rule, you can sum the natural log of the factors of n (since log(a*b) = log(a) + log(b), log(a!) = log(a) + log(a-1) + log(a-2) + ... + log(2) + log(1))

>>> import math
>>> n = 1000000
>>> sum([math.log(i+1) for i in range(n)])/(n*math.log(n)-n)

推荐阅读