torch.round¶
- torch.round(input, *, decimals=0, out=None) 张量 ¶
将
input
的元素四舍五入到最近的整数。对于整数输入,遵循返回输入张量的副本的数组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()
,向零取整。- Parameters
- Keyword Arguments
输出 (张量, 可选) – 输出张量。
示例:
>>> torch.round(torch.tensor((4.7, -2.3, 9.1, -7.7))) tensor([ 5., -2., 9., -8.]) >>> # 与两个整数等距的值会向最近的偶数值舍入(零被视为偶数) >>> torch.round(torch.tensor([-0.5, 0.5, 1.5, 2.5])) tensor([-0., 0., 2., 2.]) >>> # 正的decimals参数会舍入到该小数位 >>> torch.round(torch.tensor([0.1234567]), decimals=3) tensor([0.1230]) >>> # 负的decimals参数会舍入到小数点左侧 >>> torch.round(torch.tensor([1200.1234567]), decimals=-3) tensor([1000.])