Mail Archives: djgpp/1999/02/01/14:47:09
Eli Zaretskii wrote...
>
>On Sun, 31 Jan 1999, Rehammar wrote:
>
>> a=range*(float)random()/(float)RAND_MAX;
>>
>> but I didn't likt the way of doing it, is there no other way ??
>
>The other way is to say "random()%(range - 1)" (assuming `range' is an
>int), but that might yield less random results, as lower bits returned
>by RNGs are usually not-so-random.
>
>What's wrong with what you did in the first place, anyway?
Both method are indeed seen very often in published code, but there are both
not correct!!! That means that the original sequence is not evenly
distributed over the whole range of [0:Limit-1]. The reason is, that such an
arrangement is simply impossible if RAND_MAX is not divisible by 'range' and
this is very likely!
Though the effect lessens if you increase RAND_MAX it is not neglectible.I
would not recommend the above methods in a serious application.
One simple fix would be to iterate rand() until its result is in a range,
those length is divisible by 'range'.
For example:
unsigned a,range=17;
do
a = rand();
while (a < ((unsigned)RAND_MAX+1) % range); //be aware of overflow
a%= range;
Hope i have helped.
Oliver Roese
- Raw text -