1 use core::f64;
2
3 const TOINT: f64 = 1. / f64::EPSILON;
4
5 /// Ceil (f64)
6 ///
7 /// Finds the nearest integer greater than or equal to `x`.
8 #[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
ceil(x: f64) -> f649 pub fn ceil(x: f64) -> f64 {
10 // On wasm32 we know that LLVM's intrinsic will compile to an optimized
11 // `f64.ceil` native instruction, so we can leverage this for both code size
12 // and speed.
13 llvm_intrinsically_optimized! {
14 #[cfg(target_arch = "wasm32")] {
15 return unsafe { ::core::intrinsics::ceilf64(x) }
16 }
17 }
18 let u: u64 = x.to_bits();
19 let e: i64 = (u >> 52 & 0x7ff) as i64;
20 let y: f64;
21
22 if e >= 0x3ff + 52 || x == 0. {
23 return x;
24 }
25 // y = int(x) - x, where int(x) is an integer neighbor of x
26 y = if (u >> 63) != 0 {
27 x - TOINT + TOINT - x
28 } else {
29 x + TOINT - TOINT - x
30 };
31 // special case because of non-nearest rounding modes
32 if e < 0x3ff {
33 force_eval!(y);
34 return if (u >> 63) != 0 { -0. } else { 1. };
35 }
36 if y < 0. {
37 x + y + 1.
38 } else {
39 x + y
40 }
41 }
42
43 #[cfg(test)]
44 mod tests {
45 use super::*;
46 use core::f64::*;
47
48 #[test]
sanity_check()49 fn sanity_check() {
50 assert_eq!(ceil(1.1), 2.0);
51 assert_eq!(ceil(2.9), 3.0);
52 }
53
54 /// The spec: https://en.cppreference.com/w/cpp/numeric/math/ceil
55 #[test]
spec_tests()56 fn spec_tests() {
57 // Not Asserted: that the current rounding mode has no effect.
58 assert!(ceil(NAN).is_nan());
59 for f in [0.0, -0.0, INFINITY, NEG_INFINITY].iter().copied() {
60 assert_eq!(ceil(f), f);
61 }
62 }
63 }
64