I want to visualize the central limit theorem for an exemplary PDF. The following code works as I wish:
import sympy as sp
import numpy as np
import matplotlib.pyplot as plt
x, y = sp.symbols('x y')
dens = sp.exp(-x) #PDF
def sum(dens,n):
    """
    Parameters
    ----------
    dens : probabilty density function
    n : amount of iteration
    Returns
    -------
    pdf after n iterations
    """
    dens2 = dens.subs(x, y-x) #PDF for one further summed random variable
    
    i=1
    while i<=n:
        int = sp.integrate(dens*dens2, (x,0,y))
        int = int.subs(y,x)
        
        dens = int
        i += 1
        
    return int
#plot for n th iteration
n1 = 1
n2 = 20
n3=50
n4 = 100
X1 = np.linspace(0,200,num=1000)
Y1 = sp.lambdify(x,sum(dens,n1),'numpy')
plt.plot(X1, Y1(X1),label="n=1")
X2 = np.linspace(0,200,num=1000)
Y2 = sp.lambdify(x,sum(dens,n2),'numpy')
plt.plot(X2, Y2(X2),label="n=20")
X3 = np.linspace(0,200,num=1000)
Y3 = sp.lambdify(x,sum(dens,n3),'numpy')
plt.plot(X3, Y3(X3),label="n=50")
X4 = np.linspace(0,200,num=1000)
Y4 = sp.lambdify(x,sum(dens,n4),'numpy')
plt.plot(X4, Y4(X4),label="n=100")
plt.legend()
plt.show()
Now I'd like to do the plot for all the n possibilities (later I want to try to animate it, but at first I need to understand how to do this loop). Thus I want to do the plot using a loop instead of creating the plots separately as above. But this gives me the error
Traceback (most recent call last):
File "C:\Users\user\Desktop\ZGS.py", line 71, in Y = sp.lambdify(x,sum(dens,k),'numpy')
File "C:\Users\user\Desktop\ZGS.py", line 32, in sum return int
UnboundLocalError: local variable 'int' referenced before assignment
I tried some things such as global int but this creates problems within sympy. Why can I use different variables for n when plotting separately but get this error when assigning n using a loop?
n=100
for k in range(n):
    X = np.linspace(0,200,num=1000)
    Y = sp.lambdify(x,sum(dens,k),'numpy')
    plt.plot(X, Y(X))
    
    plt.show()
How can this problem be solved?
 
    