[swift-users] FloatingPoint equality ..

Gavin Eadie gavin at umich.edu
Thu Jun 29 13:30:20 CDT 2017


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?

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!

Apologies if this has been asked and answered before .. Gavin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170629/770e534f/attachment.html>


More information about the swift-users mailing list