How to compare two float arrays for exact equality in VB.NET

1 Answer

0 votes
Imports System

'---------------------------------------------------------------
' 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.
'---------------------------------------------------------------

Module CompareFloatArraysExactProgram

    '
    ' Compares two float arrays and returns True only if all elements
    ' are exactly equal. Direct "=" comparison checks for exact binary equality.
    '
    Function CompareFloatArraysExact(a As Single(), b As Single()) As Boolean

        ' If lengths differ, arrays cannot be equal
        If a.Length <> b.Length Then
            Return False
        End If

        ' Compare each element directly
        For i As Integer = 0 To a.Length - 1
            If a(i) <> b(i) Then
                Return False   ' Found mismatch → arrays differ
            End If
        Next

        ' All elements matched exactly
        Return True
    End Function

    '
    ' Prints the comparison result.
    '
    Sub PrintComparison(result As Boolean)
        If result Then
            Console.WriteLine("Arrays are exactly equal.")
        Else
            Console.WriteLine("Arrays differ.")
        End If
    End Sub

    Sub Main()

        ' Example arrays
        Dim floatArr1 As Single() = {
            12314.9872F,
            3.14F,
            12387.91834F,
            8873.579013F
        }

        Dim floatArr2 As Single() = {
            12314.9872F,
            3.14F,
            12387.91834F,
            8873.579013F
        }

        ' Perform exact comparison
        Dim result As Boolean = CompareFloatArraysExact(floatArr1, floatArr2)

        ' Output result
        PrintComparison(result)

    End Sub

End Module


' run:
'
' Arrays are exactly equal.
'

 



answered Sep 9 by avibootz
...