Search code examples
pythonfunctionscipynewtons-method

Why is "name 'x' not defined" when trying to implement the Newton-Raphson method?


I want to find the zeros of a simple function for given parameters a, b, c. I have to use the Newton-Raphson method. The problem I obtain when I compile the code is that the x variable is not defined.

from scipy import optimize

def Zeros(a, b, c, u):
  return optimize.newton(a*x**2+b*x+c, u, 2*ax+b, args=(a, b, c))

a, b, c are constants of the function f and u is the starting point. So with this function I should be able to obtain a zero by specifying a, b, c and u. For instance:

print Zeros(1, -1, 0, 0.8)

But I obtain "global name 'x' is not defined".

Why does that happen?


Solution

  • The way most programming languages work is that they use variables (the names a, b, c, u in your code) and functions (Zeros, for instance).

    When calling a function, Python expects all of the "quantities" that are input to be defined. In your case, x does not exist.

    The solution is to define a function that depends on x, for the function and its derivative

    from scipy import optimize
    
    def Zeros(a,b,c,u):
        def f(x, a, b, c):
            return a*x**2+b*x+c
        def fprime(x, a, b, c):
            return 2*a*x + b
        return optimize.newton(f, u, fprime=fprime,args=(a,b,c))
    
    print(Zeros(1,-1,0,0.8))