Mail Archives: djgpp/1994/09/26/09:52:13
>> It seems that rand() returns alternately an even and an odd number
>> result += ((rand() % _sides) + 1);
>
>It is not uncommon to find inadequate pseudorandom generators. One thing
>which may help when generating a small number from a random value is to make
>the number depend on the high order bits returned by rand(). Right shifting
>as many bits as possible before doing the modulo operation will probably work.
The book "Numerical Recipies" and its counterpart "Numerical Recipies in C"
published by the Cambridge University Press go to great length describing
random number generators. They emphasize that system supplied random number
generators should be used with great caution. The authors also confirm what
Mr.Babcock has stated: that many such system generated rand() functions
often have their lower order (least significant bits) much less random than
their higher order (most significant bits).
For your application, they recommend the following:
roll += int(rand()*_sides) + 1;
This implementation is also attractive because it does not involve a divide
(the %) and therefore should be somewhat faster.
However, they recommend that if you want to develop software that is
portable and behaves the same from machine to machine, you should implement
your own rand() function. They give a number of algorithms to choose from.
Their chapter on random number generators is well worth reading. The
authors are W.H.Press, B.P.Flannery, S.A.Teukolsky and W.T.Vetterling. The
C version of the book also comes with a diskette and source code for many
mathematical functions such as the rand() functions.
Happy randomizing!
Richard Young,
Signal Processing Engineer,
Communications Research Centre,
Ottawa, Canada.
- Raw text -