Bug of the sqrt() compiled by DMD

Salih Dincer salihdb at hotmail.com
Sun Jun 19 08:36:33 UTC 2022


Hi,

Actually this error is not directly related to `sqrt()` but 
probably related to `cast()` and DMD Compiler v2.0.99. Because 
this no problem occurs in LDC.

  Lets start...

n is an integer but n² doesn't have to be...  `sqrt()` does not 
accept whole number!  So the type of n² is correct.

When the root line is hidden, the 2-stage lines below it will 
toggle  and there is no problem anymore. The problem appears 
exactly at 94906267 and odd numbers.

```d
import std.math, std.stdio;
alias integer = ulong;

void main()
{
   integer n = 94_906_260;
   for( ; n <= 94_906_270; ++n)
   {
     integer root;
     double root2, n2 = n * n;

     root = cast(integer) sqrt(n2);/*
     root2 = sqrt(n2);
     root = cast(integer) root2;
     //**** no problem ****/

     root.write;
     if(root != n)
     {
       n.writefln!" != %s";
     }
     else n.writefln!" == %s";
   }
}
```

**DMD Compiler v2.0.99:**
> 94906260 == 94906260
> 94906261 == 94906261
> 94906262 == 94906262
> 94906263 == 94906263
> 94906264 == 94906264
> 94906265 == 94906265
> 94906266 == 94906266
> 94906266 != 94906267
> 94906268 == 94906268
> 94906268 != 94906269
> 94906270 == 94906270

```d
     //...

     //root = cast(integer) sqrt(n2);/*
     root2 = sqrt(n2);
     root = cast(integer) root2;
     //**** no problem ****/

     //...
```

**2-stage casting with DMD:**
> 94906260 == 94906260
> 94906261 == 94906261
> 94906262 == 94906262
> 94906263 == 94906263
> 94906264 == 94906264
> 94906265 == 94906265
> 94906266 == 94906266
> 94906266 == 94906267
> 94906268 == 94906268
> 94906268 == 94906269
> 94906270 == 94906270

SDB at 79


More information about the Digitalmars-d mailing list