Floating point rounding modes: we should restrict them slightly

Don nospam at nospam.com
Thu Sep 10 12:24:48 PDT 2009


Michel Fortin wrote:
> On 2009-09-10 04:24:38 -0400, Don <nospam at nospam.com> said:
> 
>> PROPOSAL:
>> Change the spec by adding the line to float.html:
>> "If the floating-point rounding mode is changed within a function, it 
>> must be restored before the function exits. If this rule is violated 
>> (for example, by the use of inline asm), the rounding mode used for 
>> subsequent calculations is undefined."
>>
>> This slight tightening of semantics can have a significant benefit for 
>> all floating-point code.
> 
> I perfectly agree. I'm just wondering how to enforce it in the language.

Yes, it's not so obvious how to enforce it. However, in reality it's a 
rarely-used, system level feature, so relying on convention probably 
isn't too terrible in the short term.

> 
> Later in the thread you say:
> 
>> ... have an RAII struct to restore the mode automatically. But that's 
>> just syntax sugar.
> 
> But how do you prevent someone from writing:
> 
>     auto s = new roundingMode(...);

scope _should_ take care of that. I'm not sure that it does. Still, we 
just need to make it easy to do the right thing, and difficult to do the 
wrong thing.

> The only way you can really make sure it's scoped to a specific function 
> is to call it from another function:
> 
>     R performWithRoundingMode(R)(flag roundingMode, lazy R result)
>     {
>         flag oldRoundingMode = getRoundingMode();
>         setRoundingMode(roundingMode);
>         try
>             return result;
>         finally
>             setRoundingMode(oldRoundingMode);
>     }
> 
>     auto i = performWithRoundingMode(TOWARDS_ZERO, 12 * 12);
> 
> Here you can't escape the scoping requirements.

Hmmm. Not ideal, but could be worse.
But anyway, the important thing is to codify in the spec that the 
floating point state must not change randomly.
For discussing syntax, I think we really need an interval arithmetic 
module, so that we can ensure it all works well.



More information about the Digitalmars-d mailing list