PyTorch torch.trapezoid Function


Pytorch torch 参考手册PyTorch torch Reference Manual

torch.trapezoidis a function in PyTorch used to compute trapezoidal integrals. This function uses the trapezoidal rule to perform numerical integration of a given function.

Function Definition

torch.trapezoid(y, x, dx)

Parameter Description

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

Usage Examples

Example

import torch

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

# dx=1.0 indicates uniform sampling spacing
result = torch.trapezoid(y, dx=1.0)

print("Trapezoidal integral result:", result)

# Integrate using x coordinates
x = torch.tensor([0.0, 0.5, 1.0, 1.5])
y2 = torch.tensor([0.0, 0.5, 1.0, 1.5])

result2 = torch.trapezoid(y2, x)
print("Integral result using x coordinates:", result2)

The output result is:

梯形积分结果: tensor(7.5000)
使用 x 坐标的积分结果: tensor(1.2500)

Pytorch torch 参考手册PyTorch torch Reference Manual

Other Extensions