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
Links | Site |
---|---|
Calculating the area under a curve given a set of coordinates, without knowing the function | stackoverflow |
How do I integrate two 1-D data arrays in Python? | stackoverflow |
numpy.trapz | numpy |
scipy.integrate.simps | scipy |
Calculer une intégrale simple avec python | science-emergence |