The Daily Static
  The Daily Static
UF Archives
Register
UF Membership
Ad Free Site
Postcards
Community

Geekfinder
UFie Gear
Advertise on UF

Forum Rules
& FAQ


Username

Password


Create a New Account

 
 

Back to UserFriendly Strip Comments Index

random numbers by bongodrums2002-10-19 14:29:03
  rand() % <highest number> + <offset> by DaNutBall2002-10-19 14:46:22
    Beware of low bits of rand() by rberteig 2002-10-19 17:21:30

Standard C rand() is based on a Linear Congruential sequence. Such a sequence is known to produce highly non-random low-order bits. In particular, the least bit will strictly alternate between one and zero on successive calls to rand(). This implies that the modulus is not really the most effective way to reduce the range of values produced.

A better way is to use division and keep the quotient. The quotient is strongly influenced by the highest order bits, and is more therefore more random than the remainder (modulus).

For example, assuming RAND_MAX fits in a short, the following will produce a random short in the range [low,high). Generalizing to a RAND_MAX that fits in a long is left as an exercise, but be sure to worry about arithmetic overflow in the multiply. Depending on your hardware and application, it may be easier to do the arithmetic in floating point and cast back to a suitable integer at the end.

short ranged_rand(short low, short high)
{
    long r = rand() * (long)(high-low);
    r /= RAND_MAX;
    r += low;
    return (short)r;
}

I suppose I should admit that the above fragment has never seen a compiler, and therefore probably has at least one typo or outright mistake lurking. Another exercise for the reader :-)

[ Reply ]

 

[Todays Cartoon Discussion] [News Index]

Come get yer ARS (Account Registration System) Source Code here!
All images, characters, content and text are copyrighted and trademarks of J.D. Frazer except where other ownership applies. Don't do bad things, we have lawyers.
UserFriendly.Org and its operators are not liable for comments or content posted by its visitors, and will cheerfully assist the lawful authorities in hunting down script-kiddies, spammers and other net scum. And if you're really bad, we'll call your mom. (We're not kidding, we've done it before.)