SciPy - integrate.cumulative_trapezoid() Method



The SciPy integrate.cumulative_trapezoid() method is used to calculate the integral from the given set of points using trapezoidal rule.

In calculus theory, the trapezoidal rule is defined by calculating the numerical integration which approximate the definite integral.

Syntax

Following is the syntax of the SciPy integrate.cumulative_trapezoid() method −

cumulative_trapezoid(x)
or,
cumulative_trapezoid(y,x)

Parameters

This method accepts the following parameters −

  • x: This parameter define the array using array() function.
  • y: This parameter is used to perform the integral task.

Return value

This method returns the result in the form list(float).

Example 1

Following is the basic example that shows the usage of SciPy integrate.cumulative_trapezoid() method.

import numpy as np
from scipy.integrate import cumulative_trapezoid

x = np.array([1, 2, 3, 4])
res = cumulative_trapezoid(x)
print(res)

Output

The above code produces the following result −

[1.5 4.  7.5]

Example 2

Here, we have value of x which represents the coords point. On the other hand, the y values shows the corresponding values which find the area under the curve using cumulative_trapezoid().

import numpy as np
from scipy import integrate

y = np.array([1, 4, 9, 16])
x = np.array([1, 2, 3, 4])
res = integrate.cumulative_trapezoid(y, x)
print(res)

Output

The above code produces the following result −

[ 2.5  9.  21.5]

Example 3

In this example, the cumulative_trapezoid() accept two parameter say(y and initial) which set the value of 5 and this find the integral difference from the given set of points(y).

import numpy as np
from scipy.integrate import cumulative_trapezoid

y = np.array([1, 2, 3, 4])
res = cumulative_trapezoid(y, initial=5)
print(res)  

Output

The above code produces the following result −

[5.  1.5 4.  7.5]
The initial value is set to 5, so the cumulative integral starts from 5 and adds the area of the trapezoids to this initial value.
scipy_reference.htm
Advertisements