Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,563 questions

56,781 answers

573 users

How to compare floating-point values safely in VB.NET

3 Answers

0 votes
'====================================================================
' Title: Safe Floating-Point Comparison in VB.NET
'
' Purpose:
'   Demonstrates best practices for comparing floating-point
'   values safely using tolerances.
'
' Why not use "="?
'   Floating-point values (Single and Double) are stored as
'   binary approximations. Many decimal numbers cannot be
'   represented exactly in memory.
'
' Example:
'       0.1 + 0.2 <> 0.3
'
'   Even though the values are mathematically equal,
'   tiny rounding errors can make direct comparison fail.
'====================================================================

Imports System

Module Program

    ' Absolute tolerance:
    ' Useful when comparing values very close to zero.
    Private Const ABS_TOLERANCE As Double = 1.0E-12

    ' Relative tolerance:
    ' Useful when comparing large values where a fixed
    ' tolerance may not be sufficient.
    Private Const REL_TOLERANCE As Double = 1.0E-9

    ''' <summary>
    ''' Safely compares two Double values using both
    ''' absolute and relative tolerances.
    '''
    ''' Why both?
    '''   - Absolute tolerance works well near zero.
    '''   - Relative tolerance scales with larger values.
    ''' </summary>
    Function ApproximatelyEqual(a As Double,
                                b As Double) As Boolean

        ' Calculate the absolute difference.
        Dim difference As Double = Math.Abs(a - b)

        '------------------------------------------------
        ' Step 1:
        ' Check absolute tolerance.
        '
        ' This handles values that are extremely close
        ' to zero.
        '------------------------------------------------
        If difference <= ABS_TOLERANCE Then
            Return True
        End If

        '------------------------------------------------
        ' Step 2:
        ' Check relative tolerance.
        '
        ' Scale the tolerance according to the magnitude
        ' of the numbers being compared.
        '------------------------------------------------
        Dim largest As Double = Math.Max(Math.Abs(a), Math.Abs(b))

        Return difference <= largest * REL_TOLERANCE
    End Function

    Sub Main()

        '------------------------------------------------
        ' Classic floating-point precision example.
        '------------------------------------------------
        Dim x As Double = 0.1 + 0.2
        Dim y As Double = 0.3

        Console.WriteLine("================================================")
        Console.WriteLine(" Safe Floating-Point Comparison in VB.NET")
        Console.WriteLine("================================================")
        Console.WriteLine()

        ' Display many decimal places to reveal
        ' precision differences.
        Console.WriteLine($"x = {x:F17}")
        Console.WriteLine($"y = {y:F17}")
        Console.WriteLine()

        '------------------------------------------------
        ' BAD PRACTICE:
        ' Direct comparison using "=".
        '------------------------------------------------
        If x = y Then
            Console.WriteLine("Direct comparison: Equal")
        Else
            Console.WriteLine("Direct comparison: Not Equal")
        End If

        Console.WriteLine()

        '------------------------------------------------
        ' GOOD PRACTICE:
        ' Compare using a tolerance-based function.
        '------------------------------------------------
        If ApproximatelyEqual(x, y) Then
            Console.WriteLine("Safe comparison: Equal")
        Else
            Console.WriteLine("Safe comparison: Not Equal")
        End If

        Console.ReadKey()

    End Sub

End Module



' run:
'
' ================================================
'  Safe Floating-Point Comparison in VB.NET
' ================================================
' 
' x = 0.30000000000000004
' y = 0.29999999999999999
' 
' Direct comparison: Not Equal
' 
' Safe comparison: Equal
' 
' 
'

 



answered Oct 8 by avibootz
edited Oct 8 by avibootz
0 votes
Imports System

' Use Decimal for financial calculations
' For money and other exact decimal values, prefer Decimal.

Module Program

    Sub Main()

		Dim a As Decimal = 0.1D
		Dim b As Decimal = 0.2D
		Dim result As Decimal = a + b

		If result = 0.3D Then
			Console.WriteLine("Exactly equal")
		End If
	
    End Sub

End Module



' run:
'
' Exactly equal
'

 



answered Oct 8 by avibootz
0 votes
'===========================================================
' Title: Safe Floating-Point Comparison in VB.NET
'
' Purpose:
'   Demonstrates how to compare floating-point values safely
'   using an epsilon (tolerance) instead of direct equality.
'
' Why?
'   Floating-point values are stored approximately in binary,
'   which can introduce tiny rounding errors.
'
' Example:
'       0.1 + 0.2 <> 0.3
'
'   Even though they are mathematically equal,
'   they may not be exactly equal in memory.
'===========================================================

Imports System

Module Program

    '-------------------------------------------------------
    ' Function: ApproximatelyEqual
    '
    ' Compares two Double values using a tolerance (epsilon).
    '
    ' Parameters:
    '   a       - First value
    '   b       - Second value
    '   epsilon - Maximum allowed difference
    '
    ' Returns:
    '   True  if the values are close enough
    '   False otherwise
    '-------------------------------------------------------
    Function ApproximatelyEqual(a As Double,
                                b As Double,
                                epsilon As Double) As Boolean

        Return Math.Abs(a - b) <= epsilon

    End Function

    Sub Main()

        ' Example values
        Dim x As Double = 0.1 + 0.2
        Dim y As Double = 0.3

        ' Tolerance value
        Dim epsilon As Double = 0.000000001

        Console.WriteLine("======================================")
        Console.WriteLine(" Safe Floating-Point Comparison Demo")
        Console.WriteLine("======================================")
        Console.WriteLine()

        ' Show full precision
        Console.WriteLine("x = {0:F17}", x)
        Console.WriteLine("y = {0:F17}", y)
        Console.WriteLine()

        ' Direct comparison (not recommended)
        If x = y Then
            Console.WriteLine("Direct comparison (=): Equal")
        Else
            Console.WriteLine("Direct comparison (=): Not Equal")
        End If

        Console.WriteLine()

        ' Safe comparison using epsilon
        If ApproximatelyEqual(x, y, epsilon) Then
            Console.WriteLine("ApproximatelyEqual(): Equal")
        Else
            Console.WriteLine("ApproximatelyEqual(): Not Equal")
        End If

    End Sub

End Module


' run:
'
' ======================================
'  Safe Floating-Point Comparison Demo
' ======================================
' 
' x = 0.30000000000000004
' y = 0.29999999999999999
' 
' Direct comparison (=): Not Equal
' 
' ApproximatelyEqual(): Equal
' 
'

 



answered Oct 8 by avibootz
...