Calculate the area under a curve in python
Actually, we have a similar polyline curve I want to find the approximating function, and calculate the area under it. I do not want suggestive answers, like, look there is math or scipy, but links to where there is a similar implementation, or at least. Similar, I'm a beginner, and I can't implement this on my own.
1
1 answers
You can use numpy. trapz()
Example using Numpy:
import numpy as np
from scipy.integrate import simps
from numpy import trapz
x = np.linspace(0, 5, 21)
y = np.pi / np.exp(x)
# dx - растояние между соседними X координатами
area = trapz(y, dx=5/20)
Result:
In [19]: simps(y, dx=5/20)
Out[19]: 3.1204919857832971
In [20]: trapz(y, dx=5/20)
Out[20]: 3.1366600769000623
Chart:
In [21]: plt.grid()
In [22]: plt.plot(x, y)
Out[22]: [<matplotlib.lines.Line2D at 0xd5a5c50>]
In [23]: plt.grid()
In [24]: plt.savefig('c:/temp/a.png')
1
Author: MaxU, 2017-10-17 15:52:24