How do I get random #s?

Jim Adcock jima at hplsla.HP.COM
Fri Feb 10 05:19:23 AEST 1989


/* 1) caveat emptor                       */
/* 2) assumes 16 bit shorts, 32 bit longs */
/* 3) takes about 15 uSec on a mid performance 68020 system, 
      takes about  4 uSec on a 840 system */
/* 4) pseudo random noise generator, 31 bit long shift register,
      Mersenne prime, 16 shifts calculated at a time, returning
      a 16-bit unsigned short.  Sequence length 2,147,483,647 */

static prngshift = 3141592654;
unsigned short prng();

void prnginit(initseed)
unsigned long initseed;
{
    register i;
    initseed *= 456295141;
    prngshift = initseed^3141592654;
    if (!prngshift) prngshift = 3141592654;
    for (i=0; i<6; ++i) prng();
}

unsigned short prng()
{
    register unsigned long  d0, d1;
    register unsigned short lo;

    d1 = prngshift;
    d0 = d1>>16;
    d1 <<= 16;
    d0 |= d1;
    d0 = d0<<1 | d0>>31;
    lo = d0;
    d0 = d0<<4 | d0>>28;
    lo ^= d0;
    d0 = d0<<8 | d0>>24;
    lo ^= d0;
    d0 = d0<<2 | d0>>30;
    lo ^= d0;
    d1 |= lo;
    prngshift = d1;
    return lo;
}



More information about the Comp.lang.c mailing list