Pytorch Torch Trunc
## PyTorch `torch.trunc`
The `torch.trunc` function in PyTorch is used to perform element-wise truncation on a tensor. It discards the fractional part of each element, effectively rounding the values toward zero.
---
## Function Definition
```python
torch.trunc(input, *, out=None) -> Tensor
```
### Parameters
* **`input`** *(Tensor)*: The input tensor containing the values to be truncated.
* **`out`** *(Tensor, optional)*: The alternative output tensor in which to store the result. It must have the same shape and type as the expected output.
### Return Value
* Returns a new tensor containing the truncated integer values of the elements in `input`. The data type of the returned tensor matches that of the input tensor.
---
## How Truncation Works
Unlike rounding functions such as `torch.floor` or `torch.ceil`, `torch.trunc` always rounds **toward zero**:
* For positive numbers, it behaves like `torch.floor` (e.g., `1.7` becomes `1.0`).
* For negative numbers, it behaves like `torch.ceil` (e.g., `-1.7` becomes `-1.0`).
| Input Value | `torch.trunc` | `torch.floor` | `torch.ceil` | `torch.round` |
| :--- | :--- | :--- | :--- | :--- |
| **`2.7`** | `2.0` | `2.0` | `3.0` | `3.0` |
| **`-2.7`** | `-2.0` | `-3.0` | `-2.0` | `-3.0` |
---
## Code Examples
### Example 1: Basic Truncation
This example demonstrates how to truncate a 1D tensor containing both positive and negative floating-point numbers.
```python
import torch
# Create a tensor with positive and negative floating-point numbers
x = torch.tensor([1.5, 2.7, -3.3, -0.8])
# Perform element-wise truncation
result = torch.trunc(x)
print("Original Tensor:")
print(x)
print("\nTruncated Tensor:")
print(result)
```
**Output:**
```text
Original Tensor:
tensor([ 1.5000, 2.7000, -3.3000, -0.8000])
Truncated Tensor:
tensor([ 1., 2., -3., -0.])
```
### Example 2: In-place Truncation
If you want to modify the tensor in-place without allocating new memory, you can use the in-place variant `torch.trunc_()` or pass the `out` parameter.
```python
import torch
x = torch.tensor([4.9, -5.2, 0.15])
# In-place truncation
x.trunc_()
print("In-place Truncated Tensor:")
print(x)
```
**Output:**
```text
In-place Truncated Tensor:
tensor([ 4., -5., 0.])
```
---
## Considerations and Best Practices
1. **Data Type Preservation**: `torch.trunc` preserves the data type of the input tensor. If the input is a float tensor (e.g., `torch.float32`), the output will also be a float tensor, even though the values are integers (e.g., `1.0` instead of `1`).
2. **Integer Inputs**: If you pass an integer tensor to `torch.trunc`, the operation is a no-op (no change) and returns the original tensor values, as integers have no fractional parts.
3. **Performance**: For memory-constrained operations on large tensors, prefer using the in-place version `input.trunc_()` to avoid unnecessary memory allocations.
YouTip