scipy.integrate.cumulative_trapezoid vs. Matlab cumtrapz
The 0-based indexing of Python / Numpy versus the 1-based indexing of Matlab is perhaps the most obvious difference when working between the languages. Other, more subtle defaults come into play and may not be immediately caught within functions except by manual checks.
In atmospheric science among other fields, cumulative integration implemented as cumulative trapezoidal numerical integration is a common function named “cumtrapz”.
Distinctive behavior between Matlab
cumtrapz
and
scipy.integrate.cumulative_trapezoid
might not be immediately caught inside a function, although it’s obvious when manually checking.
Specifically, SciPy scipy.integrate.cumulative_trapezoid needs the initial=0
argument to match Matlab.
Let’s show this by example:
Example: given input:
x = [-2.5, 5, 10]
Matlab (or GNU Octave) outputs:
y = cumtrapz(x)
[0, 1.25, 8.75]
scipy.integrate.cumulative_trapezoid output one element less than the input by default:
scipy.integrate.cumulative_trapezoid(x)
[1.25, 8.75]
To match Matlab output from SciPy, add the initial=0
argument:
scipy.integrate.cumulative_trapezoid(x, initial=0)
[0, 1.25, 8.75]