nearly
Compare IEEE floating point types by nearly comparisons.
When comparing floating point types, because of their limited precision, they might not be exactly identical. Consider the following example, where a and b appear to be identical, but they are not:
let a: f32 = 1.0 + 1.04 + 1.1;
let b: f32 = 3.14;
assert!; // <-- PANICS
This crate provides macros to perform a comparison with some tolerance.
use nearly;
assert!; // <-- OK
Usage
The easiest way to use nearly comparisons is by invoking the nearly! macro. The macro returns
a boolean whether the comparison is true or false by using the provided tolerance.
The comparison can be:
a == bfor testing whether a is nearly equal to ba != bfor testing whether a is not nearly equal to b
The tolerance used can be:
epsfor an absolute epsilon toleranceulpsfor an ulps based tolerancetolfor an absolute epsilon and ulps based tolerancedefaultfor an absolute epsilon and ulps based tolerance using default values
Here are some example calls:
use ;
let a: f32 = 1.0 + 1.04 + 1.1;
let b: f32 = 3.14;
// use absolute epsilon tolerance
nearly!;
// use ulps based tolerance
nearly!;
// use absolute epsilon and ulps based tolerance
nearly!;
nearly!;
// use default absolute epsilon and default ulps based tolerance
nearly!;
There is also an assert_nearly! and debug_assert_nearly! macros you can use that panic if the
nearly comparison evaluates to false. The signature is the same as for the nearly! macro.
use ;
assert_nearly!;
assert_nearly!;
assert_nearly!;
assert_nearly!;
assert_nearly!;
debug_assert_nearly!;
debug_assert_nearly!;
debug_assert_nearly!;
debug_assert_nearly!;
debug_assert_nearly!;
Derive the nearly traits
The easiest way to add nearly comparison to your own types is by deriving the nearly traits.
Just derive NearlyEq to get full support on your type.
use ;
let a = Point ;
let b = Point ;
assert_nearly!;
To use the assert_nearly! and debug_assert_nearly! macros, your type must also implement the Debug trait.
You can derive the following traits:
NearlyEqEps: enables nearly support with absolute epsilon toleranceNearlyEqUlps: enables nearly support with ulps based toleranceNearlyEqTol: enables nearly support with absolute epsilon and ulps based tolerancesNearlyEq: enables nearly support with absolute epsilon and ulps based tolerances with default values