3) Stirling\'s approximation NNeNV2TN is commonly used to approx- imate the fact
ID: 3876547 • Letter: 3
Question
3) Stirling's approximation NNeNV2TN is commonly used to approx- imate the factorial of large numbers. a) What is the behavior of the relative error for this approximation as a function of N E [1; 100]?. Hint1: For this sort of question I highly recommend using a plot to support your answer (don't forget the la- bels). Hint2: In Matlab/Python the exact value of N! is given by gamma(N+1) (in Python import the gamma function from the mod ule "math" first) b) What is the smallest integer value of N that could be used in Stirling's approximation with less than 0.5% relative error?Explanation / Answer
a.
from math import gamma
from math import factorial as fact
import matplotlib.pyplot as plt
from math import log
import numpy as np
import math as math
def stirling(n):
return math.sqrt(2*math.pi*n)*(n/math.e)**n
t = np.arange(1, 100, 1);
error = lambda t : (gamma(t+1) - stirling(t))/stirling(t)
errorFunction = np.vectorize(error)
plt.plot(t, errorFunction(t+1) )
plt.show()
b.
from math import gamma
from math import factorial as fact
import matplotlib.pyplot as plt
from math import log
import numpy as np
import math as math
def stirling(n):
return math.sqrt(2*math.pi*n)*(n/math.e)**n
for x in range (1,100):
if(gamma(x+1) - stirling(x))/stirling(x) < 0.005:
print(x)
break;
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.