I have a test assertion that looks like this
assert_eq!(-0.000031989493, res);
which works for the test. But when I run Clippy on my test it complains.
error: strict comparison of `f32` or `f64`
--> src/main.rs:351:9
|
351 | assert_eq!(-0.000031989493, res);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: `f32::EPSILON` and `f64::EPSILON` are available for the `error_margin`
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#float_cmp
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
I've looked at the provided link https://rust-lang.github.io/rust-clippy/master/index.html#float_cmp and rewrote it like this instead.
assert_eq!(
true,
(res - -0.000031989493).abs() < f32::EPSILON
);
But that makes the test less readable and if the test fails I can't see the result of what I'm testing in the output.
How should I write my f32 comparison assertions so that Clippy is happy and so that the tests still output the values in the terminal if it fails?
Or should I just not run Clippy on my tests?
Thanks!
Ok so I've copied and altered the assert_eq macro a bit
macro_rules! assert_almost_eq {
($left:expr, $right:expr, $prec:expr) => {{
match (&$left, &$right) {
(left_val, right_val) => {
let diff = (left_val - right_val).abs();
if diff > $prec {
panic!(
"assertion failed: `(left == right)`\n left: `{:?}`,\n right: `{:?}`",
&*left_val, &*right_val
)
}
}
}
}};
}
I don't really understand everything, like the reason for the match, but it seems to solve my problem.