Skip to content

Commit

Permalink
accept custom ULP for approx check
Browse files Browse the repository at this point in the history
  • Loading branch information
LorrensP-2158466 committed Feb 5, 2025
1 parent 058dd60 commit b82c735
Showing 1 changed file with 16 additions and 9 deletions.
25 changes: 16 additions & 9 deletions tests/pass/float.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use std::{f32, f64};
const ALLOWED_ULP_DIFF: i128 = 64;

macro_rules! assert_approx_eq {
($a:expr, $b:expr) => {{
($a:expr, $b:expr, $ulp:expr) => {{
let (a, b) = (&$a, &$b);
let a_signum = a.signum();
let b_signum = b.signum();
Expand All @@ -27,17 +27,22 @@ macro_rules! assert_approx_eq {
}
let a_bits = a.to_bits() as i128;
let b_bits = b.to_bits() as i128;
let allowed_ulp = $ulp;
let ulp_difference = (a_bits - b_bits).abs();
assert!(
ulp_difference <= ALLOWED_ULP_DIFF,
ulp_difference <= allowed_ulp,
"
{:?} is not approximately equal to {:?}
ulp diff: {ulp_difference} > {ALLOWED_ULP_DIFF}
ulp diff: {ulp_difference} > {allowed_ulp}
",
*a,
*b
);
}};

($a:expr, $b: expr) => {
assert_approx_eq!($a, $b, ALLOWED_ULP_DIFF);
};
}

fn main() {
Expand Down Expand Up @@ -1276,27 +1281,27 @@ fn test_non_determinism() {
// seperate operations (unlikely but possible)
// and thus this `assert_ne!` can "sometimes" fail.
macro_rules! test_operation {
($a:expr, $b:expr, $op:path) => {
($a:expr, $b:expr, $op:path $(, $ulp:expr)?) => {
// 5 times enough?
let results: [_; 5] = ::core::array::from_fn(|i| (i, $op($a, $b)));
for (idx1, res1) in results {
for (idx2, res2) in results {
if idx1 == idx2 {
continue;
}
assert_approx_eq!(res1, res2);
assert_approx_eq!(res1, res2$(, $ulp)?);
}
}
};
($a:expr, $op:path) => {
($a:expr, $op:path $(, $ulp:expr)?) => {
// 5 times enough?
let results: [_; 5] = ::core::array::from_fn(|i| (i, $op($a)));
for (idx1, res1) in results {
for (idx2, res2) in results {
if idx1 == idx2 {
continue;
}
assert_approx_eq!(res1, res2);
assert_approx_eq!(res1, res2 $(, $ulp)?);
}
}
};
Expand Down Expand Up @@ -1325,12 +1330,14 @@ fn test_non_determinism() {
}
pub fn test_operations_f32(a: f32, b: f32) {
test_operations_f!(a, b);
test_operation!(a, b, f32::log);
// custom ulp for log
test_operation!(a, b, f32::log, 128);
test_operation!(a, f32::exp);
}
pub fn test_operations_f64(a: f64, b: f64) {
test_operations_f!(a, b);
test_operation!(a, b, f64::log);
// custom ulp for log
test_operation!(a, b, f64::log, 128);
test_operation!(a, f64::exp);
}
pub fn test_operations_f128(a: f128, b: f128) {
Expand Down

0 comments on commit b82c735

Please sign in to comment.