Why use float and double instead of real?

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Wed Jul 1 07:15:36 PDT 2009


Don wrote:
> Lars T. Kyllingstad wrote:
>> Is there ever any reason to use float or double in calculations? I 
>> mean, when does one *not* want maximum precision? Will code using 
>> float or double run faster than code using real?
>>
>> I understand they are needed for I/O and compatibility purposes, so I 
>> am by no means suggesting they be removed from the language. I am 
>> merely asking out of curiosity.
>>
>> -Lars
> 
> Size. Since modern CPUs are memory-bandwidth limited, it's always going 
> to be MUCH faster to use float[] instead of real[] once the array size 
> gets too big to fit in the cache. Maybe around 2000 elements or so.
> 
> Rule of thumb: use real for temporary values, use float or double for 
> arrays.


The reason I'm asking is that I've templated the numerical routines I've 
written, so that the user can choose which floating-point type to use. 
Then I started wondering whether I should in fact always use real for 
temporary values inside the routines, for precision's sake, or whether 
this would reduce performance significantly.

 From the answers I've gotten to my question (thanks everyone, BTW!), 
It's not immediately clear to me what is the best choice in general. 
(Perhaps it would be best to have two template parameters, one for 
input/output precision and one for working precision?)

Functions in std.math are defined in a lot of different ways:
   - separate overloaded functions for float, double and real
   - like the above, only float and double versions cast to real
     and call real version
   - only real version
   - templated

Is there some rationale behind these choices?

-Lars


More information about the Digitalmars-d-learn mailing list