python - 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)
解决方案
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)
推荐阅读
- java - JavaFX:与 NumberConverter 双向绑定
- java - 如何模拟 SpringSecurity 和 OncePerRequestFilter(JWT 身份验证过滤器)以获取 @AuthenticationPrincipal?
- wix - Wix 工具集 - 相同的 MSI 未重新安装
- reactjs - 如何更新 MobX 中的嵌套存储
- python - 如何从单个 Flask 路由执行两个 SQL 命令
- javascript - 回显的 HTML 表单不调用 onsubmit 函数
- jenkins - 如何在jenkins中动态更改sonarqube projectVersion号
- android - Android:无法通过文本或其他应用程序从原始文件夹发送音频文件
- networking - 码头工人网络
- ionic-framework - Ionic - 滚动到特定元素 Virtual Scroll