torch.round¶
- torch.round(input, *, decimals=0, out=None) → Tensor
将
input
的元素四舍五入到最接近的整数。对于整数输入,遵循数组 API 的约定,返回输入张量的副本。输出类型与输入的 dtype 相同。
注意
此函数实现了“四舍六入五成双”的规则,当数字距离两个整数相等时(例如,round(2.5)等于 2)。
当指定了 :attr:`decimals` 参数时,使用的算法类似于 NumPy 的 around。此算法速度快但不够精确,对于低精度 dtype,它很容易溢出。例如,round(tensor([10000], dtype=torch.float16), decimals=3)是无穷大。
参见
torch.ceil()
向上取整。torch.floor()
向下取整。torch.trunc()
向零取整。- 参数:
input (Tensor) – 输入张量。
小数位数(整数)- 需要四舍五入到的小数位数(默认:0)。如果小数位数为负数,则指定小数点左边的位数。
- 关键字参数:
输出(张量,可选)- 输出张量。
示例:
>>> 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.])