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

David Sweeris davesweeris at mac.com
Wed Mar 2 14:45:28 CST 2016

What about this?
infix operator ≈ {precedence 255}
func ≈ (value: Double, tolerance: Double) -> (value: Double, tolerance: Double) {
    return (value: value, tolerance: tolerance)
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.

- Dave Sweeris

Sent from my iPhone

> On Mar 1, 2016, at 14:00, Joe Groff via swift-evolution <swift-evolution at swift.org> wrote:
>> On Mar 1, 2016, at 10:28 AM, ted van gaalen via swift-evolution <swift-evolution at swift.org> wrote:
>> in relation to my message about handling floating point number comparisation tolerance in e.g. a .stride function, wouldn't this be better handled by a compiler directive?
>> For example:
>>  @floatingPointComparisonTolerance = 0.001
>>   // all source that follows this will be compiled with this value
>>   // until reset or another value is specified with this directive.
>>  if fp1 == fp2    // will be evaluated with the above specified tolerance. 
>>  for v in minival.stride(to: maxival, by: 0.1)
>>  for e from -1.0 to 123.45 by 0.1       // also in loops of course, as here in the for loop       variant I will propose.
>>  @resetFloatingPointComparisonTolerance()
>> At any time, you should be able to change @floatingPointComparisonTolerance,
>> which will have its effect on source lines that follow it.
> "Floats are inaccurate, let's just add random tolerances in" is a naive outlook on floating-point numerics. There are invariants which carefully-written floating point code can expect to hold in a lot of cases. We could provide tolerant comparison operations, but global state would be a poor way of doing so, and imposing this behavior on the standard comparison operators would be problematic. It'd be better to provide methods IMO, so that e.g. `fp1.equals(fp2, tolerance: 0x1p-44)` performed a comparison with a proportional tolerance check.
> -Joe
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160302/a3d82757/attachment.html>

More information about the swift-evolution mailing list