Army1987 wrote:

> In the FAQ I read:

> If you just need to do something with probability 1/N, you could use

>

> if(rand() < (RAND_MAX+1u) / N)
In fairness to the FAQ, it goes on to explain that this

technique is only suitable for N much smaller than RAND_MAX.

> This has an obvious bias problem which is easily fixed (not

> perfectly, but an improvement).

> [...]

> if (rand() < (RAND_MAX + 1u + N / 2) / N)
That is, rounding the quotient instead of truncating it.

Yes, that could give a slightly more accurate result. How

much more accurate? By less than one part in (RAND_MAX+1u),

which could be as much as 0.0000305+ for the smallest legal

RAND_MAX.

But rounding can still leave you with an error of up to

half that amount! If N is large enough that the truncation

error of 0.0031% is significant, the rounding error of 0.0015%

is probably *also* significant. Or to put it another way, if

N is large enough to make rounding attractive, it is also

large enough to make rounding ineffective; the improvement is

only of interest when it's not good enough. For N that large,

I think you should be using a rejection technique along the

lines of the one illustrated in the FAQ.

--

Eric Sosman

http://www.velocityreviews.com/forums/(E-Mail Removed)lid