Approximate equality

From Rosetta Code
Revision as of 01:56, 2 September 2019 by Wherrera (talk | contribs)
Approximate equality is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.


Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the difference in floating point calculations between different language implementations becomes significant. For example, a difference between 32 bit and 64 bit floating point calculations may appear by about the 8th significant digit in base 10 arithmetic.

Create a function which returns true if two floating point numbers are approximately equal. The function should allow for differences in the magnitude of numbers, so that, for example, 100000000000000.01 may be approximately equal to 100000000000000.011, even though 100.01 is not approximately equal to 100.011.

If the language has such as feature in its standard library, this may be used instead of a custom function.

Show the function results with comparisons on the following pairs of values:

  • 100000000000000.01, 100000000000000.011 (note: should return true)
  • 100.01, 100.011 (note: should return false)
  • 10000000000000.001 / 10000.0, 1000000000.0000001000
  • 0.001, 0.0010000001
  • 0.000000000000000000000101, 0.0
  • sqrt(2) * sqrt(2), 2.0
  • -sqrt(2) * sqrt(2), -2.0
  • 3.14159265358979323846, 3.14159265358979324

Answers should be similar to the Python code example, except for the third case, which may well vary depending on how your function handles comparison with (exactly) 0.0.

Python

<lang python>from numpy import sqrt from math import isclose

testvalues = [[100000000000000.01,100000000000000.011], [00.01, 100.011],

             [10000000000000.001 / 10000.0, 1000000000.0000001000],
             [0.001, 0.0010000001], [0.00000000000000000101, 0.0],
             [sqrt(2) * sqrt(2), 2.0], [-sqrt(2) * sqrt(2), -2.0],
             [100000000000000003.0, 100000000000000004.0],
             [3.14159265358979323846, 3.14159265358979324]]

for (x, y) in testvalues:

   maybenot = "" if isclose(x, y) else "NOT"
   print(x, "is", maybenot, "approximately equal to ", y)

</lang>

Output:
100000000000000.02 is  approximately equal to  100000000000000.02
0.01 is NOT approximately equal to  100.011
1000000000.0000002 is  approximately equal to  1000000000.0000001
0.001 is NOT approximately equal to  0.0010000001
1.01e-18 is NOT approximately equal to  0.0
2.0 is  approximately equal to  2.0
-2.0 is  approximately equal to  -2.0
1e+17 is  approximately equal to  1e+17
3.141592653589793 is  approximately equal to  3.141592653589793