[swift-evolution] implementing real (floating point) number comparison tolerance as a compiler directive.

Joe Groff jgroff at apple.com
Wed Mar 2 14:56:27 CST 2016


> On Mar 2, 2016, at 12:45 PM, David Sweeris <davesweeris at mac.com> wrote:
> 
> func == (lhs: Double, rhs: (value: Double, tolerance: Double)) -> Bool {
>     return ((rhs.value - rhs.tolerance)...(rhs.value + rhs.tolerance)) ~= lhs
> }
> 3.0 == 3.01 ≈ 0.001 // false
> 3.0 == 3.01 ≈ 0.01 // true
> 
> I tried using "ε", which is the standard symbol for "error", but that doesn't seem to be a valid operator character. "≈" (⌥-x, at least on a mac) is the only other one that seemed to make sense, with the possible exception of "∂", but I don't think that's as well-known.

That's cute. In a real implementation of tolerant comparison, you'd want to scale the tolerance to the magnitude of the larger operand, though. (See http://code.jsoftware.com/wiki/Essays/Tolerant_Comparison .)

-Joe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160302/456b2772/attachment.html>


More information about the swift-evolution mailing list