Logo Search packages:      
Sourcecode: numactl version File versions  Download package

mt.c

/* Mersenne twister implementation from Michael Brundage. Public Domain. 
   MT is a very fast pseudo random number generator. This version works
   on 32bit words.  Minor changes by AK. */
#include <stdlib.h>
#include "mt.h"
#define MT_LEN       624

int mt_index;
unsigned int mt_buffer[MT_LEN];

void mt_init(void) 
{
    int i;
    srand(1);
    for (i = 0; i < MT_LEN; i++)
        mt_buffer[i] = rand();
    mt_index = 0;
}

#define MT_IA           397
#define MT_IB           (MT_LEN - MT_IA)
#define UPPER_MASK      0x80000000
#define LOWER_MASK      0x7FFFFFFF
#define MATRIX_A        0x9908B0DF
#define TWIST(b,i,j)    ((b)[i] & UPPER_MASK) | ((b)[j] & LOWER_MASK)
#define MAGIC(s)        (((s)&1)*MATRIX_A)

unsigned int mt_random(void) 
{
    unsigned int * b = mt_buffer;
    int idx = mt_index;
    unsigned int s;
    int i;
      
    if (idx == MT_LEN*sizeof(unsigned int)) {
        idx = 0;
        i = 0;
        for (; i < MT_IB; i++) {
            s = TWIST(b, i, i+1);
            b[i] = b[i + MT_IA] ^ (s >> 1) ^ MAGIC(s);
        }
        for (; i < MT_LEN-1; i++) {
            s = TWIST(b, i, i+1);
            b[i] = b[i - MT_IB] ^ (s >> 1) ^ MAGIC(s);
        }
        
        s = TWIST(b, MT_LEN-1, 0);
        b[MT_LEN-1] = b[MT_IA-1] ^ (s >> 1) ^ MAGIC(s);
    }
    mt_index = idx + sizeof(unsigned int);
    return *(unsigned int *)((unsigned char *)b + idx);
}

Generated by  Doxygen 1.6.0   Back to index