YouTip LogoYouTip

Pytorch Torch Ceil

## PyTorch `torch.ceil` Function The `torch.ceil` function in PyTorch is used to perform element-wise ceiling operations on an input tensor. It rounds each element up to the smallest integer greater than or equal to that element. --- ### Function Definition ```python torch.ceil(input, *, out=None) -> Tensor ``` #### Parameters: * **`input` (Tensor)**: The input tensor containing floating-point or integer elements. * **`out` (Tensor, optional)**: The alternative output tensor where the result will be written. It must have the same shape and type as the expected output. #### Returns: * A new tensor containing the ceiling values of each element in `input`. The returned tensor has the same data type as the input. --- ### Usage Examples #### Basic Example The following example demonstrates how to use `torch.ceil` on a 1D tensor containing positive and negative floating-point numbers. ```python import torch # Create a 1D tensor with floating-point values x = torch.tensor([1.1, 2.5, 3.7, -1.2]) # Apply the ceiling function result = torch.ceil(x) print("Input Tensor:") print(x) print("\nOutput Tensor (Ceil):") print(result) ``` **Output:** ```text Input Tensor: tensor([ 1.1000, 2.5000, 3.7000, -1.2000]) Output Tensor (Ceil): tensor([ 2., 3., 4., -1.]) ``` #### In-place Operation If you want to modify the tensor in-place without allocating new memory, you can use `torch.ceil_()` or pass the tensor to the `out` parameter. ```python import torch x = torch.tensor([0.3, 1.8, -2.9]) # In-place ceiling operation x.ceil_() print("In-place Result:") print(x) ``` **Output:** ```text In-place Result: tensor([ 1., 2., -2.]) ``` --- ### Key Considerations 1. **Behavior with Negative Numbers**: For negative numbers, rounding "up" means moving closer to zero. For example, the ceiling of `-1.2` is `-1.0`. 2. **Integer Inputs**: If the input tensor contains integers, the ceiling operation has no effect because the values are already integers. However, PyTorch typically expects floating-point types (`torch.float32`, `torch.float64`, etc.) for mathematical operations like `ceil`. 3. **NaN and Infinity**: `torch.ceil` preserves special values like `NaN` (Not a Number), `inf` (Positive Infinity), and `-inf` (Negative Infinity).
← Pytorch Torch Cholesky_SolvePytorch Torch Cat β†’