-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmtwist.c
99 lines (78 loc) · 2.35 KB
/
mtwist.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*
Copyright (C) 2014 Stephen M. Cameron
Author: Stephen M. Cameron
This file is part of Gaseous Giganticus.
Gaseous Giganticus is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Gaseous Giganticus is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Gaseous Giganticus; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* See http://en.wikipedia.org/wiki/Mersenne_twister */
#include <stdlib.h>
#include <string.h>
#include "mtwist.h"
struct mtwist_state {
uint32_t mt[624];
uint32_t index;
};
struct mtwist_state *mtwist_init(uint32_t seed)
{
int i;
struct mtwist_state *mtstate;
mtstate = malloc(sizeof(*mtstate));
if (!mtstate)
return mtstate;
memset(mtstate, 0, sizeof(*mtstate));
mtstate->index = 0;
mtstate->mt[0] = seed;
for (i = 1; i < 624; i++) {
const uint64_t a = 1812433253ULL;
uint64_t b = (uint64_t) mtstate->mt[i - 1] >> 30;
uint64_t c = (a * (mtstate->mt[i - 1] ^ b) + i);
mtstate->mt[i] = c & 0x0ffffffffULL;
}
return mtstate;
}
static void generate_numbers(struct mtwist_state *mtstate)
{
int i;
for (i = 0; i < 624; i++) {
uint32_t y = (mtstate->mt[i] & 0x80000000)
+ (mtstate->mt[(i + 1) % 624] & 0x7fffffff);
mtstate->mt[i] = mtstate->mt[(i + 397) % 624] ^ (y >> 1);
if (y % 2)
mtstate->mt[i] = mtstate->mt[i] ^ 2567483615;
}
}
uint32_t mtwist_next(struct mtwist_state *mtstate)
{
if (mtstate->index == 0)
generate_numbers(mtstate);
uint32_t y = mtstate->mt[mtstate->index];
y = y ^ (y >> 11);
y = y ^ ((y << 7) & 2636928640);
y = y ^ ((y << 15) & 4022730752);
y = y ^ (y >> 18);
mtstate->index = (mtstate->index + 1) % 624;
return y;
}
float mtwist_float(struct mtwist_state *mtstate)
{
return (float) mtwist_next(mtstate) / (float) 0xfffffffeUL;
}
int mtwist_int(struct mtwist_state *mtstate, int n)
{
return (int) (mtwist_next(mtstate) % n);
}
void mtwist_free(struct mtwist_state *mt)
{
if (mt)
free(mt);
}