Garry's Mod Wiki

Garry's Mod Wiki

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

Description

Checks if two floating point numbers are nearly equal.

This is useful to mitigate accuracy issues in floating point numbers. See examples below.

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

This site is a community mirror of the official Garry's Mod wiki.. This site is not maintained by Facepunch Studios.

Page content is automatically updated four times a day. Edits and history are not available.

Last Parsed: Loading...