How to compare two float arrays using a tolerance in C#

1 Answer

0 votes
using System;

class CompareFloatArraysWithTolerance
{
    /*
        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 arrays and returns true if all elements match within tolerance
    static bool CompareFloatArrays(float[] a, float[] b, float tolerance)
    {
        // If lengths differ, arrays cannot be equal
        if (a.Length != b.Length)
            return false;

        // Compare each element using absolute difference
        for (int i = 0; i < a.Length; i++) {
            float diff = Math.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
    static void PrintComparison(bool result)
    {
        if (result)
            Console.WriteLine("Arrays are equal within tolerance.");
        else
            Console.WriteLine("Arrays differ.");
    }

    static void Main()
    {
        // Example arrays
        float[] floatArr1 = new float[]
        {
            12314.9872f,
            3.14f,
            12387.91372f,
            8876.579013f
        };

        float[] floatArr2 = new float[]
        {
            12314.9872f,
            3.14f,
            12387.91371f,
            8876.579013f
        };

        // Tolerance chosen for comparison
        float tolerance = 0.001f;

        // Perform comparison
        bool result = CompareFloatArrays(floatArr1, floatArr2, tolerance);

        // Output result
        PrintComparison(result);
    }
}


/*
run:

Arrays are equal within tolerance.

*/

 



answered Sep 8 by avibootz
edited Sep 8 by avibootz
...