Garry's Mod Wiki

math.IsNearlyEqual

  boolean math.IsNearlyEqual( number a, number b, number tolerance = 1e-8 )

Recently Added

This was recently added in version (2025.01.22). It might only be available on the Dev Branch right now.

Description

Checks if two floating point numbers are nearly equal.

Arguments

1 number a
The first number to compare.
2 number b
The second number to compare.
3 number tolerance = 1e-8
The maximum difference between the two numbers to consider them equal.

Returns

1 boolean
True if the difference between the two numbers is less than or equal to the tolerance.

Example

Shows the problem known as a floating-point error, due to the limited precision of decimal numbers in hardware.

print( 0.1 + 0.2 == 0.3 ) -- Which is mathematically true. print( string.format( "%.32f", 0.1 + 0.2 ) ) -- Outputs the result with up to 32 decimal numbers.
Output:
false 0.30000000000000004440892098500626

Example

Shows the workaround using math.IsNearlyEqual().

print( math.IsNearlyEqual( 0.1 + 0.2, 0.3 ) ) print( string.format( "%.32f", 0.1 + 0.2 ) )
Output:
true 0.30000000000000004440892098500626