Home > OS >  Name is not defined python - specific value
Name is not defined python - specific value

Time:03-14

import numpy as np;

def cg(A,b,x):
     A = np.array([[1,2,3], [4,5,6], [7,8,9]])
     r = b-np.dot(A,x)
     r = p
     rfirst = np.dot(np.transpose(p), Ap)
for i in range(len(b)):
     Ap = np.dot(A,p)
     a = rfirst/np.dot(np.transpose(p), Ap)
     x = x np.dot(a,p)
     r = r-np.dot(a,Ap)
     rupd = np.dot(np.transpose(r),r)

     if np.sqrt(rupd) < 100000:
          break 
     p = r (rupd/rfirst)*p
     rfirst = rupd
return x
 

I am getting an error in the following code where I am trying to run CG algorithm.

NameError: name 'p' is not defined

I am a bit confused about that since I have already defined r = p within the function.

CodePudding user response:

You don't show where 'p' is defined at all. As it is, Ap = np.dot(A,p) cannot run without having p

Also, p doesn't exist in the function, better not to rely on variables from other scopes. If the function needs p pass it as an argument

CodePudding user response:

def cg(A,b,x):
 A = np.array([[1,2,3], [4,5,6], [7,8,9]])
 r = b-np.dot(A,x)
 r = p <-------------------------------------- // where did this guy come from?
 rfirst = np.dot(np.transpose(p), Ap)
  • Related