Tian
Tian

Reputation: 970

How to decide between scipy.integrate.simps or numpy.trapz?

I have a set of points, of which when I plot I get the graph below. I would like to find the area under the graph, however I am not sure whether scipy.integrate.simps or numpy.trapz is more suitable.

Could someone advice me on the mathematical background between the two functions and thus the conclusion on which function is more accurate?

enter image description here

Upvotes: 3

Views: 11831

Answers (1)

Ryan Soklaski
Ryan Soklaski

Reputation: 550

The trapezoidal rule is the simplest of numerical integration methods. In effect, it estimates the area under a curve by approximating the curve with straight line segments, which only requires two points for each segment. Simpson's rule uses quadratic curves to approximate the function segments instead, each of which requires three points, sampled from your function, to approximate a given segment.

So what is the error associated with using these numerical methods as approximations to an analytical integral?

The error associated with the trapezoidal rule, to leading order, is proportional to h^2[f'(a) - f'(b)]. h is the spacing between sampled points in your function; f'(a) and f'(b) are the first derivative of your function at the beginning and end of the sampling domain.

The error through Simpson's rule, on the other hand, is proportional to h^4[f'''(a) - f'''(b)]. f''' is the third-order derivative in your function.

h is typically small, so h^4 is typically much smaller than h^2!

TLDR: Simpson's rule typically gives far superior results for numerical integration, compared to the trapezoidal rule, with basically no additional computational cost.

Upvotes: 16

Related Questions