What is the numpy.trapz() function in NumPy?

Overview

The numpy.trapz() function in NumPy is used to perform integration along a given axis by using the composite trapezoidal rule.

Syntax

numpy.trapz(y, x=None, dx=1.0, axis=- 1)
Syntax for the numpy.trapz() function

Parameters

The numpy.trapz() function takes the following parameter values:

  • y: This is the input array to be integrated. This is a required parameter.
  • x: This is the given sample points that corresponds to the y values. This is an optional parameter.
  • dx: This is the spacing provided between the sample points when x is None. The default value is 1. This is an optional parameter.
  • axis: This represents the angle along which the integration is done.

Example

import numpy as np
# creating the input array to be integrated
myarray = np.array([1,2,3])
# creating the sample points
x = np.array([4, 6, 8])
# implementing the numpy.trapz() function
intarray = np.trapz(myarray, x)
print(intarray)

Explanation

  • Line 1: We import the numpy module.
  • Line 4: We create an input array myarray using the array() function.
  • Line 7: We create an array x containing the sample points using the array() function.
  • Line 10: We implement the numpy.trapz() function on the arrays and assign the result to a variable intarray.
  • Line 12: We print the variable intarray.

 

Free Resources