RosettaCodeData/Task/Approximate-equality/00-TASK.txt

33 lines
2.1 KiB
Plaintext

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.
;Task:
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,
<br>'''100000000000000.01''' &nbsp; may be approximately equal to &nbsp; '''100000000000000.011''',
<br>even though &nbsp; '''100.01''' &nbsp; is not approximately equal to &nbsp; '''100.011'''.
If the language has such a 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:
:# &nbsp; &nbsp; 100000000000000.01, &nbsp; 100000000000000.011 &nbsp; &nbsp; (note: should return ''true'')
:# &nbsp; &nbsp; 100.01, &nbsp; 100.011 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (note: should return ''false'')
:# &nbsp; &nbsp; 10000000000000.001 <big>/</big> 10000.0, &nbsp; 1000000000.0000001000
:# &nbsp; &nbsp; 0.001, &nbsp; 0.0010000001
:# &nbsp; &nbsp; 0.000000000000000000000101, &nbsp; 0.0
:# &nbsp; &nbsp; &nbsp;sqrt(2) * sqrt(2), &nbsp; &nbsp;2.0
:# &nbsp; &nbsp; -sqrt(2) * sqrt(2), &nbsp; -2.0
:# &nbsp; &nbsp; 3.14159265358979323846, &nbsp; 3.14159265358979324
<br/>
Answers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.
<br><br>
__TOC__