# Integrate using the composite trapezoidal rule and set the sample points to the y values 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 libraries −

import numpy as np

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

arr = np.array([20, 35])


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, x = [55, 80]))


## Example

import numpy as np

# Creating a numpy array using the array() method
# We have added elements of int type
arr = np.array([20, 35])

# 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, x = [55, 80]))

## Output

Our Array...
[20 35]

Dimensions of our Array...
1

Datatype of our Array object...
int64

Result (trapz)...
687.5
Updated on 28-Feb-2022 09:16:36