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 simpsfrom numpy import trapzimport numpy as npdef function(x):return x**2x = np.arange(1,10,0.1)y = function(x)print xprint 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.099666667area from Trapezoidal rule: 323.1145area 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 |
