[swift-evolution] Pre-proposal: Safer Decimal Calculations

Haravikk swift-evolution at haravikk.me
Mon Mar 21 09:04:40 CDT 2016


> On 20 Mar 2016, at 17:54, Rainer Brockerhoff via swift-evolution <swift-evolution at swift.org> wrote:
> 
> On 3/20/16 14:43, Andrey Tarantsov via swift-evolution wrote:
>> I have no stake in this proposal, except for:
>> 
>>> I suggest, therefore, that this acceptance be indicated by an
>>> annotation to the literal; a form such as ~0.1 might be easiest to 
>>> read and implement, as the prefix ~ operator currently has no
>>> meaning for a floating-point value.
>> 
>> Whatever you do, don't touch the literals! I specify NSTimeIntervals
>> of 0.1, 0.2, 0.25 etc all over the place, and I couldn't care less if
>> my animations are one femtosecond off.
>> 
>> Don't pollute everyone's apps with tildes just because there's a
>> niche that needs to care about precision loss.
> 
> Yes, I'm now agreeing that the ideal solution is to leave the whole
> binary floating-point mess alone and write a reasonable `Decimal` type.
> I'll update my text accordingly when I find time.

The alternative would be to make the Decimal type the default anywhere that Double or Float isn’t used; while this may be overkill, it shouldn’t impact performance of most applications. At this point the less-safe but higher performance types would be opt-in by either specifying the type or using the tilde operator.

This could actually expand the definition of the ± on constants to instead imply “pick the type that can represent this”, so 0.1±0.01 would pick Double, Float or Decimal as appropriate, favouring the higher performance types only if they can represent that value without exceeding the allowable error.

It is a tricky area though, Swift does have a goal of safety so it may be worth pushing a change that promotes that, even if it means that means a few changes to get maximum performance back; this could be partly avoided by the way the change is handled though, providing warnings where the intent is ambiguous, or assuming performance over safety for existing code?


More information about the swift-evolution mailing list