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 theyvalues. This is an optional parameter.dx: This is the spacing provided between the sample points whenxis None. The default value is1. 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 integratedmyarray = np.array([1,2,3])# creating the sample pointsx = np.array([4, 6, 8])# implementing the numpy.trapz() functionintarray = np.trapz(myarray, x)print(intarray)
Explanation
- Line 1: We import the
numpymodule. - Line 4: We create an input array
myarrayusing thearray()function. - Line 7: We create an array
xcontaining the sample points using thearray()function. - Line 10: We implement the
numpy.trapz()function on the arrays and assign the result to a variableintarray. - Line 12: We print the variable
intarray.