Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Not defined variable in numpy

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)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading