Calculating the area under a curve given a set of coordinates, without knowing the function

user1640255 picture user1640255 · Nov 10, 2012 · Viewed 104.2k times · Source

I have one list of 100 numbers as height for Y axis, and as length for X axis: 1 to 100 with a constant step of 5. I need to calculate the Area that it is included by the curve of the (x,y) points, and the X axis, using rectangles and Scipy. Do I have to find the function of this curve? or not? ... almost all the examples I have read are about a specific equation for the Y axis. In my case there is no equation, just data from a list. The classic solution is to add or the Y points and multiple by the step X distance... using Scipy any idea?

Please, can anyone recommend any book which focusing on numerical (finite elementary) methods, using Scipy and Numpy? ...

Answer

Warren Weckesser picture Warren Weckesser · Nov 10, 2012

The numpy and scipy libraries include the composite trapezoidal (numpy.trapz) and Simpson's (scipy.integrate.simps) rules.

Here's a simple example. In both trapz and simps, the argument dx=5 indicates that the spacing of the data along the x axis is 5 units.

from __future__ import print_function

import numpy as np
from scipy.integrate import simps
from numpy import trapz


# The y values.  A numpy array is used here,
# but a python list could also be used.
y = np.array([5, 20, 4, 18, 19, 18, 7, 4])

# Compute the area using the composite trapezoidal rule.
area = trapz(y, dx=5)
print("area =", area)

# Compute the area using the composite Simpson's rule.
area = simps(y, dx=5)
print("area =", area)

Output:

area = 452.5
area = 460.0