Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python sterling's approximation program

I'm trying to write a simple program that prints the first Stirling's approximation for the integers 1:10 alongside the actual value of 1:10 factorial. This is my code:

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

I'm getting the wrong output for the factorial, where did I mess up the code?

like image 335
Emir Avatar asked Dec 26 '22 21:12

Emir


1 Answers

(1) You need to reset nf=1 each time you compute the factorial (or, alternatively, only multiply by one new number each time, which would be more efficient);

(2) range(1,x) doesn't include x, so your factorials won't include the right upper bound. The following should work:

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

which produces

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
like image 153
DSM Avatar answered Jan 11 '23 19:01

DSM