Integrate along the given axis using the composite trapezoidal rule in Python

To integrate along the given axis using the composite trapezoidal rule, use the numpy.trapz() method. The trapezoidal rule approximates the definite integral by dividing the area under a curve into trapezoids and summing their areas.

If x is provided, the integration happens in sequence along its elements. The method returns the definite integral of y as an n-dimensional array approximated along a single axis. If y is 1-dimensional, the result is a float. If n is greater than 1, the result is an (n-1) dimensional array.

Syntax

numpy.trapz(y, x=None, dx=1.0, axis=-1)

Parameters

  • y ? Input array to integrate
  • x ? Sample points corresponding to y values. If None, points are assumed evenly spaced. Default is None
  • dx ? Spacing between sample points when x is None. Default is 1.0
  • axis ? Axis along which to integrate. Default is -1

Example 1: Basic Integration

Let's start with a simple 2D array and integrate along different axes ?

import numpy as np

# Creating a 2D array
arr = np.arange(9).reshape(3, 3)

print("Our Array:")
print(arr)

print("\nDimensions:", arr.ndim)
print("Datatype:", arr.dtype)

# Integrate along axis 0 (columns)
result_axis0 = np.trapz(arr, axis=0)
print("\nIntegration along axis 0:")
print(result_axis0)

# Integrate along axis 1 (rows)
result_axis1 = np.trapz(arr, axis=1)
print("\nIntegration along axis 1:")
print(result_axis1)
Our Array:
[[0 1 2]
 [3 4 5]
 [6 7 8]]

Dimensions: 2
Datatype: int64

Integration along axis 0:
[ 6.  8. 10.]

Integration along axis 1:
[ 2.  8. 14.]

Example 2: Integration with Custom Spacing

You can specify custom spacing between points using the dx parameter ?

import numpy as np

# Simple 1D array
y_values = np.array([1, 4, 9, 16])

# Integration with default spacing (dx=1)
result_default = np.trapz(y_values)
print("Integration with dx=1:", result_default)

# Integration with custom spacing (dx=0.5)
result_custom = np.trapz(y_values, dx=0.5)
print("Integration with dx=0.5:", result_custom)

# Integration with explicit x values
x_values = np.array([0, 1, 2, 3])
result_explicit = np.trapz(y_values, x=x_values)
print("Integration with explicit x:", result_explicit)
Integration with dx=1: 19.5
Integration with dx=0.5: 9.75
Integration with explicit x: 19.5

How It Works

The trapezoidal rule approximates the integral by connecting adjacent points with straight lines and calculating the area of the resulting trapezoids. For points (x?, y?) and (x?, y?), the area is:

Area = (x? - x?) × (y? + y?) / 2

Conclusion

Use numpy.trapz() to integrate arrays using the trapezoidal rule. Specify the axis parameter for multi-dimensional arrays and dx or x for custom spacing between sample points.

Updated on: 2026-03-26T19:18:12+05:30

239 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements