[swift-users] FloatingPoint equality ..

Stephen Canon scanon at apple.com
Thu Jun 29 13:47:50 CDT 2017



> On Jun 29, 2017, at 2:40 PM, Gavin Eadie via swift-users <swift-users at swift.org> wrote:
> 
> I've spent a fascinating evening and morning in the arcane depths of floating point, specifically researching the comparison of two floating point numbers.  I pretty much understand how to do this with a combination of 'epsilon' and 'ULPs' after reading this <https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/>.
> 
> For example, for a off-by-one ULP comparison:
> 
> public func almostEqual(_ a: Double, _ b: Double) -> Bool {
>     return a == b ||
>            a == nextafter(b, +.greatestFiniteMagnitude) ||
>            a == nextafter(b, -.greatestFiniteMagnitude)
> }
> 
> My question is whether Swift has a built in method that provides an 'almost equal' comparison?

It does not. It is “trivial” to implement such a comparison (just like you do here); the difficulty is entirely in guiding users in choosing a means of comparison and tolerance appropriate to their problem.

> Or, asking the same question another way, what doesn't the Swift method
> 
>      func isEqual(to other: Self) -> Bool <https://developer.apple.com/documentation/swift/bool>
> 
> actually do?  Does it test for equality of the binary representation of 'self' and 'other' (I assume it must given no 'precision' argument) .. I read it follows the IEEE meaning of equality but that document is not on my bookshelf and is quite expensive!

isEqual implements IEEE equality, which is *not the same* as bitwise equality of representation. In particular:

1. x != x is true when x is NaN.
2. –0 == +0, but the two values have different encodings.
3. Float80 admits non-canonical “pseudo denormal” values that compare equal to a canonical value with a different encoding.
4. IEEE 754 Decimal types (not implemented in the standard library) have *many* encodings that compare equal.

– Steve
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170629/4dc8c88c/attachment.html>


More information about the swift-users mailing list