Friday, June 4, 2010

randow number generators

Copied from wiki...
The "linear congruential" generator and
The "Multiply-With-Carry" generator of G. Marsaglia

#include <stdio.h>
#include <time.h>

static uint m_z = 0;    

uint simple_random(a,b,m)
{   
   m_x = (a*m_x + b) % m;
   return m_x;
}

static uint m_w = 0;    /* must not be zero */
static uint m_z = 0;    /* must not be zero */

void init_random()
{
  time_t seconds;
  seconds = time (NULL);
  m_w = seconds & 0xffff;
  m_z = (seconds >> 16) & 0xffff;
} 

uint get_random()
{
    m_z = 36969 * (m_z & 0xffff) + (m_z >> 16);
    m_w = 18000 * (m_w & 0xffff) + (m_w >> 16);
    return (m_z << 16) + m_w;  /* 32-bit result */
}

No comments:

Post a Comment