VincFort
VincFort

Reputation: 1180

Integral of two lists doesn't give expected results

I am trying to get the area under the curve which is defined by two lists (representing x and y coordinates). I am using the integrate function from scipy.

import numpy as np
from scipy import integrate

x= np.array([0, 207.0, 52215.0])
y= np.array([0, 1367.0, 1461.0])

integrate.simps(y, x)
# Formated result
# 3 038 124 753.3677135

My problem is that when I do the math by hand, I get a different value, which is the same value I get when I do the integral of the previous list in two steps like the following example.

# Basically integral of [1367.0, 1461.0] over [207.0, 52215.0] 
#     plus integral of [0, 1367.0] over [0, 207.0], which should give same result as above
integrate.simps(y[1:],x[1:]) + integrate.simps(y[:2],x[:2]) 
# 73 680 796.5

This is the result I am looking for. What am I missing

Upvotes: 1

Views: 177

Answers (1)

FBruzzesi
FBruzzesi

Reputation: 6495

I think you are looking for numpy.trapz:

import numpy as np

x = np.array([0, 207.0, 52215.0])
y = np.array([0, 1367.0, 1461.0])

np.trapz(y,x)
73680796.5

The trapezoidal rule is the simplest of numerical integration methods to estimate a definite integral: it approximates the curve with straight lines.

On the other hand Simpson's rule, implemented in scipy.integrate.simps, uses quadratic approximation for the function segments, each of which segment requires three points, sampled from your function.

Another answer regarding the difference between the two is here

Upvotes: 2

Related Questions