I needed a random() function to generate 32-bit random numbers.  After some
research, I used the algorithm in the following code fragment.  This code
generates VERY uniform numbers over a large domain.  IIRC, this code also
solves the 3D domain bug, common in many other PRNG algorithms.

The following code is VERY fast, for a 32-bit number.  If you want to change
the seed, just simply assign the seed variable to whatever you want, like
the time of day, etc (just don't use zero).

Doug.



static Int32 seed = 0xED0000ED;

static Int32 rand32f(void)
{
        UInt32 lo, hi;

        lo = 16807 * (seed & 0xFFFF);
        hi = 16807 * ((UInt32)seed >> 16);
        lo += (hi & 0x7FFF) << 16;

        if (lo > 2147483647)
        {
                lo &= 2147483647;
                ++lo;
        }

        lo += hi >> 15;

        if (lo > 2147483647)
        {
                lo &= 2147483647;
                ++lo;
        }

        seed = lo;
        return (seed);
}


-----Original Message-----
From: Richard Burmeister [mailto:[EMAIL PROTECTED]]
Sent: Sunday June 25, 2000 18:02
To: Palm Developer Forum
Subject: Random number problem


I have been using this function to generate a "random" number:

static UInt16 rand( UInt16 max )
{
 return ( SysRandom(TimGetTicks()) % max );
}

Unfortunately, this only works as expected on an emulated Palm IIIc and
fails on all other devices.  On the devices on which it fails, the problem
is that successive calls in a tight loop generate the same number.  For
example:

for ( i=0; i<25; i++ )
    a[i] = rand(5) + 1;

On an emulated Palm Vx, this might produce the sequence
4,5,5,1,1,2,4,4,5,5,1,3,3,4,4,5,2,2,3,3,4,1,1,2,2

On some devices it is even worse, producing sequences like
4,4,4,4,1,1,3,3,5,5,5,5,2,2,2,2,2,2,3,3,4,4,4,4,2

On an emulated Palm IIIc, this produces a more reasonable
3,4,5,2,3,4,1,2,3,4,2,3,5,1,2,4,5,1,4,5,1,3,4,5,2

Does anyone know why this is happening?  Does anyone have a better idea for
generating a more random series?



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

-- 
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