In this post, we explain how to implement Newton’s method in Python from scratch. We will be using the SymPy symbolic toolbox to automatically differentiate the function and automatically define the Newton iteration. The YouTube video accompanying this video is given below
First, we briefly revise Newton’s method. The purpose of Netwon’s method is to solve the equations having the following form:
(1)
starting from some initial guess of the variable
The basic idea is to compute a line that passes through the point
(2)
From the last equation, we can determine
(3)
So Newton’s method can be summarized as follows
- Pick an initial guess of the solution for
, that is, select - For
, update the solution
(4)
Let us write the Python code to compute this solution. Let us use the following test case
(5)
The zeros of this function are obviously at x=-3 and x=-7. This can be seen by either recalling the formula for the zeros of the quadratic equation
(6)
that are given by
(7)
or by recalling that the zeros of the quadratic function directly participate in the coefficients:
(8)
We will use Python to code the Newton method. We will use Python symbolic toolbox to perform differentiation. Instead of manually computing the first derivative, we will let Python to symbolically differentiate the function
# -*- coding: utf-8 -*-
"""
Created on Wed May 25 08:37:25 2022
@author: ahaber
"""
# Newtwon method implementation in python
import sympy as sym
import numpy as np
x=sym.Symbol('x')
f=x**2+10*x+21
diff_f=sym.diff(f,x)
diff_f
f_func=sym.lambdify(x,f,'numpy')
diff_f_func=sym.lambdify(x,diff_f,'numpy')
def newtonMethod(x0,iterationNumber, f,df):
x=x0
for i in range(iterationNumber):
x=x-f(x)/df(x)
residual=np.abs(f(x))
return x,residual
solution,residual = newtonMethod(-2,200,f_func,diff_f_func)
We use the Python toolbox SymPy to define symbolic variable x on the code line 14. The code line 16 is used to define the function
That is it! It is simple as that. This code can be modified and used in more complex codes.