template bug?
Marius Muja
mariusm at cs.ubc.ca
Fri Feb 29 10:46:23 PST 2008
Because of the nature of floating point numbers, you shouldn't use
equality(==) to compare floating point numbers.
Instead of n==1 you should write something like abs(n-1)<eps (where eps
is a small number)
Denton Cockburn wrote:
> In DMD 2.011
>
> import std.stdio;
>
> template factorial(real n)
> {
> static if (n == 1)
> const factorial = 1;
> else const factorial = n * factorial!(n - 1);
> }
>
> void main()
> {
> writefln(factorial!(5));
> }
>
> produces: -3.10504e+231
>
> when the template is changed to accept an int instead of a real, it
> produces the right output: 120
>
> What's the cause of this?
>
> Note: in 1.027, the version accepting a real still produces the correct
> output of 120.
More information about the Digitalmars-d
mailing list