Compare Floats With Relative Tolerance

Compare floating point values with a relative tolerance plus an absolute fallback, because exact equality rarely survives arithmetic.

RustData Integrity

Code

rustsnippet
27 lines
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);
}

How the snippet works

Compare Floats With Relative Tolerance comes down to the functions approx_eq and main.

for (a, b) in cases is the loop that carries the per-item work.

Applying it

Signature: fn approx_eq(a: f64, b: f64, tolerance: f64) -> bool

Running the file prints labeled results such as exact equality: — each operation’s effect is visible in the output.

The demo flow inside main is approx_eq — run the file to see it end to end.

Statements that matter

return diff <= f64::EPSILON;

Interactive Tools for This Topic

FAQ

What does Compare Floats With Relative Tolerance print when run?
Invoke the file as-is — the `exact equality:` prefixes identify which step printed each line.