NumPy trapezoid()

The numpy.trapezoid() function computes the definite integral of an array using the composite trapezoidal rule. It integrates along a specified axis and can work with evenly or unevenly spaced sample points.

Syntax

</>
Copy
numpy.trapezoid(y, x=None, dx=1.0, axis=-1)

Parameters

ParameterTypeDescription
yarray_likeInput array to integrate.
xarray_like, optionalSample points corresponding to y values. If not provided, the spacing is assumed to be uniform.
dxscalar, optionalThe spacing between sample points when x is not provided. Default is 1.0.
axisint, optionalAxis along which to integrate. Default is -1 (last axis).

Return Value

Returns a float if the input y is 1D, otherwise returns an array with one dimension reduced by integration.


Examples

1. Integrating a 1D Function with Evenly Spaced Points

Here, we compute the integral of a function using evenly spaced sample points.

</>
Copy
import numpy as np

# Define the y values (function values)
y = np.array([1, 2, 3, 4, 5])

# Compute the integral using the trapezoidal rule with default dx=1
result = np.trapezoid(y)

# Print the result
print("Integral of y using the trapezoidal rule:", result)

Output:

Integral of y using the trapezoidal rule: 10.0

2. Integrating with Unevenly Spaced Sample Points

We specify the x values explicitly to integrate along unevenly spaced points.

</>
Copy
import numpy as np

# Define y values
y = np.array([1, 2, 3, 4, 5])

# Define corresponding x values (unevenly spaced)
x = np.array([0, 1, 1.5, 3, 4])

# Compute the integral
result = np.trapezoid(y, x=x)

# Print the result
print("Integral with unevenly spaced x values:", result)

Output:

Integral with unevenly spaced x values: 10.75

3. Using a Custom dx Value

Setting a custom spacing between points instead of using the default dx=1.

</>
Copy
import numpy as np

# Define y values
y = np.array([1, 3, 7, 9])

# Compute the integral using a dx of 2
result = np.trapezoid(y, dx=2)

# Print the result
print("Integral with dx=2:", result)

Output:

Integral with dx=2: 30.0

4. Integrating Along a Specific Axis

Computing the integral along a specified axis in a multidimensional array.

</>
Copy
import numpy as np

# Define a 2D array
y = np.array([[1, 2, 3], [4, 5, 6]])

# Integrate along axis 0 (columns)
result_axis0 = np.trapezoid(y, axis=0)

# Integrate along axis 1 (rows)
result_axis1 = np.trapezoid(y, axis=1)

# Print the results
print("Integral along axis 0:", result_axis0)
print("Integral along axis 1:", result_axis1)

Output:

Integral along axis 0: [2.5 3.5 4.5]
Integral along axis 1: [4. 10.]

When integrating along axis=0, each column is integrated separately, reducing the number of rows. When integrating along axis=1, each row is integrated, reducing the number of columns.