PyTorch torch.trapz 函数
torch.trapz 是 PyTorch 中用于计算梯形积分的函数,是 torch.trapezoid 函数的别名,两者功能相同。
函数定义
torch.trapz(y, x, dx)
参数说明
y: 要积分的函数值x: 积分变量的值(可选)dx: 采样间距(当 x 不提供时使用)
使用示例
实例
import torch
# 使用 dx 进行梯形积分
y = torch.tensor([1.0, 2.0, 3.0, 4.0])
# dx=1.0 表示均匀采样间距
result = torch.trapz(y, dx=1.0)
print("梯形积分结果 (trapz):", result)
# 与 trapezoid 等效
result2 = torch.trapezoid(y, dx=1.0)
print("梯形积分结果 (trapezoid):", result2)
# 使用 dx 进行梯形积分
y = torch.tensor([1.0, 2.0, 3.0, 4.0])
# dx=1.0 表示均匀采样间距
result = torch.trapz(y, dx=1.0)
print("梯形积分结果 (trapz):", result)
# 与 trapezoid 等效
result2 = torch.trapezoid(y, dx=1.0)
print("梯形积分结果 (trapezoid):", result2)
输出结果为:
梯形积分结果 (trapz): tensor(7.5000) 梯形积分结果 (trapezoid): tensor(7.5000)

Pytorch torch 参考手册