Skip to content

Commit b82c735

Browse files
accept custom ULP for approx check
1 parent 058dd60 commit b82c735

File tree

1 file changed

+16
-9
lines changed

1 file changed

+16
-9
lines changed

tests/pass/float.rs

+16-9
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use std::{f32, f64};
1616
const ALLOWED_ULP_DIFF: i128 = 64;
1717

1818
macro_rules! assert_approx_eq {
19-
($a:expr, $b:expr) => {{
19+
($a:expr, $b:expr, $ulp:expr) => {{
2020
let (a, b) = (&$a, &$b);
2121
let a_signum = a.signum();
2222
let b_signum = b.signum();
@@ -27,17 +27,22 @@ macro_rules! assert_approx_eq {
2727
}
2828
let a_bits = a.to_bits() as i128;
2929
let b_bits = b.to_bits() as i128;
30+
let allowed_ulp = $ulp;
3031
let ulp_difference = (a_bits - b_bits).abs();
3132
assert!(
32-
ulp_difference <= ALLOWED_ULP_DIFF,
33+
ulp_difference <= allowed_ulp,
3334
"
3435
{:?} is not approximately equal to {:?}
35-
ulp diff: {ulp_difference} > {ALLOWED_ULP_DIFF}
36+
ulp diff: {ulp_difference} > {allowed_ulp}
3637
",
3738
*a,
3839
*b
3940
);
4041
}};
42+
43+
($a:expr, $b: expr) => {
44+
assert_approx_eq!($a, $b, ALLOWED_ULP_DIFF);
45+
};
4146
}
4247

4348
fn main() {
@@ -1276,27 +1281,27 @@ fn test_non_determinism() {
12761281
// seperate operations (unlikely but possible)
12771282
// and thus this `assert_ne!` can "sometimes" fail.
12781283
macro_rules! test_operation {
1279-
($a:expr, $b:expr, $op:path) => {
1284+
($a:expr, $b:expr, $op:path $(, $ulp:expr)?) => {
12801285
// 5 times enough?
12811286
let results: [_; 5] = ::core::array::from_fn(|i| (i, $op($a, $b)));
12821287
for (idx1, res1) in results {
12831288
for (idx2, res2) in results {
12841289
if idx1 == idx2 {
12851290
continue;
12861291
}
1287-
assert_approx_eq!(res1, res2);
1292+
assert_approx_eq!(res1, res2$(, $ulp)?);
12881293
}
12891294
}
12901295
};
1291-
($a:expr, $op:path) => {
1296+
($a:expr, $op:path $(, $ulp:expr)?) => {
12921297
// 5 times enough?
12931298
let results: [_; 5] = ::core::array::from_fn(|i| (i, $op($a)));
12941299
for (idx1, res1) in results {
12951300
for (idx2, res2) in results {
12961301
if idx1 == idx2 {
12971302
continue;
12981303
}
1299-
assert_approx_eq!(res1, res2);
1304+
assert_approx_eq!(res1, res2 $(, $ulp)?);
13001305
}
13011306
}
13021307
};
@@ -1325,12 +1330,14 @@ fn test_non_determinism() {
13251330
}
13261331
pub fn test_operations_f32(a: f32, b: f32) {
13271332
test_operations_f!(a, b);
1328-
test_operation!(a, b, f32::log);
1333+
// custom ulp for log
1334+
test_operation!(a, b, f32::log, 128);
13291335
test_operation!(a, f32::exp);
13301336
}
13311337
pub fn test_operations_f64(a: f64, b: f64) {
13321338
test_operations_f!(a, b);
1333-
test_operation!(a, b, f64::log);
1339+
// custom ulp for log
1340+
test_operation!(a, b, f64::log, 128);
13341341
test_operation!(a, f64::exp);
13351342
}
13361343
pub fn test_operations_f128(a: f128, b: f128) {

0 commit comments

Comments
 (0)