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

Joe Groff jgroff at apple.com
Wed Mar 2 15:28:51 CST 2016


> On Mar 2, 2016, at 1:23 PM, Tino Heth via swift-evolution <swift-evolution at swift.org> wrote:
> 
> I hope that I'll finally have the time to write a pitch for "inheritance for structs" this weekend — this looks like another good use case for a "newtype" feature:
> 
> struct Length: Double {
> 	static let tolerance: Double = 0.001
> }
> 
> override func ==(a: Length, b: Length) -> Bool {
> 	return (a - b).abs() < Length.tolerance
> }
> 
> Of course, this example leaves many questions, but I hope the principle is clear.

This is also a place where function partial application might be interesting:

func equalityWithTolerance(tolerance: Double) -> (Double, Double) -> Bool {
  return {
    var exp0 = 0, exp1 = 0
    frexp($0, &exp0)
    frexp($1, &exp1)
    return abs($0 - $1) < scalb(tolerance, max(exp0, exp1))
  }
}

If you could locally bind operators, you could then do this:

func compareLengths(x: Double, y: Double) -> Bool {
  let (==) = equalityWithTolerance(0x1p-44)
  return x == y // Uses local (==)
}

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


More information about the swift-evolution mailing list