Alias std.numeric.FPTemporary
Defines the fastest type to use when storing temporaries of a
calculation intended to ultimately yield a result of type F
(where F
must be one of float
, double
, or real
). When doing a multi-step computation, you may want to store
intermediate results as FPTemporary!F
.
alias FPTemporary(F)
= real;
The necessity of FPTemporary
stems from the optimized
floating-point operations and registers present in virtually all
processors. When adding numbers in the example above, the addition may
in fact be done in real
precision internally. In that case,
storing the intermediate result
in double format
is not only
less precise, it is also (surprisingly) slower, because a conversion
from real
to double
is performed every pass through the
loop. This being a lose-lose situation, FPTemporary!F
has been
defined as the fastest type to use for calculations at precision
F
. There is no need to define a type for the most accurate
calculations, as that is always real
.
Finally, there is no guarantee that using FPTemporary!F
will
always be fastest, as the speed of floating-point calculations depends
on very many factors.
Example
import std .math : approxEqual;
// Average numbers in an array
double avg(in double[] a)
{
if (a .length == 0) return 0;
FPTemporary!double result = 0;
foreach (e; a) result += e;
return result / a .length;
}
auto a = [1.0, 2.0, 3.0];
assert(approxEqual(avg(a), 2));
Authors
Andrei Alexandrescu, Don Clugston, Robert Jacques, Ilya Yaroshenko