快捷鍵

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(),向零捨入。

參數
  • 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.])

文件

存取 PyTorch 的完整開發人員文件

檢視文件

教學

取得初學者和進階開發人員的深入教學

檢視教學

資源

尋找開發資源並獲得您問題的解答

檢視資源