[comp.lang.c++] Random number generation

ads@gateway.mitre.org (Alexas D. Skucas) (03/11/91)

  Here is a C++ problem that is really giving me
headaches.  I am trying to generate a random number
between 0 and 1.  The rand function returns a huge
number (i.e 3.75658e+08) which I can't seem to be
able to deal with.  I am running the Sun CC compiler.

ANY help would be extremely appreciated. Thanks.

Alex
ads@gateway.mitre.org

juul@diku.dk (Anders Juul Munch) (03/15/91)

ads@gateway.mitre.org (Alexas D. Skucas) writes:


>  Here is a C++ problem that is really giving me
>headaches.  I am trying to generate a random number
>between 0 and 1.  The rand function returns a huge
>number (i.e 3.75658e+08) which I can't seem to be
>able to deal with.  I am running the Sun CC compiler.

>ANY help would be extremely appreciated. Thanks.


Apparently,  rand() on your system returns a number between 
0 and 2**32-1. Just divide by 2**32 and you get numbers 
evenly distributed between 0 and 1.
	The following function should do the trick:

double rand01()
{ return rand()/4294967296.0; }

-- Anders Munch