How to compare two float arrays for exact equality in C#

1 Answer

0 votes
/*
    Compare two float arrays element-by-element for exact equality.
    Floating‑point values must match exactly; even tiny rounding
    differences will cause inequality. This is stricter than using
    a tolerance-based comparison.
*/

using System;

class CompareFloatArraysExactProgram
{
    /*
        Compares two float arrays and returns true only if all elements
        are exactly equal. Direct == comparison checks for exact binary equality.
    */
    static bool CompareFloatArraysExact(float[] a, float[] b)
    {
        // If lengths differ, arrays cannot be equal
        if (a.Length != b.Length)
            return false;

        // Compare each element directly
        for (int i = 0; i < a.Length; i++) {
            if (a[i] != b[i])
                return false;   // Found mismatch → arrays differ
        }

        // All elements matched exactly
        return true;
    }

    /*
        Prints the comparison result.
    */
    static void PrintComparison(bool result)
    {
        if (result)
            Console.WriteLine("Arrays are exactly equal.");
        else
            Console.WriteLine("Arrays differ.");
    }

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

        float[] floatArr2 = {
            12314.9872f,
            3.14f,
            12387.91834f,
            8873.579013f
        };

        // Perform exact comparison
        bool result = CompareFloatArraysExact(floatArr1, floatArr2);

        // Output result
        PrintComparison(result);
    }
}


/*
run:

Arrays are exactly equal.

*/

 



answered Sep 9 by avibootz
...