实现说明
函数 approx_eq、main定义了示例的全部动作。
这个文件只在 for (a, b) in cases 里循环。
使用要点
- 跑完文件,输出里会留下标记——
exact equality:。 - 执行文件,
main会按顺序走完approx_eq。
常见问题
运行「浮点数相对误差比较」会打印什么?
运行文件本身,exact equality: 这些前缀各对应一段演示逻辑。
主要签名是 fn approx_eq(a: f64, b: f64, tolerance: f64) -> bool
核心语句
return diff <= f64::EPSILON;
代码示例
fn approx_eq(a: f64, b: f64, tolerance: f64) -> bool {
if a == b {
return true;
}
// Compare floats with relative tolerance; near zero, fall back to absolute
let diff = (a - b).abs();
let scale = a.abs().max(b.abs());
// 相对误差:阈值随数值量级缩放;接近零时退回绝对误差
if scale == 0.0 {
return diff <= f64::EPSILON;
}
diff <= tolerance * scale
}
fn main() {
let tolerance = 1e-9;
let cases = [
(0.1 + 0.2, 0.3),
(1.0, 1.000_000_001),
(1.0e12, 1.0e12 + 1.0),
(0.0, 0.0),
];
for (a, b) in cases {
println!("{a} vs {b} -> {}", approx_eq(a, b, tolerance));
}
println!("exact equality: {}", 0.1 + 0.2 == 0.3);
}