Modular Arithmetic in PyTorch
Explanation
Modular arithmetic, also known as the remainder operation, is a function that returns the remainder when dividing $a$ by $b$. In PyTorch, there are two functions available:
torch.remainder(a,b)
torch.fmod(a,b)
Both provide the remainder when $a$ is divided by $b$, but the outcomes are slightly different. If you’re curious about the specific formulas, refer to the official documents for remainder
and fmod
. Simply put, in remainder
, the sign of the remainder is the same as that of the divisor $b$, whereas in mod
, the sign of the remainder is the same as that of the dividend $a$.
>>> torch.remainder(torch.tensor([-3.1, 3.1, 1, -0.5, 2.1]), 2)
tensor([0.9000, 1.1000, 1.0000, 1.5000, 0.1000])
>>> torch.remainder(torch.tensor([-3.1, 3.1, 1, -0.5, 2.1]), -2)
tensor([-1.1000, -0.9000, -1.0000, -0.5000, -1.9000])
>>> torch.fmod(torch.tensor([-3.1, 3.1, 1, -0.5, 2.1]), 2)
tensor([-1.1000, 1.1000, 1.0000, -0.5000, 0.1000])
>>> torch.fmod(torch.tensor([-3.1, 3.1, 1, -0.5, 2.1]), -2)
tensor([-1.1000, 1.1000, 1.0000, -0.5000, 0.1000])
Environment
- OS: Windows11
- Version: Python v3.9.13, torch==1.13.1