Mail Archives: djgpp/1999/08/01/15:51:31
On Fri, 30 Jul 1999, Horst Kraemer wrote:
> > > > x = ((double) rand ()) * 100 / RAND_MAX;
> > >
> > > Not exactly the correct method (IIRC), but close:
> > >
> > > x = ((double) rand ()/RAND_MAX) * 100;
> >
> > Care to explain what is the difference?
>
> The difference is that both methods are wrong <g>
>
> A correct formula is
>
>
> int x = (double)rand()*100 / (RAND_MAX+1.0) ;
This will never generate 100, only numbers that are less that 100.
Depending on the case in point, this might or might not be what
the original poster wanted.
> (With the incorrect RAND_MAX instead of RAND_MAX+1.0, the result will
> not be necessarily identical because the division by RAND_MAX is not a
> clean SHIFT of the 2-based exponent of the double value but a regular
> division).
Since the results are meant to be random, I don't see why this effect
should matter, it simply introduces some more random bits near the LSB.
- Raw text -