评价此页

torch.round#

torch.round(input, *, decimals=0, out=None) Tensor#

input的元素四舍五入到最近的整数。

对于整数输入,遵循 array-api 的约定,返回输入张量的副本。输出的返回类型与输入的 dtype 相同。

注意

此函数实现“四舍五入到偶数”的规则,以打破在数字与两个整数距离相等时(例如,round(2.5) 为 2)的平局。

当指定 :attr:`decimals` 参数时,使用的算法类似于 NumPy 的 around。此算法速度快但精度不高,并且很容易在低精度 dtype 上溢出。例如,round(tensor([10000], dtype=torch.float16), decimals=3)inf

另请参阅

torch.ceil(),向上取整。torch.floor(),向下取整。torch.trunc(),向零取整。

参数
  • input (Tensor) – 输入张量。

  • decimals (int) – 要四舍五入的小数位数(默认值:0)。如果 decimals 为负数,则指定小数点左边的位数。

关键字参数

out (Tensor, optional) – 输出张量。

示例

>>> 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.])