All pastes #835558 Raw Edit

Unnamed

public text v1 · immutable
#835558 ·published 2007-12-28 22:47 UTC
rendered paste body
/*
 * "Cleaned up" and simplified Mersenne Twister implementation.
 * Vastly smaller and more easily understood and embedded.  Stores the
 * state in a user-maintained structure instead of static memory, so
 * you can have more than one, or save snapshots of the RNG state.
 * Lacks the "init_by_array()" feature of the original code in favor
 * of the simpler 32 bit seed initialization.  Lacks the floating
 * point generator, which is an orthogonal problem not related to
 * random number generation.  Verified to be identical to the original
 * MT199367ar code through the first 10M generated numbers.
 */

#define MT_N 624
#define MT_M 397

struct mt { unsigned int array[MT_N]; int index; };

#define MT(i) mt->array[i]

void mt_init(struct mt *mt, unsigned int seed)
{
    int i;
    MT(0)= seed;
    for(i=1; i<MT_N; i++)
        MT(i) = (1812433253 * (MT(i-1) ^ (MT(i-1) >> 30)) + i);
    mt->index = MT_N+1;
}

unsigned int mt_rand32(struct mt *mt)
{
    unsigned int i, y;
    if(mt->index >= MT_N) {
        for(i=0; i<MT_N; i++) {
            y = (MT(i) & 0x80000000) | (MT((i+1)%MT_N) & 0x7fffffff);
            MT(i) = MT((i+MT_M)%MT_N) ^ (y>>1) ^ (y&1 ? 0x9908b0df : 0);
        }
        mt->index = 0;
    }
    y = MT(mt->index++);
    y ^= (y >> 11);
    y ^= (y << 7) & 0x9d2c5680;
    y ^= (y << 15) & 0xefc60000;
    y ^= (y >> 18);
    return y;
}

/*********************************************************************/

#include <stdio.h>

int main()
{
    struct mt mt;
    mt_init(&mt, 0);
    while(1)
        printf("0x%8.8x\n", mt_rand32(&mt));
    return 0;
}