python sterling的近似程序

标签 python python-2.7

我正在尝试编写一个简单的程序来打印第一个 Stirling's approximation对于整数 1:10 以及 1:10 阶乘的实际值。这是我的代码:

import math

nf =1 

def stirling(n):
    return math.sqrt(2*math.pi*n)*(n/math.e)**n

print "n","\t", "Stirling","\t\tFactorial"
for x in range (1,11):
    for y in range(1,x):
        nf *=y
    print x,"\t", stirling(x), "\t\t", nf

我得到了错误的阶乘输出,我在哪里弄乱了代码?

最佳答案

(1) 每次计算阶乘时都需要重新设置nf=1(或者,每次只乘以一个新数,这样效率会更高);

(2) range(1,x) 不包括 x,因此您的阶乘将不包括右上界。以下应该有效:

nf = 1
for x in range (1,11):
    nf *= x
    print x,"\t", stirling(x), "\t\t", nf

产生

n   Stirling        Factorial
1   0.922137008896      1
2   1.91900435149       2
3   5.83620959135       6
4   23.5061751329       24
5   118.019167958       120
6   710.078184642       720
7   4980.39583161       5040
8   39902.3954527       40320
9   359536.872842       362880
10  3598695.61874       3628800

关于python sterling的近似程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11437700/

相关文章:

python - Scrapy:在 scrapyd 运行多个蜘蛛 - python 逻辑错误

python - String.maketrans 用于英语和波斯语数字

linux - 在 openstack 上安装多个实例时没有免费的 nbd 设备

python - 同步但不关闭 dbm

python - 表征股票市场神经网络的 Keras 损失和准确性

python - 创建一个生成新列表的交互式 Python GUI

python - 通过 Flask 上传多个文件或整个文件夹

python - PerformanceWarning : dropping on a non-lexsorted multi-index without a level parameter may impact performance. 如何摆脱它?

Python [Errno 17] 文件存在问题

python - 如何在Python中删除重复的短语?