# Integrate along axis 0 using the composite trapezoidal rule in Python

PythonNumpyServer Side ProgrammingProgramming

To integrate along the given axis using the composite trapezoidal rule, use the numpy.trapz() method. If x is provided, the integration happens in sequence along its elements - they are not sorted. The method returns the definite integral of ‘y’ = n-dimensional array as approximated along a single axis by the trapezoidal rule. If ‘y’ is a 1-dimensional array, then the result is a float. If ‘n’ is greater than 1, then the result is an ‘n-1’ dimensional array.

The 1st parameter, y is the input array to integrate. The 2nd parameter, x is the sample points corresponding to the y values. If x is None, the sample points are assumed to be evenly spaced dx apart. The default is None. The 3rd parameter, dx is the spacing between sample points when x is None. The default is 1. The 4th parameter, axis is the axis along which to integrate.

## Steps

At first, import the required library −

import numpy as np

Creating a numpy array using the arange() method. We have added elements of int type −

arr = np.arange(9).reshape(3, 3)


Display the array −

print("Our Array...\n",arr)

Check the Dimensions −

print("\nDimensions of our Array...\n",arr.ndim)


Get the Datatype −

print("\nDatatype of our Array object...\n",arr.dtype)

To integrate along the given axis using the composite trapezoidal rule, use the numpy.trapz() method −

print("\nResult (trapz)...\n",np.trapz(arr, axis = 0))


## Example

import numpy as np

# Creating a numpy array using the arange() method
# We have added elements of int type
arr = np.arange(9).reshape(3, 3)

# Display the array
print("Our Array...\n",arr)

# Check the Dimensions
print("\nDimensions of our Array...\n",arr.ndim)

# Get the Datatype
print("\nDatatype of our Array object...\n",arr.dtype)

# To integrate along the given axis using the composite trapezoidal rule, use the numpy.trapz() method
print("\nResult (trapz)...\n",np.trapz(arr, axis = 0))

## Output

Our Array...
[[0 1 2]
[3 4 5]
[6 7 8]]

Dimensions of our Array...
2

Datatype of our Array object...
int64

Result (trapz)...
[ 6. 8. 10.]
Updated on 25-Feb-2022 04:55:00