pythonareaintegrate

Correctly calculate the area beneath curve using trapz and simpson in python


I used np.trapz and scipy simps to calculate an area below a curve and noticed that I might not be doing it correctly. As an example below

import numpy as np
from scipy.integrate import simps


y = np.array([1,2,3,4,5])
y1= np.array([5,5,5,5,5])

print np.trapz(y,dx=1)
print simps(y,dx=1)
print np.trapz(y1,dx=1)
print simps(y1,dx=1)

These yield

12.0
12.0
20.0
20.0

But shouldn't they yeild 15 and 25 respectively? It seems like it between to small limits?


Solution

  • You have implicitly that x = [0, 1, 2, 3, 4], remember that in programming almost everywhere and everything starts with 0. Also, usually, upper limits are not inclusive.

    For y that means a rectangle with vertices (0,0), (0,1), (4,0), and (4,1) plus a triangle with vertices (0,1), (4,5), and (4,1). The rectangle has an area of 4*1=4 and the triangle 4*4/2=8 totaling an area of 12.

    For y1 you have a rectangle with vertices (0,0), (0,5), (4,0), and (4,5), thus giving you and area of 20.