|
| 1 | +// Compiler: |
| 2 | +// |
| 3 | +// Run-time: |
| 4 | +// status: 0 |
| 5 | + |
| 6 | +// TODO: remove these tests (extracted from libcore) when we run the libcore tests in the CI of the |
| 7 | +// Rust repo. |
| 8 | + |
| 9 | +#![feature(core_intrinsics)] |
| 10 | + |
| 11 | +use std::f32::consts; |
| 12 | +use std::intrinsics; |
| 13 | + |
| 14 | +const EXP_APPROX: Float = 1e-6; |
| 15 | +const ZERO: Float = 0.0; |
| 16 | +const ONE: Float = 1.0; |
| 17 | + |
| 18 | +macro_rules! assert_biteq { |
| 19 | + ($left:expr, $right:expr $(,)?) => {{ |
| 20 | + let l = $left; |
| 21 | + let r = $right; |
| 22 | + |
| 23 | + // Hack to coerce left and right to the same type |
| 24 | + let mut _eq_ty = l; |
| 25 | + _eq_ty = r; |
| 26 | + |
| 27 | + // Hack to get the width from a value |
| 28 | + assert!(l.to_bits() == r.to_bits()); |
| 29 | + }}; |
| 30 | +} |
| 31 | + |
| 32 | +macro_rules! assert_approx_eq { |
| 33 | + ($a:expr, $b:expr $(,)?) => {{ |
| 34 | + assert_approx_eq!($a, $b, $crate::num::floats::lim_for_ty($a)) |
| 35 | + }}; |
| 36 | + ($a:expr, $b:expr, $lim:expr) => {{ |
| 37 | + let (a, b) = (&$a, &$b); |
| 38 | + let diff = (*a - *b).abs(); |
| 39 | + assert!( |
| 40 | + diff <= $lim, |
| 41 | + ); |
| 42 | + }}; |
| 43 | +} |
| 44 | + |
| 45 | +type Float = f32; |
| 46 | +const fn flt (x: Float) -> Float { x } |
| 47 | + |
| 48 | +fn test_exp() { |
| 49 | + assert_biteq!(1.0, flt(0.0).exp()); |
| 50 | + assert_approx_eq!(consts::E, flt(1.0).exp(), EXP_APPROX); |
| 51 | + assert_approx_eq!(148.41315910257660342111558004055227962348775, flt(5.0).exp(), EXP_APPROX); |
| 52 | + |
| 53 | + let inf: Float = Float::INFINITY; |
| 54 | + let neg_inf: Float = Float::NEG_INFINITY; |
| 55 | + let nan: Float = Float::NAN; |
| 56 | + assert_biteq!(inf, inf.exp()); |
| 57 | + assert_biteq!(0.0, neg_inf.exp()); |
| 58 | + assert!(nan.exp().is_nan()); |
| 59 | +} |
| 60 | + |
| 61 | +#[inline(never)] |
| 62 | +fn my_abs(num: f32) -> f32 { |
| 63 | + unsafe { intrinsics::fabs(num) } |
| 64 | +} |
| 65 | + |
| 66 | +fn test_abs() { |
| 67 | + assert_biteq!(Float::INFINITY.abs(), Float::INFINITY); |
| 68 | + assert_biteq!(ONE.abs(), ONE); |
| 69 | + assert_biteq!(ZERO.abs(), ZERO); |
| 70 | + assert_biteq!((-ZERO).abs(), ZERO); |
| 71 | + assert_biteq!((-ONE).abs(), ONE); |
| 72 | + assert_biteq!(Float::NEG_INFINITY.abs(), Float::INFINITY); |
| 73 | + assert_biteq!((ONE / Float::NEG_INFINITY).abs(), ZERO); |
| 74 | + assert!(Float::NAN.abs().is_nan()); |
| 75 | +} |
| 76 | + |
| 77 | +fn main() { |
| 78 | + test_abs(); |
| 79 | + test_exp(); |
| 80 | +} |
0 commit comments