-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMT19937.cs
558 lines (480 loc) · 21.9 KB
/
MT19937.cs
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
// Copyright 2007-2008 Rory Plaire (codekaizen@gmail.com)
// Adapted from:
/* C# Version Copyright (C) 2001-2004 Akihilo Kramot (Takel). */
/* C# porting from a C-program for MT19937, originaly coded by */
/* Takuji Nishimura and Makoto Matsumoto, considering the suggestions by */
/* Topher Cooper and Marc Rieffel in July-Aug. 1997. */
/* This library is free software under the Artistic license: */
/* */
/* You can find the original C-program at */
/* http://www.math.keio.ac.jp/~matumoto/mt.html */
/* */
// and:
/////////////////////////////////////////////////////////////////////////////
// C# Version Copyright (c) 2003 CenterSpace Software, LLC //
// //
// This code is free software under the Artistic license. //
// //
// CenterSpace Software //
// 2098 NW Myrtlewood Way //
// Corvallis, Oregon, 97330 //
// USA //
// http://www.centerspace.net //
/////////////////////////////////////////////////////////////////////////////
// and, of course:
/*
A C-program for MT19937, with initialization improved 2002/2/10.
Coded by Takuji Nishimura and Makoto Matsumoto.
This is a faster version by taking Shawn Cokus's optimization,
Matthe Bellew's simplification, Isaku Wada's real version.
Before using, initialize the state by using init_genrand(seed)
or init_by_array(init_key, key_length).
Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The names of its contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Any feedback is very welcome.
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
*/
using System;
namespace Org.Reddragonit.MultiDomain
{
/// <summary>
/// Generates pseudo-random numbers using the Mersenne Twister algorithm.
/// </summary>
/// <remarks>
/// See <a href="http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html">
/// http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html</a> for details
/// on the algorithm.
/// </remarks>
internal class MT19937 : Random
{
private const string _STRING_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
public string NextString(int length)
{
string ret = "";
for (int x = 0; x < length; x++)
ret += _STRING_CHARACTERS[Next(0, _STRING_CHARACTERS.Length - 1)];
return ret;
}
/// <summary>
/// Creates a new pseudo-random number generator with a given seed.
/// </summary>
/// <param name="seed">A value to use as a seed.</param>
public MT19937(Int32 seed)
{
init((UInt32)seed);
}
/// <summary>
/// Creates a new pseudo-random number generator with a default seed.
/// </summary>
/// <remarks>
/// <c>new <see cref="System.Random"/>().<see cref="Random.Next()"/></c>
/// is used for the seed.
/// </remarks>
public MT19937()
: this(new Random().Next()) /* a default initial seed is used */
{ }
public MT19937(long seed)
: this((int)(seed % (long)int.MaxValue))
{
}
/// <summary>
/// Creates a pseudo-random number generator initialized with the given array.
/// </summary>
/// <param name="initKey">The array for initializing keys.</param>
public MT19937(Int32[] initKey)
{
if (initKey == null)
{
throw new ArgumentNullException("initKey");
}
UInt32[] initArray = new UInt32[initKey.Length];
for (int i = 0; i < initKey.Length; ++i)
{
initArray[i] = (UInt32)initKey[i];
}
init(initArray);
}
/// <summary>
/// Returns the next pseudo-random <see cref="UInt32"/>.
/// </summary>
/// <returns>A pseudo-random <see cref="UInt32"/> value.</returns>
public virtual UInt32 NextUInt32()
{
return GenerateUInt32();
}
/// <summary>
/// Returns the next pseudo-random <see cref="UInt32"/>
/// up to <paramref name="maxValue"/>.
/// </summary>
/// <param name="maxValue">
/// The maximum value of the pseudo-random number to create.
/// </param>
/// <returns>
/// A pseudo-random <see cref="UInt32"/> value which is at most <paramref name="maxValue"/>.
/// </returns>
public virtual UInt32 NextUInt32(UInt32 maxValue)
{
return (UInt32)(GenerateUInt32() / ((Double)UInt32.MaxValue / maxValue));
}
/// <summary>
/// Returns the next pseudo-random <see cref="UInt32"/> at least
/// <paramref name="minValue"/> and up to <paramref name="maxValue"/>.
/// </summary>
/// <param name="minValue">The minimum value of the pseudo-random number to create.</param>
/// <param name="maxValue">The maximum value of the pseudo-random number to create.</param>
/// <returns>
/// A pseudo-random <see cref="UInt32"/> value which is at least
/// <paramref name="minValue"/> and at most <paramref name="maxValue"/>.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// If <c><paramref name="minValue"/> >= <paramref name="maxValue"/></c>.
/// </exception>
public virtual UInt32 NextUInt32(UInt32 minValue, UInt32 maxValue) /* throws ArgumentOutOfRangeException */
{
if (minValue >= maxValue)
{
throw new ArgumentOutOfRangeException();
}
return (UInt32)(GenerateUInt32() / ((Double)UInt32.MaxValue / (maxValue - minValue)) + minValue);
}
/// <summary>
/// Returns the next pseudo-random <see cref="Int32"/>.
/// </summary>
/// <returns>A pseudo-random <see cref="Int32"/> value.</returns>
public override Int32 Next()
{
return Next(Int32.MaxValue);
}
/// <summary>
/// Returns the next pseudo-random <see cref="Int32"/> up to <paramref name="maxValue"/>.
/// </summary>
/// <param name="maxValue">The maximum value of the pseudo-random number to create.</param>
/// <returns>
/// A pseudo-random <see cref="Int32"/> value which is at most <paramref name="maxValue"/>.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// When <paramref name="maxValue"/> < 0.
/// </exception>
public override Int32 Next(Int32 maxValue)
{
if (maxValue <= 1)
{
if (maxValue < 0)
{
throw new ArgumentOutOfRangeException();
}
return 0;
}
return (Int32)(NextDouble() * maxValue);
}
/// <summary>
/// Returns the next pseudo-random <see cref="Int32"/>
/// at least <paramref name="minValue"/>
/// and up to <paramref name="maxValue"/>.
/// </summary>
/// <param name="minValue">The minimum value of the pseudo-random number to create.</param>
/// <param name="maxValue">The maximum value of the pseudo-random number to create.</param>
/// <returns>A pseudo-random Int32 value which is at least <paramref name="minValue"/> and at
/// most <paramref name="maxValue"/>.</returns>
/// <exception cref="ArgumentOutOfRangeException">
/// If <c><paramref name="minValue"/> >= <paramref name="maxValue"/></c>.
/// </exception>
public override Int32 Next(Int32 minValue, Int32 maxValue)
{
if (maxValue <= minValue)
{
throw new ArgumentOutOfRangeException();
}
if (maxValue == minValue)
{
return minValue;
}
return Next(maxValue - minValue) + minValue;
}
/// <summary>
/// Fills a buffer with pseudo-random bytes.
/// </summary>
/// <param name="buffer">The buffer to fill.</param>
/// <exception cref="ArgumentNullException">
/// If <c><paramref name="buffer"/> == <see langword="null"/></c>.
/// </exception>
public override void NextBytes(Byte[] buffer)
{
// [codekaizen: corrected this to check null before checking length.]
if (buffer == null)
{
throw new ArgumentNullException();
}
Int32 bufLen = buffer.Length;
for (Int32 idx = 0; idx < bufLen; ++idx)
{
buffer[idx] = (Byte)Next(256);
}
}
public byte[] NextBytes(long len)
{
byte[] ret = new byte[len];
NextBytes(ret);
return ret;
}
/// <summary>
/// Returns the next pseudo-random <see cref="Double"/> value.
/// </summary>
/// <returns>A pseudo-random double floating point value.</returns>
/// <remarks>
/// <para>
/// There are two common ways to create a double floating point using MT19937:
/// using <see cref="GenerateUInt32"/> and dividing by 0xFFFFFFFF + 1,
/// or else generating two double words and shifting the first by 26 bits and
/// adding the second.
/// </para>
/// <para>
/// In a newer measurement of the randomness of MT19937 published in the
/// journal "Monte Carlo Methods and Applications, Vol. 12, No. 5-6, pp. 385 393 (2006)"
/// entitled "A Repetition Test for Pseudo-Random Number Generators",
/// it was found that the 32-bit version of generating a double fails at the 95%
/// confidence level when measuring for expected repetitions of a particular
/// number in a sequence of numbers generated by the algorithm.
/// </para>
/// <para>
/// Due to this, the 53-bit method is implemented here and the 32-bit method
/// of generating a double is not. If, for some reason,
/// the 32-bit method is needed, it can be generated by the following:
/// <code>
/// (Double)NextUInt32() / ((UInt64)UInt32.MaxValue + 1);
/// </code>
/// </para>
/// </remarks>
public override Double NextDouble()
{
return compute53BitRandom(0, InverseOnePlus53BitsOf1s);
}
/// <summary>
/// Returns a pseudo-random number greater than or equal to zero, and
/// either strictly less than one, or less than or equal to one,
/// depending on the value of the given parameter.
/// </summary>
/// <param name="includeOne">
/// If <see langword="true"/>, the pseudo-random number returned will be
/// less than or equal to one; otherwise, the pseudo-random number returned will
/// be strictly less than one.
/// </param>
/// <returns>
/// If <paramref name="includeOne"/> is <see langword="true"/>,
/// this method returns a double-precision pseudo-random number greater than
/// or equal to zero, and less than or equal to one.
/// If <paramref name="includeOne"/> is <see langword="false"/>, this method
/// returns a double-precision pseudo-random number greater than or equal to zero and
/// strictly less than one.
/// </returns>
public Double NextDouble(Boolean includeOne)
{
return includeOne ? compute53BitRandom(0, Inverse53BitsOf1s) : NextDouble();
}
/// <summary>
/// Returns a pseudo-random number greater than 0.0 and less than 1.0.
/// </summary>
/// <returns>A pseudo-random number greater than 0.0 and less than 1.0.</returns>
public Double NextDoublePositive()
{
return compute53BitRandom(0.5, Inverse53BitsOf1s);
}
/// <summary>
/// Returns a pseudo-random number between 0.0 and 1.0.
/// </summary>
/// <returns>
/// A single-precision floating point number greater than or equal to 0.0,
/// and less than 1.0.
/// </returns>
public Single NextSingle()
{
return (Single)NextDouble();
}
/// <summary>
/// Returns a pseudo-random number greater than or equal to zero, and either strictly
/// less than one, or less than or equal to one, depending on the value of the
/// given boolean parameter.
/// </summary>
/// <param name="includeOne">
/// If <see langword="true"/>, the pseudo-random number returned will be
/// less than or equal to one; otherwise, the pseudo-random number returned will
/// be strictly less than one.
/// </param>
/// <returns>
/// If <paramref name="includeOne"/> is <see langword="true"/>, this method returns a
/// single-precision pseudo-random number greater than or equal to zero, and less
/// than or equal to one. If <paramref name="includeOne"/> is <see langword="false"/>,
/// this method returns a single-precision pseudo-random number greater than or equal to zero and
/// strictly less than one.
/// </returns>
public Single NextSingle(Boolean includeOne)
{
return (Single)NextDouble(includeOne);
}
/// <summary>
/// Returns a pseudo-random number greater than 0.0 and less than 1.0.
/// </summary>
/// <returns>A pseudo-random number greater than 0.0 and less than 1.0.</returns>
public Single NextSinglePositive()
{
return (Single)NextDoublePositive();
}
public int RandomRange(int low, int high)
{
return Next(low, high);
}
public long NextLong()
{
byte[] tmp = new byte[8];
NextBytes(tmp);
return BitConverter.ToInt64(tmp,0);
}
/// <summary>
/// Generates a new pseudo-random <see cref="UInt32"/>.
/// </summary>
/// <returns>A pseudo-random <see cref="UInt32"/>.</returns>
protected UInt32 GenerateUInt32()
{
UInt32 y;
/* _mag01[x] = x * MatrixA for x=0,1 */
if (_mti >= N) /* generate N words at one time */
{
Int16 kk = 0;
for (; kk < N - M; ++kk)
{
y = (_mt[kk] & UpperMask) | (_mt[kk + 1] & LowerMask);
_mt[kk] = _mt[kk + M] ^ (y >> 1) ^ _mag01[y & 0x1];
}
for (; kk < N - 1; ++kk)
{
y = (_mt[kk] & UpperMask) | (_mt[kk + 1] & LowerMask);
_mt[kk] = _mt[kk + (M - N)] ^ (y >> 1) ^ _mag01[y & 0x1];
}
y = (_mt[N - 1] & UpperMask) | (_mt[0] & LowerMask);
_mt[N - 1] = _mt[M - 1] ^ (y >> 1) ^ _mag01[y & 0x1];
_mti = 0;
}
y = _mt[_mti++];
y ^= temperingShiftU(y);
y ^= temperingShiftS(y) & TemperingMaskB;
y ^= temperingShiftT(y) & TemperingMaskC;
y ^= temperingShiftL(y);
return y;
}
/* Period parameters */
private const Int32 N = 624;
private const Int32 M = 397;
private const UInt32 MatrixA = 0x9908b0df; /* constant vector a */
private const UInt32 UpperMask = 0x80000000; /* most significant w-r bits */
private const UInt32 LowerMask = 0x7fffffff; /* least significant r bits */
/* Tempering parameters */
private const UInt32 TemperingMaskB = 0x9d2c5680;
private const UInt32 TemperingMaskC = 0xefc60000;
private static UInt32 temperingShiftU(UInt32 y)
{
return (y >> 11);
}
private static UInt32 temperingShiftS(UInt32 y)
{
return (y << 7);
}
private static UInt32 temperingShiftT(UInt32 y)
{
return (y << 15);
}
private static UInt32 temperingShiftL(UInt32 y)
{
return (y >> 18);
}
private readonly UInt32[] _mt = new UInt32[N]; /* the array for the state vector */
private Int16 _mti;
private static readonly UInt32[] _mag01 = { 0x0, MatrixA };
private void init(UInt32 seed)
{
_mt[0] = seed & 0xffffffffU;
for (_mti = 1; _mti < N; _mti++)
{
//to try and fix arithmetic overflow, place temporarily into ulong then drop back to uint.
ulong tmp = (ulong)((ulong)1812433253U * (ulong)(_mt[_mti - 1] ^ (_mt[_mti - 1] >> 30)) + (ulong)_mti);
_mt[_mti] = (uint)(tmp % uint.MaxValue);
// See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier.
// In the previous versions, MSBs of the seed affect
// only MSBs of the array _mt[].
// 2002/01/09 modified by Makoto Matsumoto
_mt[_mti] &= 0xffffffffU;
// for >32 bit machines
}
}
private void init(UInt32[] key)
{
Int32 i, j, k;
init(19650218U);
Int32 keyLength = key.Length;
i = 1; j = 0;
k = (N > keyLength ? N : keyLength);
for (; k > 0; k--)
{
_mt[i] = (uint)((_mt[i] ^ ((_mt[i - 1] ^ (_mt[i - 1] >> 30)) * 1664525U)) + key[j] + j); /* non linear */
_mt[i] &= 0xffffffffU; // for WORDSIZE > 32 machines
i++; j++;
if (i >= N) { _mt[0] = _mt[N - 1]; i = 1; }
if (j >= keyLength) j = 0;
}
for (k = N - 1; k > 0; k--)
{
_mt[i] = (uint)((_mt[i] ^ ((_mt[i - 1] ^ (_mt[i - 1] >> 30)) * 1566083941U)) - i); /* non linear */
_mt[i] &= 0xffffffffU; // for WORDSIZE > 32 machines
i++;
if (i < N)
{
continue;
}
_mt[0] = _mt[N - 1]; i = 1;
}
_mt[0] = 0x80000000U; // MSB is 1; assuring non-zero initial array
}
// 9007199254740991.0 is the maximum double value which the 53 significand
// can hold when the exponent is 0.
private const Double FiftyThreeBitsOf1s = 9007199254740991.0;
// Multiply by inverse to (vainly?) try to avoid a division.
private const Double Inverse53BitsOf1s = 1.0 / FiftyThreeBitsOf1s;
private const Double OnePlus53BitsOf1s = FiftyThreeBitsOf1s + 1;
private const Double InverseOnePlus53BitsOf1s = 1.0 / OnePlus53BitsOf1s;
private Double compute53BitRandom(Double translate, Double scale)
{
// get 27 pseudo-random bits
UInt64 a = (UInt64)GenerateUInt32() >> 5;
// get 26 pseudo-random bits
UInt64 b = (UInt64)GenerateUInt32() >> 6;
// shift the 27 pseudo-random bits (a) over by 26 bits (* 67108864.0) and
// add another pseudo-random 26 bits (+ b).
return ((a * 67108864.0 + b) + translate) * scale;
// What about the following instead of the above? Is the multiply better?
// Why? (Is it the FMUL instruction? Does this count in .Net? Will the JITter notice?)
//return BitConverter.Int64BitsToDouble((a << 26) + b));
}
}
}