ashleygwilliams / assert_approx_eq

a rust macro for asserting 2 numbers are approximately equal
https://docs.rs/assert_approx_eq/
Apache License 2.0
27 stars 6 forks source link

support relative tolerance as well as absolute difference? #26

Open smason opened 5 years ago

smason commented 5 years ago

I've just started using your code and realised it doesn't have a concept of "relative difference", e.g:

let a = 1e10;
let b = a + a * std::f64::EPSILON;
assert_approx_eq!(a, b);

will fail, even though the values are as close as possible to each other while being distinct. the hex representations of the above are:

0x1.2a05f20000000p+33
0x1.2a05f20000001p+33

i.e. one bit different, which seems like something I'd consider "approximately equal".

other libraries do something equivalent to:

(a - b).abs() < a.abs().max(b.abs()) * rel_tol + abs_tol

where rel_tol and abs_tol are configurable like eps is in your code, with your code implicitly using 0 and 1e-6 at the moment. for comparison, Python variously uses values of 1e-9 and 0, 1e-5 and 1e-08, and 1e-7 and 0.

could put a patch together, but not sure if this something you want & how much to break the existing API

cglosser commented 4 years ago

I'd be interested in this, too. I'm kind of a newbie Rustacean, but I wouldn't mind taking a stab at implementing or discussing this, either (mostly so I can learn something :smile:).

smason commented 4 years ago

@cglosser https://lib.rs/crates/approx provides a macro for this as well as looking somewhat more popular