How to compare two float arrays using a tolerance in VB.NET

1 Answer

0 votes
Imports System

Module 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
    Function CompareFloatArrays(a As Single(), b As Single(), tolerance As Single) As Boolean

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

        ' Compare each element using absolute difference
        For i As Integer = 0 To a.Length - 1
            Dim diff As Single = Math.Abs(a(i) - b(i))

            ' If any element differs more than tolerance, arrays are not equal
            If diff > tolerance Then
                Return False
            End If
        Next

        ' All elements matched within tolerance
        Return True
    End Function

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

    Sub Main()

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

        Dim floatArr2 As Single() = {
            12314.9872F,
            3.14F,
            12387.91371F,
            8876.579013F
        }

        ' Tolerance chosen for comparison
        Dim tolerance As Single = 0.001F

        ' Perform comparison
        Dim result As Boolean = CompareFloatArrays(floatArr1, floatArr2, tolerance)

        ' Output result
        PrintComparison(result)

    End Sub

End Module


'
' run:
'
' Arrays are equal within tolerance.
'

 



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