torch.round

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

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

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

注意

此函数采用“四舍六入五成双”的原则,在数字处于两个整数正中间时(例如 round(2.5) 结果为 2)来决定取整方向。

当指定 :attr:`decimals` 参数时,使用的算法类似于 NumPy 的 around 函数。该算法速度快但不够精确,并且对于低精度的数据类型容易发生溢出。例如,round(tensor([10000], dtype=torch.float16), decimals=3) 的结果为 inf

参见

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

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

  • decimals (int) – 舍入的小数位数(默认为 0)。如果 decimals 是负数,则表示小数点左侧的位数。

关键字参数

out (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.])
本页目录