Quote:
>>One solution, suggested in the faq <polite jab>, is:
>> (int)((double)rand() / ((double)RAND_MAX + 1) * N)
>Minor point. You have a typo. That should be
> (int)((double)rand() / ((double)RAND_MAX + 1) / N)
Actually, that's not a typo. I asked the original question before reading
a recent version of the FAQ. (The copy I had was several months old.)
The code above should be:
(int)((double)rand() / ((double)RAND_MAX + 1) * N)
rand() / (RAND_MAX + 1) will give a value between 0 and 1 when cast as a
double. One then multiplies by the integer N to get a value between 0 and
N - 1. (Now, I just have to make this work with Random() on the Macintosh
which returns a signed short int and has no definition for RAND_MAX....Aw,
it won't be hard.)
My original question was why I seemed to get better results with a method that
the FAQ does not recommend than the results I got with the recommended method.
The answer, in a nut shell, was that I was not casting the values as above and
was always getting a value of 0. Anyway, this subject has been beaten to
death in this newsgroup and in e-mail. I promise to refrain from asking any
more questions on this topic, until someone comes up with a way for a computer
to get truly random integers (without attaching a roulette wheel).
+----------------------------+-----------------------------+
| Jason Stephenson | "Curiouser and curiouser," |
+----------------------------+-----------------------------+