|
| 1 | +--- |
| 2 | +Title: '.fmod()' |
| 3 | +Description: 'Returns the element-wise remainder of division, keeping the same sign as the dividend.' |
| 4 | +Subjects: |
| 5 | + - 'Computer Science' |
| 6 | + - 'Machine Learning' |
| 7 | +Tags: |
| 8 | + - 'Functions' |
| 9 | + - 'Machine Learning' |
| 10 | + - 'Python' |
| 11 | + - 'Tensor' |
| 12 | +CatalogContent: |
| 13 | + - 'intro-to-py-torch-and-neural-networks' |
| 14 | + - 'paths/computer-science' |
| 15 | +--- |
| 16 | + |
| 17 | +In PyTorch, the **`.fmod()`** method performs element-wise modulo operation on a [tensor](https://www.codecademy.com/resources/docs/pytorch/tensors) and returns a new tensor containing the remainders. The sign of the result always matches the sign of the dividend (the input tensor elements). |
| 18 | + |
| 19 | +Mathematically, for each element in the input tensor, the operation follows: |
| 20 | + |
| 21 | +$$ |
| 22 | +\text{result} = \text{input} - (\text{divisor} \times \text{trunc}(\text{input}/\text{divisor})) |
| 23 | +$$ |
| 24 | + |
| 25 | +Here, `trunc` means truncation toward zero (i.e., rounding towards 0). |
| 26 | + |
| 27 | +## Syntax |
| 28 | + |
| 29 | +```pseudo |
| 30 | +torch.fmod(input, other, *, out=None) -> Tensor |
| 31 | +``` |
| 32 | + |
| 33 | +**Parameters:** |
| 34 | + |
| 35 | +- `input` (Tensor): Dividend tensor. |
| 36 | +- `other` (Tensor or Scalar): Divisor, can be a tensor (broadcastable with input) or a scalar. |
| 37 | +- `out` (Tensor, optional): Output tensor to store the result. |
| 38 | + |
| 39 | +**Return value:** |
| 40 | + |
| 41 | +- Returns a tensor containing the element-wise remainder of division, where the result has the same sign as `input`. |
| 42 | + |
| 43 | +## Example |
| 44 | + |
| 45 | +This example demonstrates the usage of the `.fmod()` function: |
| 46 | + |
| 47 | +```py |
| 48 | +import torch |
| 49 | + |
| 50 | +# Scalar divisor |
| 51 | +x = torch.tensor([5.0, -3.5, 2.1]) |
| 52 | +result = x.fmod(2) # or torch.fmod(x, 2) |
| 53 | +print(result) |
| 54 | + |
| 55 | +# Tensor divisor |
| 56 | +x = torch.tensor([5.0, -3.5, 2.1]) |
| 57 | +y = torch.tensor([3.0, 2.0, 1.5]) |
| 58 | +result = x.fmod(y) |
| 59 | +print(result) |
| 60 | + |
| 61 | +# In-place operation |
| 62 | +x = torch.tensor([5.0, -3.5, 2.1]) |
| 63 | +x.fmod_(2) # x is modified directly |
| 64 | +print(x) |
| 65 | +``` |
| 66 | + |
| 67 | +The output of this code is: |
| 68 | + |
| 69 | +```shell |
| 70 | +tensor([ 1.0000, -1.5000, 0.1000]) |
| 71 | +tensor([ 2.0000, -1.5000, 0.6000]) |
| 72 | +tensor([ 1.0000, -1.5000, 0.1000]) |
| 73 | +``` |
0 commit comments