[swift-users] FloatingPoint equality ..

David Sweeris davesweeris at mac.com
Thu Jun 29 17:14:42 CDT 2017


I'd probably do this:
precedencegroup FauxTwoPartOperatorPrecedence {
  associativity: right
  higherThan: BitwiseShiftPrecedence
}
public struct VaE<T> {
  var value: T
  var epsilon: T
}
infix operator ± : FauxTwoPartOperatorPrecedence // `±` is typed "shift-opt-=", at least with macOS's default QWERTY US keyboard layout
public func ± <T: BinaryFloatingPoint> (value: T, epsilon: T) -> VaE<T> {
  return VaE(value: value, epsilon: epsilon)
}
public func == <T: BinaryFloatingPoint> (lhs: T, rhs: VaE<T>) -> Bool {
  return lhs <= (rhs.value + rhs.epsilon) && lhs >= (rhs.value - rhs.epsilon)
}

0.0 == 0.0 ± 0.1 // true
1.0 == 0.0 ± 0.1 // false
-0.3 == 0.0 ± 0.5 // true

(or use something like `+-`, if you prefer your custom operators to be not quite that custom)

Hope that helps,
- Dave Sweeris

> On Jun 29, 2017, at 2:20 PM, Gavin Eadie via swift-users <swift-users at swift.org> wrote:
> 
> .. agreed but this looks too awful (and is mostly a joke!)
> 
>     return a >= b.nextDown.nextDown.nextDown.nextDown && a <= b.nextUp.nextUp.nextUp.nextUp
> 
> Thanks, friends, for your insights and info .. Gavin
> 
> On Thu, Jun 29, 2017 at 3:30 PM, Taylor Swift via swift-users <swift-users at swift.org <mailto:swift-users at swift.org>> wrote:
> 
> (b) one ULP is almost never a tolerance you want to use. It’s much too small for almost all computations, and too large for most of the remaining ones.
> 
> – Steve
> 
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org <mailto:swift-users at swift.org>
> https://lists.swift.org/mailman/listinfo/swift-users <https://lists.swift.org/mailman/listinfo/swift-users>
> 
> 
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


More information about the swift-users mailing list