Ad

Not Defined Variable In Numpy

- 1 answer

i'm trying to run the code below but i get the same when running the code. The issue is that q seems to not be defined but this should not be true.

    #Question 1 

#i)
#Defining the parameters using SimpleNameSpace. par = Parameters
par = SimpleNamespace()
par.y = 1 #assets
par.p = 0.2 #probability
par.theta = -2 #elasticity 

#Defining utility function for agent
def utility(z,par):
    return (z**(1+par.theta))/(1+par.theta)

#Defining premium
def premium(q,par):
    return par.p*q

#Defining expected value
#Note that z_1, z_2 represents first and second part of the objective function - just in a compressed version
def exp_value (i,q,par):
    z_1 = par.y-i+q-premium(q,par)
    z_2 = par.y-premium(q,par)
    return par.p*utility(z_1,par)+(1-par.p)*utility(z_2,par)

def opt_q(i,q,par):
    obj = lambda q: -exp_value(i,q,par) #defining the objective function
    solution = optimize.minimize_scalar(obj, bounds=(0,0.9), method="bounded") #bounded solution within [0.01, 0.9] 
    q = solution.x 
    return q

for i in np.linspace(0.01,0.9,num=100):
    res = opt_q(i,q,par)
    print(res)
Ad

Answer

You are getting the NameError because you are not passing the q to opt_q in the last for-loop. Since it is already defined inside opt_q just remove q from its arguments and don't pass it in the for-loop as well as follows:

def opt_q(i,par):
    obj = lambda q: -exp_value(i,q,par) #defining the objective function
    solution = minimize_scalar(obj, bounds=(0,0.9), method="bounded") #bounded solution within [0.01, 0.9]
    q = solution.x
    return q

for i in np.linspace(0.01,0.9,num=100):
    res = opt_q(i,par)
    print(res)

This resolves your issue.

Ad
source: stackoverflow.com
Ad