Three floating point questions

Don nospam at nospam.com
Wed Aug 25 17:32:23 PDT 2010


bearophile wrote:
> This program prints (dmd 2.048):
> 7ff4000000000000
> 7ffc000000000000
> 
> // program #1
> import std.stdio: writeln, writefln;
> import std.string: format;
> void main() {
>     string toHex(T)(T x) {
>         string result;
>         ubyte* ptr = cast(ubyte*)&x;
>         foreach (i; 0 .. T.sizeof)
>             result = format("%02x", ptr[i]) ~ result;
>         return result;
>     }
>     writeln(toHex(double.init));
>     writefln("%x", cast(ulong)double.init);
> }
> 
> Do you know what cast(ulong) is doing here?

Turning it from a signalling nan to a quiet nan.

> ---------------------------
> 
> This program prints (dmd 2.048)::
> -nan
> 
> // program #2
> import std.stdio: writeln;
> void main() {
>     writeln(0.0 / 0.0);
> }
> 
> Is it a bug of writeln?

You mean, because it's a negative nan?

> ---------------------------
> 
> Do you know why this isn't raising runtime errors?
> 
> // program #3
> import std.math: FloatingPointControl;
> import std.c.stdlib: atof;
> void main() {
>     double d3 = atof("3.0");
>     double x; // nan
>     FloatingPointControl fpc;
>     fpc.enableExceptions(FloatingPointControl.severeExceptions);
>     double r = x * d3;
> }

That's a known bug in the backend, which I still haven't fixed. The 
signalling nans get triggered in the 'double x; ' line.
This happens because there's a difference in the way AMD and Intel deal 
with signalling nans, which is completely unpublicised. So my initial 
testing was inadequate.


More information about the Digitalmars-d-learn mailing list