Boost logo

Boost :

From: Carlo Wood (carlo_at_[hidden])
Date: 2004-09-03 22:03:17

On Fri, Sep 03, 2004 at 08:37:20PM -0600, Jonathan Turkanis wrote:
> > 2. tutorial docs:
> >
> > The first code example:
> > s[z] = (char) (rand() * 256 / RAND_MAX);
> > I think this causes overflows way too often.
> > s[z] = (char) (rand() % 256);
> > is more likely intended even if it
> > adds small bias.

Please no, this is in every FAQ on the use of rand().
The lower bits of rand() are not very random and
using (rand() % 256) would be a classical case of
misuse of that function.

The use of (rand() * 256 / RAND_MAX) is fine because
RAND_MAX can be devided by 256. For the general way
one is supposed to devide the result of rand() in
buckets. Ie, if you want to find an integer random
number in the range [0, n> then you'd devide the
results of rand() into n equally sized buckets and
ignore results that fall outside of them in order to
get a good distribution namely,
while ((res = (rand() / (RAND_MAX / n))) == n);

Carlo Wood <carlo_at_[hidden]>

Boost list run by bdawes at, gregod at, cpdaniel at, john at