The torch.trunc() method truncates the decimal part of each element in a tensor, returning only the integer part of the numbers.

Truncation removes the fractional part of floating-point numbers, effectively rounding towards zero. For example, 2.7 becomes 2, and -3.9 becomes -3. Both values are near 0.
The output tensor has the same shape and data type as the input tensor. The related methods to this method are torch.ceil() and torch.floor().Syntax
torch.trunc(input, out=None)
Parameters
Argument | Description |
input (Tensor) | It represents an input tensor. |
out (Tensor, optional) | It is an output tensor to store the result. This argument is helpful if you have a pre-allocated tensor. |
Truncation of a 1D tensor
import torch tensor = torch.tensor([2.7, -2.1, 0.9, -1.9]) print(tensor) # Output: tensor([ 2.7000, -2.1000, 0.9000, -1.9000]) truncated_tensor = torch.trunc(tensor) print(truncated_tensor) # Output: tensor([ 2., -2., 0., -1.])
The above output shows that it performs operations independently on the tensor.
import torch tensor_twod = torch.tensor([[1.1, 2.2], [-1.1, -2.2]]) print(tensor_twod) # Output: tensor([[ 1.1000, 2.2000], # [-1.1000, -2.2000]]) truncated_2d_tensor = torch.trunc(tensor_twod) print(truncated_2d_tensor) # Output: tensor([[ 1., 2.], # [-1., -2.]])
Using “out” Parameter
This “out” argument is helpful when you have a pre-allocated tensor. We can create it by using the torch.empty() method. Then, we will save the truncated values inside the pre-allocated tensor.
import torch input_tensor = torch.tensor([5.7, -6.3]) output_tensor = torch.empty(2) torch.trunc(input_tensor, out=output_tensor) print(output_tensor) # Output: tensor([ 5., -6.])
Integer tensors

If you pass an input tensor filled with integer values, it will have no effect and return the output as it is, because integer values do not have anything to truncate.
import torch integer_tensor = torch.tensor([11, 19, 21], dtype=torch.int32) integer_output_tensor = torch.trunc(integer_tensor) print(integer_output_tensor) # Output: tensor([11, 19, 21], dtype=torch.int32)That’s all!