std.random

Carlos Santander csantander619 at gmail.com
Tue Apr 11 13:45:56 PDT 2006


pragma escribió:
> 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).
> 

In fact, there's no need to: std.random ctor does that already.

> 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


-- 
Carlos Santander Bernal



More information about the Digitalmars-d-learn mailing list