5

I have a list of y values and a list of x values. I would like to find the area under the curve defined by these points. I have found a couple of solutions to this problem for x values with even spacing:

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

2) Using scipy to perform discrete integration of the sample

But neither of these works when the x values are not evenly spaced.

For example:

>>> from scipy.integrate import simps
>>> y = np.array([1,1,1,1])
>>> x = np.array([0,5,20,30])
>>> simps(y,x)
-inf

Of course, using x = np.array([0,10,20,30]) in the above code returns 30.0, as expected.

Can anyone suggest a way to find the area under a curve with uneven x-spacing?

Community
  • 1
  • 1
user3390452
  • 51
  • 1
  • 2

1 Answers1

0

I'd just go for a simple trapezoidal rule:

import numpy as np

x = np.array([0,5,20,30])
y = np.array([1,1,1,1])

s = np.sum((x[1:] - x[:-1]) * (y[1:] + y[:-1]) / 2)
# same as
# s = 0.0
# for k in range(len(x) - 1):
#    s += (x[k+1] - x[k]) * (y[k+1] + y[k]) / 2

print(s)
30.0
Nico Schlömer
  • 53,797
  • 27
  • 201
  • 249