Skip to content

Commit f2a236e

Browse files
committed
Add some float tests from libcore
1 parent 529953e commit f2a236e

1 file changed

Lines changed: 78 additions & 0 deletions

File tree

tests/run/core-float.rs

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
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 $(,)?) => {{ assert_approx_eq!($a, $b, $crate::num::floats::lim_for_ty($a)) }};
34+
($a:expr, $b:expr, $lim:expr) => {{
35+
let (a, b) = (&$a, &$b);
36+
let diff = (*a - *b).abs();
37+
assert!(diff <= $lim,);
38+
}};
39+
}
40+
41+
type Float = f32;
42+
const fn flt(x: Float) -> Float {
43+
x
44+
}
45+
46+
fn test_exp() {
47+
assert_biteq!(1.0, flt(0.0).exp());
48+
assert_approx_eq!(consts::E, flt(1.0).exp(), EXP_APPROX);
49+
assert_approx_eq!(148.41315910257660342111558004055227962348775, flt(5.0).exp(), EXP_APPROX);
50+
51+
let inf: Float = Float::INFINITY;
52+
let neg_inf: Float = Float::NEG_INFINITY;
53+
let nan: Float = Float::NAN;
54+
assert_biteq!(inf, inf.exp());
55+
assert_biteq!(0.0, neg_inf.exp());
56+
assert!(nan.exp().is_nan());
57+
}
58+
59+
#[inline(never)]
60+
fn my_abs(num: f32) -> f32 {
61+
unsafe { intrinsics::fabs(num) }
62+
}
63+
64+
fn test_abs() {
65+
assert_biteq!(Float::INFINITY.abs(), Float::INFINITY);
66+
assert_biteq!(ONE.abs(), ONE);
67+
assert_biteq!(ZERO.abs(), ZERO);
68+
assert_biteq!((-ZERO).abs(), ZERO);
69+
assert_biteq!((-ONE).abs(), ONE);
70+
assert_biteq!(Float::NEG_INFINITY.abs(), Float::INFINITY);
71+
assert_biteq!((ONE / Float::NEG_INFINITY).abs(), ZERO);
72+
assert!(Float::NAN.abs().is_nan());
73+
}
74+
75+
fn main() {
76+
test_abs();
77+
test_exp();
78+
}

0 commit comments

Comments
 (0)