PyTorch .fmod()
Anonymous contributor
Published Aug 29, 2025
Contribute to Docs
In PyTorch, the .fmod() method performs element-wise modulo operation on a tensor and returns a new tensor containing the remainders. The sign of the result always matches the sign of the dividend (the input tensor elements).
Mathematically, for each element in the input tensor, the operation follows:
$$ \text{result} = \text{input} - (\text{divisor} \times \text{trunc}(\text{input}/\text{divisor})) $$
Here, trunc means truncation toward zero (i.e., rounding towards 0).
Syntax
torch.fmod(input, other, *, out=None) -> Tensor
Parameters:
input(Tensor): Dividend tensor.other(Tensor or Scalar): Divisor, can be a tensor (broadcastable with input) or a scalar.out(Tensor, optional): Output tensor to store the result.
Return value:
- Returns a tensor containing the element-wise remainder of division, where the result has the same sign as
input.
Example
This example demonstrates the usage of the .fmod() function:
import torch# Scalar divisorx = torch.tensor([5.0, -3.5, 2.1])result = x.fmod(2) # or torch.fmod(x, 2)print(result)# Tensor divisorx = torch.tensor([5.0, -3.5, 2.1])y = torch.tensor([3.0, 2.0, 1.5])result = x.fmod(y)print(result)# In-place operationx = torch.tensor([5.0, -3.5, 2.1])x.fmod_(2) # x is modified directlyprint(x)
The output of this code is:
tensor([ 1.0000, -1.5000, 0.1000])tensor([ 2.0000, -1.5000, 0.6000])tensor([ 1.0000, -1.5000, 0.1000])
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn PyTorch on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn how to use PyTorch to build, train, and test artificial neural networks in this course.
- Intermediate.3 hours