Newton-Raphson method using Python SymPy

Newton-Raphson method

Newton-Raphson is a very popular method for the numerical calculation of an equation’s root. Its’ basic concepts for formulation originate from the Taylor theorem and of course the fact that function value becomes zero at the root point. You can read more about the method in the Wikipedia entry.


SymPy is a Python library which enables the use of symbolic mathematical operations. It can solve equations, differentiate or integrate, simplify complex expressions or evaluate mathematical functions.

In various distributions you can install the package directly with the help of the corresponding package manager. For example in Ubuntu:

apt-get install python-sympy


Our “solver” will receive the precision (optional) with default value of 5⋅10-6, the function representation in a SymPy compatible format and letting x be the symbolic variable (check the docs) and the starting guess value.

import sys, math, argparse, time
from sympy import *

start_time = time.time()

# using argparse to get command line arguments
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--function", help = "Define a function")
parser.add_argument("-s", "--starting", help = "Starting point value", type = float, default = 0.0)
parser.add_argument("-p", "--precision", help = "Convergence precision", type = float, default = 5*10**(-6))
args = parser.parse_args()

sym_x = Symbol('x')
# convert the given function to a symbolic expression
  fx = S(args.function)
  sys.exit('Unable to convert function to symbolic expression.')

# calculate the differential of the function
  dfdx = diff(fx, Symbol('x'))
  sys.exit('Unable to differentiate function.')

# e is the relative error between 2 consecutive estimations of the root
e = 1
x0 = args.starting
iterations = 0

while ( e > args.precision ):
  # new root estimation
    r = x0 - fx.subs({sym_x : x0})/dfdx.subs({sym_x : x0})
  except ZeroDivisionError:
    print "Function derivative is zero. Division by zero, program will terminate."
  # relative error
  e = abs((r - x0)/r)
  iterations += 1
  x0 = r

total_time = time.time() - start_time

print 'Function:'
print 'Derivative:'
print 'Root %10.6f calculated after %d iterations'%(r, iterations)
print 'Function value at root %10.6f'%(fx.subs({sym_x : r}),)
print 'Finished in %10.6f seconds'%(total_time,)


We want to solve the equation

6x2 = 400

near the initial value 910 (the positive root).
This is the output of a test run.

root@localhost:/home/nr# ./ -f ‘6*x**2 – 400’ -s 910
6⋅x – 400
Root 8.164966 calculated after 11 iterations
Function value at root 0.000000
Finished in 0.035108 seconds
%d bloggers like this: