[swift-evolution] implementing real (floating point) number comparison tolerance as a compiler directive.
jgroff at apple.com
Tue Mar 1 14:00:49 CST 2016
> 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.
> 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.
More information about the swift-evolution