burn_tensor/tensor/api/
trunc.rs

1use crate::{Float, Tensor, TensorPrimitive, backend::Backend};
2
3impl<B, const D: usize> Tensor<B, D, Float>
4where
5    B: Backend,
6{
7    /// Truncates the tensor element-wise, rounding toward zero.
8    ///
9    /// This function returns a new tensor with the same shape as the input tensor,
10    /// where each element is truncated toward zero. For positive values, this is
11    /// equivalent to floor, and for negative values, it's equivalent to ceil.
12    ///
13    /// # Special Cases (IEEE 754 compliant)
14    ///
15    /// - `trunc(±0)` returns ±0 (preserves sign of zero)
16    /// - `trunc(±∞)` returns ±∞
17    /// - `trunc(NaN)` returns NaN
18    ///
19    /// # Returns
20    ///
21    /// A tensor with the same shape where each element has been truncated toward zero.
22    ///
23    /// # Example
24    ///
25    /// ```rust
26    /// use burn_tensor::backend::Backend;
27    /// use burn_tensor::Tensor;
28    ///
29    /// fn example<B: Backend>() {
30    ///     let device = B::Device::default();
31    ///     let tensor = Tensor::<B, 1>::from_data([2.3, -1.7, 0.5, -0.5, 3.9], &device);
32    ///     let truncated = tensor.trunc();
33    ///
34    ///     // Result: [2.0, -1.0, 0.0, -0.0, 3.0]
35    /// }
36    /// ```
37    pub fn trunc(self) -> Self {
38        Self::new(TensorPrimitive::Float(B::float_trunc(
39            self.primitive.tensor(),
40        )))
41    }
42}