~ubuntu-branches/ubuntu/trusty/numactl/trusty

« back to all changes in this revision

Viewing changes to mt.c

  • Committer: Bazaar Package Importer
  • Author(s): Ian Wienand
  • Date: 2006-01-04 10:25:27 UTC
  • mfrom: (1.1.1 upstream)
  • Revision ID: james.westby@ubuntu.com-20060104102527-1seu1f5eafl9iuoc
Tags: 0.9-1
* New upstream
* Most patches accepted into upstream; see upstream changelog or
  debian/patches/README in source package for history

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* Mersenne twister implementation from Michael Brundage. Public Domain. 
 
2
   MT is a very fast pseudo random number generator. This version works
 
3
   on 32bit words.  Minor changes by AK. */
 
4
#include <stdlib.h>
 
5
#include "mt.h"
 
6
#define MT_LEN       624
 
7
 
 
8
int mt_index;
 
9
unsigned int mt_buffer[MT_LEN];
 
10
 
 
11
void mt_init(void) 
 
12
{
 
13
    int i;
 
14
    srand(1);
 
15
    for (i = 0; i < MT_LEN; i++)
 
16
        mt_buffer[i] = rand();
 
17
    mt_index = 0;
 
18
}
 
19
 
 
20
#define MT_IA           397
 
21
#define MT_IB           (MT_LEN - MT_IA)
 
22
#define UPPER_MASK      0x80000000
 
23
#define LOWER_MASK      0x7FFFFFFF
 
24
#define MATRIX_A        0x9908B0DF
 
25
#define TWIST(b,i,j)    ((b)[i] & UPPER_MASK) | ((b)[j] & LOWER_MASK)
 
26
#define MAGIC(s)        (((s)&1)*MATRIX_A)
 
27
 
 
28
unsigned int mt_random(void) 
 
29
{
 
30
    unsigned int * b = mt_buffer;
 
31
    int idx = mt_index;
 
32
    unsigned int s;
 
33
    int i;
 
34
        
 
35
    if (idx == MT_LEN*sizeof(unsigned int)) {
 
36
        idx = 0;
 
37
        i = 0;
 
38
        for (; i < MT_IB; i++) {
 
39
            s = TWIST(b, i, i+1);
 
40
            b[i] = b[i + MT_IA] ^ (s >> 1) ^ MAGIC(s);
 
41
        }
 
42
        for (; i < MT_LEN-1; i++) {
 
43
            s = TWIST(b, i, i+1);
 
44
            b[i] = b[i - MT_IB] ^ (s >> 1) ^ MAGIC(s);
 
45
        }
 
46
        
 
47
        s = TWIST(b, MT_LEN-1, 0);
 
48
        b[MT_LEN-1] = b[MT_IA-1] ^ (s >> 1) ^ MAGIC(s);
 
49
    }
 
50
    mt_index = idx + sizeof(unsigned int);
 
51
    return *(unsigned int *)((unsigned char *)b + idx);
 
52
}