PyTorch torch.trapezoid function
PyTorch torch reference manual
torch.trapezoid is a function in PyTorch used to compute the trapezoidal integral. It uses the trapezoidal rule to numerically integrate a given function.
Function definition
torch.trapezoid(y, x, dx)
Parameter Description
y: The function values to integratex: The values of the integration variable (optional)dx: The sampling interval (used when x is not provided)
Usage examples
Example
import
torch
Trapezoidal integration using dx
y
=
torch.
tensor
(
[
1.0
,
2.0
,
3.0
,
4.0
]
)
dx=1.0 means a uniform sampling interval
result
=
torch.
trapezoid
(
y
,
dx
=
1.0
)
(
"Trapezoidal integration 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
)
(
"Integration result using x coordinates:"
,
result2
)
The output is:
梯形积分结果: tensor(7.5000)
使用 x 坐标的积分结果: tensor(1.2500)