Validity of Algorithm for Testing Two Floating Point Numbers
There is one method to compare floating point numbers for equality, which is both very simple and correct: You use the equality (==) operator.
There is another method to compare whether floating point numbers are identical, which unlike the equality operator would find that -0 and +0 are not the same, and that NaNs with the same bit pattern are the same: Use memcmp. (Don't do this if your compiler stores 80 bit long double into 128 bits).
What you are talking about is the question: &quot;Are these two numbers so close together that their difference could be due to rounding errors alone&quot;, and another question would be &quot;Are these two numbers so close together that we don't care that they are different&quot;.
Swift has decided to put an operator for the latter into its standard library. This considers floating numbers with an n bit mantissa &quot;as good as equal&quot; if the difference is at most the last n/2 bits.
So first don't call your function &quot;equals&quot;, because that is a lie. Call it &quot;almostEqual&quot; or something like that. Then make sure that it returns true without failure whenever x == y, that almostEqual (x, y) == almostEqual (y, x) for all pairs x, y, and that it returns the same result if you scale x, y both by the same power of two (unless this produces overflow or underflow).
Be aware that you cannot guarantee that almostEqual(x,y) and almostEqual(y,z) implies almostEqual(x,z). This also implies that you cannot make it compatible with any hash function.