std.random
pragma
pragma_member at pathlink.com
Tue Apr 11 11:41:13 PDT 2006
In article <e1gfcb$2a7e$1 at digitaldaemon.com>, Charles says...
>
>How do i get a number in the range -0.5 to 0.5 ?
Unfortunately, std.random doesn't do anything outside of uint for randomness (as
you've probably already learned). This doesn't leave you completely out of
luck.
Since the range returned by rand() is distributed over 0 to uint.max, all you
need to do is map this range to the range of floating point values you want.
/**/ double result = ((cast(double)rand())/uint.max); // result = [0..1]
/**/ result = result -0.5 // shift the range down by 0.5
Remember to call rand_seed(), as this kicks things off with the random number
generator. The index parameter is useful for replaying simulations or games,
when you want to re-create the sequence of random values returned by rand() (its
deterministic after all, and not truely random).
Fot that I'd reccomend using the current time for seed and 0 as the index. The
std.date package has a function that will work great for the time, but we need
to truncate it to a uint as it's too big (long).
/**/ rand_seed(cast(uint)getUTCTime,0); // use cast() to truncate
For completeness, here is a complete listing that displays 20 random numbers:
/**/ import std.random;
/**/ import std.date;
/**/ import std.stdio;
/**/
/**/ void main(){
/**/ rand_seed(cast(uint)getUTCtime(),0);
/**/
/**/ for(int i=0; i<20; i++){
/**/ double result = ((cast(double)rand())/uint.max);
/**/ result = result - 0.5;
/**/ writefln("value: %f",result);
/**/ }
/**/ }
Enjoy!
- EricAnderton at yahoo
More information about the Digitalmars-d-learn
mailing list