• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 use core::u64;
2 
3 /// Absolute value (magnitude) (f64)
4 /// Calculates the absolute value (magnitude) of the argument `x`,
5 /// by direct manipulation of the bit representation of `x`.
6 #[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
fabs(x: f64) -> f647 pub fn fabs(x: f64) -> f64 {
8     // On wasm32 we know that LLVM's intrinsic will compile to an optimized
9     // `f64.abs` native instruction, so we can leverage this for both code size
10     // and speed.
11     llvm_intrinsically_optimized! {
12         #[cfg(target_arch = "wasm32")] {
13             return unsafe { ::core::intrinsics::fabsf64(x) }
14         }
15     }
16     f64::from_bits(x.to_bits() & (u64::MAX / 2))
17 }
18 
19 #[cfg(test)]
20 mod tests {
21     use super::*;
22     use core::f64::*;
23 
24     #[test]
sanity_check()25     fn sanity_check() {
26         assert_eq!(fabs(-1.0), 1.0);
27         assert_eq!(fabs(2.8), 2.8);
28     }
29 
30     /// The spec: https://en.cppreference.com/w/cpp/numeric/math/fabs
31     #[test]
spec_tests()32     fn spec_tests() {
33         assert!(fabs(NAN).is_nan());
34         for f in [0.0, -0.0].iter().copied() {
35             assert_eq!(fabs(f), 0.0);
36         }
37         for f in [INFINITY, NEG_INFINITY].iter().copied() {
38             assert_eq!(fabs(f), INFINITY);
39         }
40     }
41 }
42