Newtons Method Python

Prince Avecillas
3 min readAug 24, 2021

So this is for people who want to see newton’s method in python. Some basic calculus is required for full comprehension.

Math

My first exposure to numerical analysis was during college 2 years ago as a Sophomore. I never thought I would get into coding but I always thought numerical approximations to equations were fascinating. Looking back I still do so now I’ll show one of the methods I learned.

Numerical Methods are used for approximating solutions to equations that have no solutions through the use of iteration. That's where computers are handy

This is Newton's method pretty much.

  1. To find the roots of f(x) you take f(x) and then take the derivative f `(x).

2. Then you take an initial numerical guess x(n) and evaluate the function and derivative at that value: f(x(n)), f `(x(n)).

Example x(n) = 1 then plug in f(1), f `(1)

3. Plugging all 3 numerical terms into the equation will solve for a numerical value x(n+1)

The process is then repeated with the new value x(n+1) in place of x(n) solving for another numerical value x(n+2).

The process is repeated until the numerical value converges to some value, and that is the root of the equation.

It is best to use an initial guess that is as close to the root as possible since newtons method converges locally.

Newton’s method converges quadratically.

Python

This is the code translation of newton’s method for python:

from math import *

def equation(x):
return x**3 + e**x

def derivative(x):
return 3*x**2 + e**x

xn = 1

for k in range(10):
xn = xn-equation(xn)/derivative(xn)
print(k, str(round(xn, 7)))

  1. So first we import all(*) the special functions like the exponential and trigonometric functions.
  2. Then the equation f(x) is defined as x³ +e^x
  3. With the derivative f `(x) as 3x² +e^x
  4. The initial guess is xn = 1
  5. Then a for loop is activated 10 times (iterations); going through newton’s method 10 times and each time using the new value of xn
  6. xn = xn-equation(xn)/derivative(xn) is newtons method
  7. The values are printed out rounded to 7 decimal places

The print values for this code comes out as

0 0.3497554
1 -0.4686911
2 -0.8756406
3 -0.7818552
4 -0.772957
5 -0.772883
6 -0.772883
7 -0.772883
8 -0.772883
9 -0.772883

According to this, the root of x³ +e^x is approximately -0.772883 since there is convergence to that value over a number of iterations.

Graph

Desmos Graph of x³ + e^x

A graph of demos proves the root is around the vicinity predicted by newton’s method.

Our initial guess was close to the root so newton’s method was able to find the value with only 5 iterations.

An initial guess of 100 would have taken 105 iterations for newton’s method to converge.

I find numerical analysis fascinating. Using iteration to find solutions to unsolvable problems is a great feat. Perhaps someday machines will help us solve even harder problems in mathematics and physics.

--

--