Casting double to ulong weirdness

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Tue Aug 25 10:40:06 PDT 2015


On 8/25/15 11:56 AM, "Ola Fosheim =?UTF-8?B?R3LDuHN0YWQi?= 
<ola.fosheim.grostad+dlang at gmail.com>" wrote:
> On Tuesday, 25 August 2015 at 14:54:41 UTC, Steven Schveighoffer wrote:
>> As bachmeier says, it's not something that's easy to get right.
>
> Are you sure you follow IEEE 754 recommendations? Floating point
> arithmetics should be reproducible according to the chosen rounding mode.
>
> https://en.wikipedia.org/wiki/IEEE_floating_point#Reproducibility
>
> «The reproducibility clause recommends that language standards should
> provide a means to write reproducible programs (i.e., programs that will
> produce the same result in all implementations of a language), and
> describes what needs to be done to achieve reproducible results.»
>

I'm not an expert on floating point, but I have written code that uses 
it, and I have gotten it very wrong because I didn't take into account 
the floating point error (worst was causing an infinite loop in a corner 
case).

I'll note that D does exactly what C does in the case where you are 
using 80-bit floating point numbers.

There is definitely an issue with the fact that storing it as a double 
causes a change in the behavior, and that D doesn't treat expressions 
that are typed as doubles, as doubles.

I see an issue with this:

double x = 1.2;

auto y = x * 10.0; // typed as double
writefln("%s %s", cast(ulong)y, cast(ulong)(x * 10.0)); // 12 11

IMO, these two operations should be the same. If the result of an 
expression is detected to be double, then it should behave like one. You 
can't have the calculation done in 80-bit mode, and then magically throw 
away the rounding to get to 64-bit mode.

I think Marcio has a point that this is both surprising and troublesome. 
But I think this is an anecdotal instance of a toy example. I'd expect 
real code to use adjustments when truncating to avoid the FP error (this 
obviously isn't his real code).

-Steve


More information about the Digitalmars-d mailing list