How to compare two float arrays using a tolerance in Rust

1 Answer

0 votes
/*
    Compare two float arrays element-by-element using a tolerance.
    Floating‑point values often differ slightly due to rounding,
    so two numbers are considered "equal" when their absolute
    difference is below the chosen threshold.
*/

/// Compares two float slices and returns true if all elements match within tolerance.
fn compare_float_slices(a: &[f32], b: &[f32], tolerance: f32) -> bool {
    // If lengths differ, slices cannot be equal
    if a.len() != b.len() {
        return false;
    }

    // Compare each element using absolute difference
    for i in 0..a.len() {
        let diff: f32 = (a[i] - b[i]).abs();

        // If any element differs more than tolerance, slices are not equal
        if diff > tolerance {
            return false;
        }
    }

    // All elements matched within tolerance
    true
}

/// Prints the comparison result.
fn print_comparison(result: bool) {
    if result {
        println!("Slices are equal within tolerance.");
    } else {
        println!("Slices differ.");
    }
}

fn main() {
    // Example slices
    let float_slice1: [f32; 4] = [
        12314.9872f32,
        3.14f32,
        12387.91371f32,
        8876.579013f32,
    ];

    let float_slice2: [f32; 4] = [
        12314.9872f32,
        3.14f32,
        12387.91372f32,
        8876.579013f32,
    ];

    // Tolerance chosen for comparison
    let tolerance: f32 = 0.001f32;

    // Perform comparison
    let result: bool = compare_float_slices(&float_slice1, &float_slice2, tolerance);

    // Output result
    print_comparison(result);
}


/*
run:

Slices are equal within tolerance.

*/

 



answered Sep 8 by avibootz
...