torch.round¶
- torch.round(input, *, decimals=0, out=None) Tensor ¶
将
input
中的元素舍入到最接近的整数。对于整数输入,遵循 array-api 约定,返回输入 tensor 的副本。输出的返回类型与输入的 dtype 相同。
注意
此函数实现“舍半取偶”规则来处理当一个数与两个整数等距时的情况(例如 round(2.5) 为 2)。
当指定了 :attr:`decimals` 参数时,使用的算法类似于 NumPy 的 around。此算法速度快但不精确,对于低精度 dtypes 容易溢出。例如,round(tensor([10000], dtype=torch.float16), decimals=3) 的结果是 inf。
另请参阅
torch.ceil()
,向上舍入。torch.floor()
,向下舍入。torch.trunc()
,向零舍入。- 参数
- 关键字参数
out (Tensor, 可选) – 输出 tensor。
示例
>>> torch.round(torch.tensor((4.7, -2.3, 9.1, -7.7))) tensor([ 5., -2., 9., -8.]) >>> # Values equidistant from two integers are rounded towards the >>> # the nearest even value (zero is treated as even) >>> torch.round(torch.tensor([-0.5, 0.5, 1.5, 2.5])) tensor([-0., 0., 2., 2.]) >>> # A positive decimals argument rounds to the to that decimal place >>> torch.round(torch.tensor([0.1234567]), decimals=3) tensor([0.1230]) >>> # A negative decimals argument rounds to the left of the decimal >>> torch.round(torch.tensor([1200.1234567]), decimals=-3) tensor([1000.])