torch.round¶
- torch.round(input, *, decimals=0, out=None) Tensor ¶
將
input
中的元素四捨五入到最接近的整數。對於整數輸入,遵循 array-api 慣例,回傳輸入張量的副本。輸出 (output) 的回傳型別與輸入 (input) 的 dtype 相同。
注意
此函數實現「四捨五入到最接近的偶數」 (round half to even) 的規則,以打破數字與兩個整數等距時的平手局面(例如 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, 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.])