Pytorch Torch Reciprocal
## PyTorch `torch.reciprocal`
The `torch.reciprocal` function in PyTorch is used to compute the element-wise reciprocal (multiplicative inverse) of a given input tensor.
Mathematically, for each element $x$ in the input tensor, it computes:
$$y_i = \frac{1}{x_i}$$
---
## Function Definition
```python
torch.reciprocal(input, *, out=None) -> Tensor
```
### Parameters
| Parameter | Type | Description |
| :--- | :--- | :--- |
| `input` | *Tensor* | The input tensor containing the values to invert. |
| `out` | *Tensor, optional* | The output tensor where the result will be written. |
### Return Value
* Returns a new tensor containing the element-wise reciprocal of the `input` tensor.
---
## Code Examples
### Example 1: Basic Usage
This example demonstrates how to compute the reciprocal of a 1D tensor containing floating-point numbers.
```python
import torch
# Create a 1D tensor
x = torch.tensor([1.0, 2.0, 4.0])
# Compute the element-wise reciprocal
result = torch.reciprocal(x)
print("Input Tensor:")
print(x)
print("\nReciprocal Result:")
print(result)
```
**Output:**
```text
Input Tensor:
tensor([1., 2., 4.])
Reciprocal Result:
tensor([1.0000, 0.5000, 0.2500])
```
### Example 2: In-place Operation
PyTorch also provides an in-place version of this function: `torch.reciprocal_` (with a trailing underscore) or the tensor method `.reciprocal_()`. This modifies the original tensor directly without allocating new memory.
```python
import torch
# Create a tensor
x = torch.tensor([5.0, 10.0, 20.0])
# Perform in-place reciprocal
x.reciprocal_()
print("In-place Result:")
print(x)
```
**Output:**
```text
In-place Result:
tensor([0.2000, 0.1000, 0.0500])
```
---
## Important Considerations
### 1. Division by Zero
If the input tensor contains `0` or `0.0`, computing the reciprocal will result in positive infinity (`inf`), negative infinity (`-inf`), or `NaN` (Not a Number) depending on the sign and data type.
```python
import torch
x = torch.tensor([0.0, -0.0])
result = torch.reciprocal(x)
print(result)
# Output: tensor([inf, -inf])
```
### 2. Integer Data Types
`torch.reciprocal` requires floating-point or complex data types. If you pass an integer tensor, PyTorch will raise a `RuntimeError`. You must cast integer tensors to float before applying the function.
```python
import torch
x = torch.tensor([1, 2, 4])
# This will raise a RuntimeError:
# result = torch.reciprocal(x)
# Correct approach: Cast to float first
result = torch.reciprocal(x.to(torch.float32))
print(result)
# Output: tensor([1.0000, 0.5000, 0.2500])
```
YouTip