0

In the following code, I try to create an array of functions which i need later for other computations. When I compute the function for T = 1 in the loop, the result displayed is the correct one because I compare it with the analytical result i calculated. Later on, when I need to call these functions I stored in the array, apparently, it is not the right function that is called. Perhaps it is a pointers problem, but I'm not sure how this problem occurs.

X0 = 1
T = 1
sigma = 0.2
r = 0.02
def E(n,t):
    y = np.exp((n*r+0.5*n*(n-1)*sigma**2)*t)
    return y

phi_0= lambda t : 1 #initial term

phi_1=[]  #first order term
phi_2=[0]*9  #second order term

phi1_1 = lambda t : t
phi1_2 = lambda t : X0*(np.exp(r*t)-1)
phi1_3 = lambda t : X0*t/T
phi_1 = [phi1_1,phi1_2,phi1_3] #there is no problem this way 

for i in range(1,4):
    for j in range(1,4) :
        alpha = (i==2) +(i==3) + (j==2) +(j==3)
        ind = j-1+3*(i-1)
        
        if i==1 :
            result = lambda t : integrate.quad(lambda s : E(alpha,s)*phi_1[j-1](t-s),0,t)[0]
        if i == 2 and j==1 :        
            result = lambda t : integrate.quad(lambda s :X0*(r+sigma**2*(alpha-1))*E(alpha,s)*phi_1[1-1](t-s),0,t)[0]
        if  i==2 and j ==2 :
            result = lambda t : integrate.quad(lambda s :X0*(r+sigma**2*(alpha-1))*E(alpha,s)*phi_1[2-1](t-s)+0.5*(sigma*X0)**2*E(alpha,s)*phi_0(t-s),0,t)[0]
        if i == 3 :
            result = lambda t : integrate.quad(lambda s : X0/T*E(alpha-1,s)*phi_1[j-1](t-s),0,t)[0]
        if not ((i==1) or (i == 2 and j==1) or (i==2 and j ==2) or (i == 3)) :
            result= lambda t : 0
            
        phi_2[ind] = result
        print(result(T),(i,j),alpha) # results displayed here are the correct ones

However, when I try his

In : phi_2[0](T)
Out: 0.5136043242122741
  • https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result – Dennis Jun 06 '22 at 01:22
  • Change `lambda t : integrate.quad(lambda s : E(alpha,s)*phi_1[j-1](t-s),0,t)[0]` to `lambda t, alpha=alpha, j=j: integrate.quad(lambda s : E(alpha,s)*phi_1[j-1](t-s),0,t)[0]`. Variables inside the lambda are evaluated when you call the lambda (after the loop is done); variables you define as default arguments are evaluated at the time the lambda is defined. – Samwise Jun 06 '22 at 01:24

0 Answers0