|
| 1 | +/* SPDX-License-Identifier: MIT |
| 2 | + * origin: musl src/math/ceil.c */ |
| 3 | + |
| 4 | +use super::super::{CastInto, Float}; |
| 5 | + |
| 6 | +pub fn ceil<F: Float>(x: F) -> F { |
| 7 | + let toint = F::ONE / F::EPSILON; |
| 8 | + |
| 9 | + // NB: using `exp` here and comparing to values adjusted by `EXP_BIAS` has better |
| 10 | + // perf than using `exp_unbiased` here. |
| 11 | + let e = x.exp(); |
| 12 | + let y: F; |
| 13 | + |
| 14 | + // If the represented value has no fractional part, no truncation is needed. |
| 15 | + if e >= (F::SIG_BITS + F::EXP_BIAS).cast() || x == F::ZERO { |
| 16 | + return x; |
| 17 | + } |
| 18 | + |
| 19 | + let neg = x.is_sign_negative(); |
| 20 | + |
| 21 | + // y = int(x) - x, where int(x) is an integer neighbor of x. |
| 22 | + // The `x - t + t - x` method is a way to expose non-round-to-even modes. |
| 23 | + y = if neg { x - toint + toint - x } else { x + toint - toint - x }; |
| 24 | + |
| 25 | + // Exp < 0; special case because of non-nearest rounding modes |
| 26 | + if e < F::EXP_BIAS.cast() { |
| 27 | + // Raise `FE_INEXACT` |
| 28 | + force_eval!(y); |
| 29 | + return if neg { F::NEG_ZERO } else { F::ONE }; |
| 30 | + } |
| 31 | + |
| 32 | + if y < F::ZERO { x + y + F::ONE } else { x + y } |
| 33 | +} |
| 34 | + |
| 35 | +#[cfg(test)] |
| 36 | +mod tests { |
| 37 | + use super::*; |
| 38 | + |
| 39 | + #[test] |
| 40 | + fn sanity_check_f64() { |
| 41 | + assert_eq!(ceil(1.1f64), 2.0); |
| 42 | + assert_eq!(ceil(2.9f64), 3.0); |
| 43 | + } |
| 44 | + |
| 45 | + /// The spec: https://en.cppreference.com/w/cpp/numeric/math/ceil |
| 46 | + #[test] |
| 47 | + fn spec_tests_f64() { |
| 48 | + // Not Asserted: that the current rounding mode has no effect. |
| 49 | + assert!(ceil(f64::NAN).is_nan()); |
| 50 | + for f in [0.0, -0.0, f64::INFINITY, f64::NEG_INFINITY].iter().copied() { |
| 51 | + assert_eq!(ceil(f), f); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + #[test] |
| 56 | + fn sanity_check_f32() { |
| 57 | + assert_eq!(ceil(1.1f32), 2.0); |
| 58 | + assert_eq!(ceil(2.9f32), 3.0); |
| 59 | + } |
| 60 | + |
| 61 | + /// The spec: https://en.cppreference.com/w/cpp/numeric/math/ceil |
| 62 | + #[test] |
| 63 | + fn spec_tests_f32() { |
| 64 | + // Not Asserted: that the current rounding mode has no effect. |
| 65 | + assert!(ceil(f32::NAN).is_nan()); |
| 66 | + for f in [0.0, -0.0, f32::INFINITY, f32::NEG_INFINITY].iter().copied() { |
| 67 | + assert_eq!(ceil(f), f); |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments