How to compare two float arrays using a tolerance in Swift

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.
*/

import Foundation

/// Compares two float arrays and returns true if all elements match within tolerance.
func compareFloatArrays(_ a: [Float], _ b: [Float], tolerance: Float) -> Bool {

    // If lengths differ, arrays cannot be equal
    guard a.count == b.count else { return false }

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

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

    // All elements matched within tolerance
    return true
}

/// Prints the comparison result.
func printComparison(_ result: Bool) {
    if result {
        print("Arrays are equal within tolerance.")
    } else {
        print("Arrays differ.")
    }
}

func main() {

    // Example arrays
    let floatArr1: [Float] = [
        12314.9872,
        3.14,
        12387.91371,
        8876.579013
    ]

    let floatArr2: [Float] = [
        12314.9872,
        3.14,
        12387.91372,
        8876.579013
    ]

    // Tolerance chosen for comparison
    let tolerance: Float = 0.001

    // Perform comparison
    // Note: function parameters are (_ a: [Float], _ b: [Float], tolerance: Float)
    let result: Bool = compareFloatArrays(floatArr1, floatArr2, tolerance: tolerance)

    // Output result
    printComparison(result)
}

main()


/*
run:

Arrays are equal within tolerance.

*/

 



answered Sep 8 by avibootz
...