At 3:28 PM +0200 06/26/00, Dave Lippincott wrote:
>Somebody from Palm posted a great message on how to properly generate random
>numbers on the Palm OS. (it might have been Bob).  I can't find a copy in
>the archives but hopefully someone else has a copy.

Are you thinking of this one?

                        --Bob

Date: Fri, 19 Feb 1999 19:36:55 -0800
From: Bob Ebert <[EMAIL PROTECTED]>
Subject: Re: SysRandom() working poorly; clock based?
To: [EMAIL PROTECTED]
Cc: Palm Developers Forum List <[EMAIL PROTECTED]>
Mime-Version: 1.0
Precedence: Bulk
Reply-To: [EMAIL PROTECTED]

At 6:08 PM -0800 2/19/99, Eric House wrote:
>Tile selection in my Scrabble clone "Crosswords" happens in response
>to user actions, but underneath I just grab "random" tiles out of the
>bag using this code:
>
>index = ((((long) SysRandom(0)) * gNumTilesLeft) / ((long) sysRandomMax + 1));
>
>which I stole from one of the official examples.

Really?  Which one?  ...that's kind of an odd way to limit a random number.

For one thing, that will overflow a long if gNumTilesLeft is more than
about 64K, and go negative if gNumTilesLeft > 32K.  Admittedly, that's not
possible with Scrabble where gNumTilesLeft is always less than 100.

You might look at the code generated and make sure the operations are
really all done with longs.  In particular, sysRandomMax is just a constant
= 0x7FFF, so if adding one is done by the compiler before the long cast,
you could be sign-extending 0x8000 into a long, which would give really
unpredictable results.  Also the types of gNumTilesLeft and index might be
limiting the computation to a 16-bit quantity.

Anyway, why not use the more traditional (and simpler) form below.  It even
avoids long multiplies or divides.  The low bits of the SysRandom result
should be reasonably random, so you don't have to worry about blowing the
randomness if you use this technique.

        index = SysRandom(0) % gNumTilesLeft;

                        --Bob

P.S. SysRandom is pretty simple, but should generate reasonably random
numbers.  You should not have to mess with the seed each time.

Also, if you want more randomness, an easy way to improve a lame random
number generator is to generate and array of random numbers, then pick a
number randomly from that array and replace the array element with a newly
generated random number.  The quality of the random numbers generated
increases with the size of the array.

That is:
 #define kSetSize 10            // increase this to improve randomness
 static int set[kSetSize];

// build the set initially
 int i;
 for (i = 0; i < kSetSize; i++)
        set[i] = SysRandom(0);

// get a "more" random number
  int slot = SysRandom(0) % kSetSize;
  int result = set[slot];
  set[slot] = SysRandom(0);
  return result;



-- 
For information on using the Palm Developer Forums, or to unsubscribe, please see 
http://www.palmos.com/dev/tech/support/forums/

Reply via email to