Search code examples
pythontypeerrorsympyderivativenewtons-method

Error in newton raphson method finding root


I was trying to use the newton raphson method to compute the derivative of a function and I got the following error:

import numpy as np
import matplotlib.pyplot as plt
import sympy as sym
acc = 10**-4

x = sym.Symbol('x')
def p(x): #define the function
    return 924*x**6 - 2772*x**5 + 3150*x**4 - 1680*x**3 + 420*x**2 - 42*x + 1

p_prime = sym.diff(p(x))
def newton(p,p_prime, acc, start_val):
    x= start_val
    delta = p(x)/p_prime(x)
    while abs(delta) > acc:
        delta = p(x)/p_prime(x)
        print(abs(delta))
        x =x- delta;
        return round(x, acc);

a = newton(p, p_prime,-4, 0)

The error was:

delta = p(x)/p_prime(x)
TypeError: 'Add' object is not callable

Solution

  • There are a few mistakes in your code, correcting them as pointed out in the following modified code snippet, it works fine:

    def p_prime(xval):            # define as a function and substitute the value of x
        return sym.diff(p(x)).subs(x, xval)
    
    def newton(p, p_prime, prec, start_val): # rename the output precision variable 
        x = start_val                        # otherwise it's shadowing acc tolerance
        delta = p(x) / p_prime(x)            # call the function p_prime()
        while abs(delta) > acc:
            delta = p(x) / p_prime(x)
            x = x - delta 
        return round(x, prec)                # return when the while loop terminates
    
    a = newton(p, p_prime,4, 0.1)
    a
    # 0.0338
    

    enter image description here

    The following animation shows how Newton-Raphson converges to a root of the polynomial p(x).