PyTorch torch.trapz function


Pytorch torch 参考手册Pytorch torch Reference Manual

torch.trapzis a function in PyTorch used to compute trapezoidal integration, and istorch.trapezoidan alias of the function, both have the same functionality.

Function Definition

torch.trapz(y, x, dx)

Parameter Description

  • y: Function values to be integrated
  • x: Values of the integration variable (optional)
  • dx: Sampling spacing (used when x is not provided)

Usage Examples

Example

import torch

# Perform trapezoidal integration using dx
y = torch.tensor([1.0, 2.0, 3.0, 4.0])

# dx=1.0 means uniform sampling spacing
result = torch.trapz(y, dx=1.0)

print("Trapezoidal integration result (trapz):", result)

# Equivalent to trapezoid
result2 = torch.trapezoid(y, dx=1.0)
print("Trapezoidal integration result (trapezoid):", result2)

The output result is:

梯形积分结果 (trapz): tensor(7.5000)
梯形积分结果 (trapezoid): tensor(7.5000)

Pytorch torch 参考手册Pytorch torch Reference Manual

Other Extensions