|
| 1 | +/* SPDX-License-Identifier: MIT |
| 2 | + * origin: musl src/math/trunc.c */ |
| 3 | + |
| 4 | +use super::super::{Float, Int, IntTy, MinInt}; |
| 5 | + |
| 6 | +pub fn trunc<F: Float>(x: F) -> F { |
| 7 | + let mut xi: F::Int = x.to_bits(); |
| 8 | + let e: i32 = x.exp_unbiased(); |
| 9 | + |
| 10 | + // C1: The represented value has no fractional part, so no truncation is needed |
| 11 | + if e >= F::SIG_BITS as i32 { |
| 12 | + return x; |
| 13 | + } |
| 14 | + |
| 15 | + let mask = if e < 0 { |
| 16 | + // C2: If the exponent is negative, the result will be zero so we mask out everything |
| 17 | + // except the sign. |
| 18 | + F::SIGN_MASK |
| 19 | + } else { |
| 20 | + // C3: Otherwise, we mask out the last `e` bits of the significand. |
| 21 | + !(F::SIG_MASK >> e.unsigned()) |
| 22 | + }; |
| 23 | + |
| 24 | + // C4: If the to-be-masked-out portion is already zero, we have an exact result |
| 25 | + if (xi & !mask) == IntTy::<F>::ZERO { |
| 26 | + return x; |
| 27 | + } |
| 28 | + |
| 29 | + // C5: Otherwise the result is inexact and we will truncate. Raise `FE_INEXACT`, mask the |
| 30 | + // result, and return. |
| 31 | + force_eval!(x + F::MAX); |
| 32 | + xi &= mask; |
| 33 | + F::from_bits(xi) |
| 34 | +} |
| 35 | + |
| 36 | +#[cfg(test)] |
| 37 | +mod tests { |
| 38 | + use super::*; |
| 39 | + |
| 40 | + #[test] |
| 41 | + fn sanity_check() { |
| 42 | + assert_biteq!(trunc(1.1f32), 1.0); |
| 43 | + assert_biteq!(trunc(1.1f64), 1.0); |
| 44 | + |
| 45 | + // C1 |
| 46 | + assert_biteq!(trunc(hf32!("0x1p23")), hf32!("0x1p23")); |
| 47 | + assert_biteq!(trunc(hf64!("0x1p52")), hf64!("0x1p52")); |
| 48 | + assert_biteq!(trunc(hf32!("-0x1p23")), hf32!("-0x1p23")); |
| 49 | + assert_biteq!(trunc(hf64!("-0x1p52")), hf64!("-0x1p52")); |
| 50 | + |
| 51 | + // C2 |
| 52 | + assert_biteq!(trunc(hf32!("0x1p-1")), 0.0); |
| 53 | + assert_biteq!(trunc(hf64!("0x1p-1")), 0.0); |
| 54 | + assert_biteq!(trunc(hf32!("-0x1p-1")), -0.0); |
| 55 | + assert_biteq!(trunc(hf64!("-0x1p-1")), -0.0); |
| 56 | + } |
| 57 | +} |
0 commit comments