Random double
Ivan Kazmenko
gassa at mail.ru
Wed Apr 24 06:30:37 PDT 2013
On Tuesday, 23 April 2013 at 14:43:15 UTC, qznc wrote:
> I want to generate a random "double" value, excluding wierdos
> like NaN and Infinity. However, std.random.uniform seems to be
> useless. I tried things like
>
> std.random.uniform( double.min, double.max);
> std.random.uniform(-double.max, double.max);
> std.random.uniform(0.0, double.max);
>
> However, I just get Inf values. :(
I've just tried to reproduce that. The first line gives a
deprecation warning, the second gives infinities, but the third
line does give me non-infinities. I've checked that under DMD
2.062 on Windows, and the hardware is Intel Xeon E5450.
Here is an example:
-----
import std.random;
import std.stdio;
void main ()
{
foreach (i; 0..5)
{
double x = uniform (-double.max, +double.max);
writefln ("%25a %30.20g", x, x);
}
foreach (i; 0..5)
{
double x = uniform ( 0, +double.max);
writefln ("%25a %30.20g", x, x);
}
}
-----
And an example output is:
-----
inf inf
inf inf
inf inf
inf inf
inf inf
0x1.9d6fad0f9d6f9p+1023 1.4516239851099787345e+308
0x1.b53e4c11b53e3p+1020 1.919017005286872499e+307
0x1.5dc7e6d15dc7dp+1020 1.5351529811186840176e+307
0x1.bd608187bd606p+1023 1.5637717442069522658e+308
0x1.e38d5871e38d4p+1023 1.6978092693521789428e+308
-----
Perhaps "std.random.uniform(-double.max, double.max);" call does
indeed cause overflow. If the example does not work for you, try
"double.max / 2" or "double.max / 4" boundary instead.
That said, note that the values generated this way will have
exponent close to the maximal possible (1024), and that may be
not the only case you wish to cover. Your suggestion to generate
64-bit patterns instead of real numbers, probably excluding
special values (all-0 or all-1), sounds like the way to go. I'd
include some important cases (like +-0 and +-1) manually too.
Ivan Kazmenko.
More information about the Digitalmars-d-learn
mailing list