Fun with floating point

Meta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Feb 7 18:07:43 PST 2015


On Saturday, 7 February 2015 at 16:06:14 UTC, Kenny wrote:
> Hi, D community!
>
> I have this program:
>
> import std.stdio;
> import std.conv;
>
> int main(string[] argv)
> {
>       float eps = 1.0f;
>       float f = 0.0f;
>       while (f + eps != f)
>           f += 1.0f;
>
>       writeln("eps = " ~ to!string(eps) ~ ", max_f = " ~
> to!string(f));
>       return 0;
> }
>
> According to the languge specification what result would you
> expect from its execution?
>
> When running similar C++ program (VS 2013) the loop terminates
> and I get t = 2^24 = 16777216.
>
> Does D language specifies that loop will be terminated for this
> program or  ?
>
> I compiled with DMD and it hungs.
> Details about assembly generated by DMD can be found here:
> http://stackoverflow.com/questions/28380651/floating-point-maxing-out-loop-doesnt-terminate-in-d-works-in-c
>
> Thanks.

A point of advice that Walter gives for situations like these is 
to ensure that your algorithm has a minimum required precision to 
work correctly but not a maximum. As Peter Alexander mentioned, 
DMD performs intermediate calculations at higher precision than 
GDC/LDC and thus your algorithm breaks.


More information about the Digitalmars-d-learn mailing list