The torch.div() method performs element-wise division of tensors. It divides each element of the input tensor by a scalar or another tensor, returning a new tensor with the divided values.

Here is the basic formula: output_tensor = input_tensor / other_tensor
Syntax
torch.div(input, other, rounding_mode=None, out=None)
Parameters
Argument | Description |
input (Tensor) | It is a numerator tensor. |
other (Tensor or Scalar) | It is the denominator, which can be either a tensor of compatible shape or a scalar. |
rounding_mode (str, optional) | It specifies the division rounding behaviour.
|
out (Tensor) | It is a pre-allocated tensor to store the result in. |
Division by a scalar
Let’s define a 1D tensor and divide that tensor by a scalar value.
import torch input = torch.tensor([22.0, 18.0, 10.0]) scalar = 2 division_tensor = torch.div(input, scalar) print(division_tensor) # Output: tensor([11., 9., 5.])
In this code, you can see that 22.0 is divided by 2, which equals 11. 18.0 is divided by 2, which is 9, and 10.0 is divided by 2, which is equal to 5.
Element-wise division of tensors

Let’s divide a tensor of the same size by another tensor of the same size.
import torch input = torch.tensor([10.0, 20.0, 30.0]) other = torch.tensor([1.0, 4.0, 5.0]) division_tensor = torch.div(input, other) print(division_tensor) # Output: tensor([10., 5., 6.])
Each element of the input tensor is divided by the corresponding element of the other tensor.
Rounding modes
Let’s explore different rounding modes and control the division behavior with rounding_mode.
import torch input = torch.tensor([11.0, 23.0, 35.0]) other = torch.tensor([1.0, 4.0, 5.0]) division_tensor = torch.div(input, other) print(division_tensor) # Output: tensor([11.0000, 5.7500, 7.0000]) # Standard division result = torch.div(input, other) print(result) # Output: tensor([11.0000, 5.7500, 7.0000]) # Truncated division result_trunc = torch.div(input, other, rounding_mode="trunc") print(result_trunc) # Output: tensor([11., 5., 7.]) # Floor division result_floor = torch.div(input, other, rounding_mode="floor") print(result_floor) # Output: tensor([11., 5., 7.])
In the above code, we demonstrated the element-wise division of two tensors using torch.div().
By default, it performs floating-point division, but with rounding_mode=’trunc’ or ‘floor’, it returns truncated or floor-rounded integer results.
For positive inputs, trunc and floor give the same output, but they differ for negative values.
That’s all!