from math import factorial, log
import numpy as np

# Script som viser at stirlings approksimasjon er god når N blir stor
# Det betyr at for makroskopiske systemer med N ≈ Avogadros tall funker den
# Praktisk talt perfekt

def stirling(n):
    return n * log(n) - n

def exact_sol(n):
    return log(factorial(n))

n_list = [int(n) for n in np.logspace(1,6,50)] #Fill in the values of n_list that you wish to test

with open("Stirlings.txt", "w") as file: # Creates the file Stirlings.txt to be written
    file.write( "           n_list      " + "Exact solution      " + "       Stirling     " + "Absolute error     " + "Relative error" +'\n') #Sets up the file header and adjusts column width

    for ind, i in enumerate(n_list):
        print(ind)
        file.write( "%12d      %14.4f       %14.4f     %14.4f     %14.4f"%(i, exact_sol(i), stirling(i), exact_sol(i) - stirling(i), (1 - stirling(i)/exact_sol(i)))) #Calculates n_list factorial, the approximation and corresponding errors.
        file.write('\n')