Double implicitly converted to real

deadalnix deadalnix at gmail.com
Thu Nov 3 08:59:32 PDT 2011


Le 03/11/2011 15:39, Charles McAnany a écrit :
> Hi. I noticed that one of the guarantees in TDPL is that any code that is valid in both C
> and D should compile with the same result. But I'm seeing a different behavior here.
> I'm trying to find the smallest double for which the comparison x+1/x = x is true.
> I take a number way too small, and a number way too large, and then binary search (for 100
> iterations) to get the desired number:
>
> //add appropriate import std.stdio or #include<stdio.h>
> int main(){
>      double min = 1;
>      double max = 10000000000;
>      int iters = 0;
>      double average;
>      for(;iters<100; iters++){
>          average = (min+max)/2;
>          if( average + 1/average == average)
>              max = average;
>          else
>              min = average;
>      }
>      printf("%f",average);
>      return 0;
> }
>
> Here's the problem:
> D (under DMD v2.051) gives this answer: 4294967296.000000
> C (gcc version 3.4.6 20060404): 134217728.000000
>
> It seems D is implicitly converting double to real. Is this the usual behavior?
>
> Cheers,
> Charles.

As long as you don't loose information, you can cast implicitely in D. 
If you loose information (or the compiler cannot prove that your are not 
loosing information) then an explicit cast is required.

So this implicit cast is expected.

Now, you are not using real in your code, so you shouldn't use real 
anywhere. Are you sure this is the actual issue ?

Finally, both compiler you are using are rather old ones. dmd is in 
version 2.056 now and gdc has 4.6.2 version (and using 2.055 frontend).


More information about the Digitalmars-d-learn mailing list