How to perform a numerical integration using python ?

Published: February 09, 2019

DMCA.com Protection Status

To do a numerical integration with python, a solution is to use the trapezoidal rule from numpy numpy.trapz or the Simpson's rule from scipy scipy.integrate.simps:

Note: to do an integration from a known function see the scipy method called quad

from scipy.integrate import simps
from numpy import trapz

import numpy as np

def function(x):
    return x**2

x = np.arange(1,10,0.1)
y = function(x)

print x
print y

# primitive :

print "area: ", 1.0 / 3.0 * ( x[len(x)-1]**3 - x[0]**3 )

# using Trapezoidal rule:

area = trapz(y,x)
print 'area: ',area

# using Simpson's rule:

area = simps(y,x)
print 'area: ',area

returns:

area from the primitive:  323.099666667
area from Trapezoidal rule:  323.1145
area from Simpson's rule:  323.099833333

References