Used to compare two floating-point values for approximate equality.
? = x NEAR y
x, y : avar
NEAR can be used to reliably test whether two floating-point variables or expressions are equal.
Calculations on IEEE floating-point format expressions are performed in an internal 64-bit temporary register, which has more bits of accuracy than are stored in single-precision or double-precision variables. This often results in an IF statement returning an error which states that the intermediate calculation is not equal to the expression being compared. For example:
Dim x#, y#
x = 25, y = 60.1
Debug.Print x * y ' result = 1502.5
If 1502.5 = (x * y) Then Debug.Print "equal"
Running the above code will NOT print "equal". In contrast, the following method using a placeholder variable will print "equal", but is still NOT a reliable technique as a test for equality:
Dim z# = 25 * 60.1
If z = 1502.5 Then Debug.Print "equal"
Note that explicit numeric type casts (! for single precision, # for double precision) will affect the precision in which calculations are stored and printed. Whichever type casting you perform, you may still see unexpected rounding results:
Debug.Print 69.82! + 1 ' Single precision, prints 70.8199996948242
Debug.Print 69.82# + 1 ' Double precision, prints 70.82.
Most numbers in decimal (base 10) notation do NOT have an exact representation in the binary (base 2) floating-point storage format used in single-precision and double-precision data types. The IEEE format cannot exactly represent (and must round off) all numbers that are not of the form 1.x to the power of y (where x and y are base 2 numbers). The numbers that can be exactly represented are spread out over a very wide range. A high density of representable numbers is near 1.0 and -1.0, but fewer and fewer representable numbers occur as the numbers go towards 0 or infinity. These limitations often cause Basic to return floating-point results different than you might expect. In the following example not even NEAR provides a solution:
Debug (69.82# + 1) - (69.82! + 1) ' 3.0517577442879e-07
If (69.82! + 1) NEAR (69.82# + 1) Then Debug "EQUAL"
The NEAR comparison compare too much bits.
Only an explicit typecast makes the floating point comparison possible:
If (69.82! + 1) = CSng(69.82# + 1) Then Debug "EQUAL"
In GFA-BASIC 16 the 'near' comparison was performed using the == operator. However, in GFA-BASIC 32 this operator must be replaced by NEAR (in GFA-BASIC 32 the == operator is equivalent to =).
=, <, >, <=, >=, !=
{Created by Sjouke Hamstra; Last updated: 20/10/2014 by James Gaite}