why the array bounds array

Sergey Gromov snake.scaly at gmail.com
Mon Dec 8 03:22:39 PST 2008


Mon, 8 Dec 2008 06:59:40 +0000 (UTC), BCS wrote:

> Reply to Bill,
> 
>> On Mon, Dec 8, 2008 at 2:57 PM, BCS <ao at pathlink.com> wrote:
>> 
>>> Reply to Michael P.,
>>> 
>>> rand() & TYPES_OF_TILES
>>> 
>>> never use rand like that (the low order bit on many rands toggles
>>> every
>>> single time)
>>> better (I think):
>>> rand() / (TYPES_OF_TILES / RAND_MAX)
>>> 
>> That's a divide by zero, so I don't think that's what you meant.
>> 
>> --bb
>> 
> 
> Oops  x-p
> 
> rand() / (RAND_MAX / TYPES_OF_TILES)

Don't use rand() like this, ever.  ;)  "RAND_MAX / TYPES_OF_TILES" is an
integer expression, it rounds down, therefore your formula gives a
slightly greater range of values than you expect.  You'll get all sorts
of out of bounds errors.

Your best bet is to use a uniform distribution method of the same random
number generator implementation.  There is std.random.uniform() in D2's
Phobos which serves this purpose.  If you don't have an equivalent, your
next stop is "rand() % TYPES_OF_TILES".  It's not strictly uniform but
close if TYPES_OF_TILES is small.


More information about the Digitalmars-d-learn mailing list