我有一个看起来像这样的测试断言
assert_eq!(-0.000031989493, res);
适用于测试。但是,当我在测试中运行Clippy时,它会提示。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)
我查看了提供的链接https://rust-lang.github.io/rust-clippy/master/index.html#float_cmp,并改写为这样。assert_eq!(
true,
(res - -0.000031989493).abs() < f32::EPSILON
);
但这会使测试的可读性降低,如果测试失败,我将无法在输出中看到测试结果。我应该如何编写f32比较断言,以便Clippy满意,并且如果失败,测试仍会在终端中输出值?
还是我不应该在测试中运行Clippy?
谢谢!
最佳答案
好的,所以我已经复制并更改了assert_eq宏
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
)
}
}
}
}};
}
我并不是很了解一切,比如比赛的原因,但这似乎可以解决我的问题。
关于rust - Clippy提示严格的f32比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65874156/