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?
(1) You need to reset
nf=1each 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:which produces