13 | * Version 20, based on version MT199937(99/10/29) of the Mersenne Twister algorithm found at 14 | * The Mersenne Twister Home Page, with 15 | * the initialization improved using the new 2002/1/26 initialization algorithm By Sean Luke, 16 | * October 2004. 17 | * 18 | *
19 | * MersenneTwister is a drop-in subclass replacement for java.util.Random. It is properly 20 | * synchronized and can be used in a multithreaded environment. On modern VMs such as HotSpot, it is 21 | * approximately 1/3 slower than java.util.Random. 22 | * 23 | *
24 | * MersenneTwisterFast is not a subclass of java.util.Random. It has the same public methods 25 | * as Random does, however, and it is algorithmically identical to MersenneTwister. 26 | * MersenneTwisterFast has hard-code inlined all of its methods directly, and made all of them final 27 | * (well, the ones of consequence anyway). Further, these methods are not synchronized, so 28 | * the same MersenneTwisterFast instance cannot be shared by multiple threads. But all this helps 29 | * MersenneTwisterFast achieve well over twice the speed of MersenneTwister. java.util.Random is 30 | * about 1/3 slower than MersenneTwisterFast. 31 | * 32 | *
34 | * This is a Java version of the C-program for MT19937: Integer version. The MT19937 algorithm was 35 | * created by Makoto Matsumoto and Takuji Nishimura, who ask: "When you use this, send an email to: 36 | * matumoto@math.keio.ac.jp with an appropriate reference to your work". Indicate that this is a 37 | * translation of their algorithm into Java. 38 | * 39 | *
40 | * Reference. Makato Matsumoto and Takuji Nishimura, "Mersenne Twister: A 623-Dimensionally 41 | * Equidistributed Uniform Pseudo-Random Number Generator", ACM Transactions on Modeling and. 42 | * Computer Simulation, Vol. 8, No. 1, January 1998, pp 3--30. 43 | * 44 | *
47 | * Changes since V19: nextFloat(boolean, boolean) now returns float, not double. 48 | * 49 | *
50 | * Changes since V18: Removed old final declarations, which used to potentially speed up the 51 | * code, but no longer. 52 | * 53 | *
54 | * Changes since V17: Removed vestigial references to &= 0xffffffff which stemmed from the 55 | * original C code. The C code could not guarantee that ints were 32 bit, hence the masks. The 56 | * vestigial references in the Java code were likely optimized out anyway. 57 | * 58 | *
59 | * Changes since V16: Added nextDouble(includeZero, includeOne) and nextFloat(includeZero, 60 | * includeOne) to allow for half-open, fully-closed, and fully-open intervals. 61 | * 62 | *
63 | * Changes Since V15: Added serialVersionUID to quiet compiler warnings from Sun's overly 64 | * verbose compilers as of JDK 1.5. 65 | * 66 | *
67 | * Changes Since V14: made strictfp, with StrictMath.log and StrictMath.sqrt in nextGaussian 68 | * instead of Math.log and Math.sqrt. This is largely just to be safe, as it presently makes no 69 | * difference in the speed, correctness, or results of the algorithm. 70 | * 71 | *
72 | * Changes Since V13: clone() method CloneNotSupportedException removed. 73 | * 74 | *
75 | * Changes Since V12: clone() method added. 76 | * 77 | *
78 | * Changes Since V11: stateEquals(...) method added. MersenneTwisterFast is equal to other 79 | * MersenneTwisterFasts with identical state; likewise MersenneTwister is equal to other 80 | * MersenneTwister with identical state. This isn't equals(...) because that requires a contract of 81 | * immutability to compare by value. 82 | * 83 | *
84 | * Changes Since V10: A documentation error suggested that setSeed(int[]) required an int[] 85 | * array 624 long. In fact, the array can be any non-zero length. The new version also checks for 86 | * this fact. 87 | * 88 | *
89 | * Changes Since V9: readState(stream) and writeState(stream) provided. 90 | * 91 | *
92 | * Changes Since V8: setSeed(int) was only using the first 28 bits of the seed; it should 93 | * have been 32 bits. For small-number seeds the behavior is identical. 94 | * 95 | *
96 | * Changes Since V7: A documentation error in MersenneTwisterFast (but not MersenneTwister) 97 | * stated that nextDouble selects uniformly from the full-open interval [0,1]. It does not. 98 | * nextDouble's contract is identical across MersenneTwisterFast, MersenneTwister, and 99 | * java.util.Random, namely, selection in the half-open interval [0,1). That is, 1.0 should not be 100 | * returned. A similar contract exists in nextFloat. 101 | * 102 | *
103 | * Changes Since V6: License has changed from LGPL to BSD. New timing information to compare 104 | * against java.util.Random. Recent versions of HotSpot have helped Random increase in speed to the 105 | * point where it is faster than MersenneTwister but slower than MersenneTwisterFast (which should 106 | * be the case, as it's a less complex algorithm but is synchronized). 107 | * 108 | *
109 | * Changes Since V5: New empty constructor made to work the same as java.util.Random -- 110 | * namely, it seeds based on the current time in milliseconds. 111 | * 112 | *
113 | * Changes Since V4: New initialization algorithms. See (see 115 | * http://www.math.keio.ac.jp/matumoto/MT2002/emt19937ar.html) 116 | * 117 | *
118 | * The MersenneTwister code is based on standard MT19937 C/C++ code by Takuji Nishimura, with 119 | * suggestions from Topher Cooper and Marc Rieffel, July 1997. The code was originally translated 120 | * into Java by Michael Lecuyer, January 1999, and the original code is Copyright (c) 1999 by 121 | * Michael Lecuyer. 122 | * 123 | *
126 | * This implementation implements the bug fixes made in Java 1.2's version of Random, which means it 127 | * can be used with earlier versions of Java. See the JDK 1.2 129 | * java.util.Random documentation for further documentation on the random-number generation 130 | * contracts made. Additionally, there's an undocumented bug in the JDK java.util.Random.nextBytes() 131 | * method, which this code fixes. 132 | * 133 | *
134 | * Just like java.util.Random, this generator accepts a long seed but doesn't use all of it. 135 | * java.util.Random uses 48 bits. The Mersenne Twister instead uses 32 bits (int size). So it's best 136 | * if your seed does not exceed the int range. 137 | * 138 | *
139 | * MersenneTwister can be used reliably on JDK version 1.1.5 or above. Earlier Java versions have 140 | * serious bugs in java.util.Random; only MersenneTwisterFast (and not MersenneTwister nor 141 | * java.util.Random) should be used with them. 142 | * 143 | *
150 | * Redistribution and use in source and binary forms, with or without modification, are permitted 151 | * provided that the following conditions are met: 152 | *
163 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR 164 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 165 | * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNERS OR 166 | * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 167 | * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 168 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 169 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY 170 | * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 171 | * 172 | * @version 20 173 | */ 174 | 175 | public strictfp class MersenneTwister 176 | extends java.util.Random 177 | implements Serializable, Cloneable 178 | { 179 | // Serialization 180 | private static final long serialVersionUID = -4035832775130174188L; // locked as of Version 15 181 | 182 | // Period parameters 183 | private static final int N = 624; 184 | private static final int M = 397; 185 | private static final int MATRIX_A = 0x9908b0df; // private static final * constant vector a 186 | private static final int UPPER_MASK = 0x80000000; // most significant w-r bits 187 | private static final int LOWER_MASK = 0x7fffffff; // least significant r bits 188 | 189 | // Tempering parameters 190 | private static final int TEMPERING_MASK_B = 0x9d2c5680; 191 | private static final int TEMPERING_MASK_C = 0xefc60000; 192 | 193 | private int mt[]; // the array for the state vector 194 | private int mti; // mti==N+1 means mt[N] is not initialized 195 | private int mag01[]; 196 | 197 | // a good initial seed (of int size, though stored in a long) 198 | // private static final long GOOD_SEED = 4357; 199 | 200 | /* 201 | * implemented here because there's a bug in Random's implementation of the Gaussian code 202 | * (divide by zero, and log(0), ugh!), yet its gaussian variables are private so we can't access 203 | * them here. :-( 204 | */ 205 | 206 | private double __nextNextGaussian; 207 | private boolean __haveNextNextGaussian; 208 | 209 | /* We're overriding all internal data, to my knowledge, so this should be okay */ 210 | public Object clone() 211 | { 212 | try { 213 | MersenneTwister f = (MersenneTwister) (super.clone()); 214 | f.mt = (int[]) (mt.clone()); 215 | f.mag01 = (int[]) (mag01.clone()); 216 | return f; 217 | } 218 | catch (CloneNotSupportedException e) { 219 | throw new InternalError(); 220 | } // should never happen 221 | } 222 | 223 | public boolean stateEquals(Object o) 224 | { 225 | if (o == this) 226 | return true; 227 | if (o == null || !(o instanceof MersenneTwister)) 228 | return false; 229 | MersenneTwister other = (MersenneTwister) o; 230 | if (mti != other.mti) 231 | return false; 232 | for (int x = 0; x < mag01.length; x++) 233 | if (mag01[x] != other.mag01[x]) 234 | return false; 235 | for (int x = 0; x < mt.length; x++) 236 | if (mt[x] != other.mt[x]) 237 | return false; 238 | return true; 239 | } 240 | 241 | /** Reads the entire state of the MersenneTwister RNG from the stream */ 242 | public void readState(DataInputStream stream) 243 | throws IOException 244 | { 245 | int len = mt.length; 246 | for (int x = 0; x < len; x++) 247 | mt[x] = stream.readInt(); 248 | 249 | len = mag01.length; 250 | for (int x = 0; x < len; x++) 251 | mag01[x] = stream.readInt(); 252 | 253 | mti = stream.readInt(); 254 | __nextNextGaussian = stream.readDouble(); 255 | __haveNextNextGaussian = stream.readBoolean(); 256 | } 257 | 258 | /** Writes the entire state of the MersenneTwister RNG to the stream */ 259 | public void writeState(DataOutputStream stream) 260 | throws IOException 261 | { 262 | int len = mt.length; 263 | for (int x = 0; x < len; x++) 264 | stream.writeInt(mt[x]); 265 | 266 | len = mag01.length; 267 | for (int x = 0; x < len; x++) 268 | stream.writeInt(mag01[x]); 269 | 270 | stream.writeInt(mti); 271 | stream.writeDouble(__nextNextGaussian); 272 | stream.writeBoolean(__haveNextNextGaussian); 273 | } 274 | 275 | /** 276 | * Constructor using the default seed. 277 | */ 278 | public MersenneTwister() 279 | { 280 | this(System.currentTimeMillis()); 281 | } 282 | 283 | /** 284 | * Constructor using a given seed. Though you pass this seed in as a long, it's best to make 285 | * sure it's actually an integer. 286 | */ 287 | public MersenneTwister(long seed) 288 | { 289 | super(seed); /* just in case */ 290 | setSeed(seed); 291 | } 292 | 293 | /** 294 | * Constructor using an array of integers as seed. Your array must have a non-zero length. Only 295 | * the first 624 integers in the array are used; if the array is shorter than this then integers 296 | * are repeatedly used in a wrap-around fashion. 297 | */ 298 | public MersenneTwister(int[] array) 299 | { 300 | super(System.currentTimeMillis()); /* pick something at random just in case */ 301 | setSeed(array); 302 | } 303 | 304 | /** 305 | * Initalize the pseudo random number generator. Don't pass in a long that's bigger than an int 306 | * (Mersenne Twister only uses the first 32 bits for its seed). 307 | */ 308 | 309 | synchronized public void setSeed(long seed) 310 | { 311 | // it's always good style to call super 312 | super.setSeed(seed); 313 | 314 | // Due to a bug in java.util.Random clear up to 1.2, we're 315 | // doing our own Gaussian variable. 316 | __haveNextNextGaussian = false; 317 | 318 | mt = new int[N]; 319 | 320 | mag01 = new int[2]; 321 | mag01[0] = 0x0; 322 | mag01[1] = MATRIX_A; 323 | 324 | mt[0] = (int) (seed & 0xffffffff); 325 | mt[0] = (int) seed; 326 | for (mti = 1; mti < N; mti++) { 327 | mt[mti] = (1812433253 * (mt[mti - 1] ^ (mt[mti - 1] >>> 30)) + mti); 328 | /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ 329 | /* In the previous versions, MSBs of the seed affect */ 330 | /* only MSBs of the array mt[]. */ 331 | /* 2002/01/09 modified by Makoto Matsumoto */ 332 | // mt[mti] &= 0xffffffff; 333 | /* for >32 bit machines */ 334 | } 335 | } 336 | 337 | /** 338 | * Sets the seed of the MersenneTwister using an array of integers. Your array must have a 339 | * non-zero length. Only the first 624 integers in the array are used; if the array is shorter 340 | * than this then integers are repeatedly used in a wrap-around fashion. 341 | */ 342 | 343 | synchronized public void setSeed(int[] array) 344 | { 345 | if (array.length == 0) 346 | throw new IllegalArgumentException("Array length must be greater than zero"); 347 | int i, j, k; 348 | setSeed(19650218); 349 | i = 1; 350 | j = 0; 351 | k = (N > array.length ? N : array.length); 352 | for (; k != 0; k--) { 353 | mt[i] = (mt[i] ^ ((mt[i - 1] ^ (mt[i - 1] >>> 30)) * 1664525)) + array[j] + j; /* 354 | * non 355 | * linear 356 | */ 357 | // mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */ 358 | i++; 359 | j++; 360 | if (i >= N) { 361 | mt[0] = mt[N - 1]; 362 | i = 1; 363 | } 364 | if (j >= array.length) 365 | j = 0; 366 | } 367 | for (k = N - 1; k != 0; k--) { 368 | mt[i] = (mt[i] ^ ((mt[i - 1] ^ (mt[i - 1] >>> 30)) * 1566083941)) - i; /* non linear */ 369 | // mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */ 370 | i++; 371 | if (i >= N) { 372 | mt[0] = mt[N - 1]; 373 | i = 1; 374 | } 375 | } 376 | mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */ 377 | } 378 | 379 | /** 380 | * Returns an integer with bits bits filled with a random number. 381 | */ 382 | synchronized protected int next(int bits) 383 | { 384 | int y; 385 | 386 | if (mti >= N) // generate N words at one time 387 | { 388 | int kk; 389 | final int[] mt = this.mt; // locals are slightly faster 390 | final int[] mag01 = this.mag01; // locals are slightly faster 391 | 392 | for (kk = 0; kk < N - M; kk++) { 393 | y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); 394 | mt[kk] = mt[kk + M] ^ (y >>> 1) ^ mag01[y & 0x1]; 395 | } 396 | for (; kk < N - 1; kk++) { 397 | y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); 398 | mt[kk] = mt[kk + (M - N)] ^ (y >>> 1) ^ mag01[y & 0x1]; 399 | } 400 | y = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK); 401 | mt[N - 1] = mt[M - 1] ^ (y >>> 1) ^ mag01[y & 0x1]; 402 | 403 | mti = 0; 404 | } 405 | 406 | y = mt[mti++]; 407 | y ^= y >>> 11; // TEMPERING_SHIFT_U(y) 408 | y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) 409 | y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) 410 | y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) 411 | 412 | return y >>> (32 - bits); // hope that's right! 413 | } 414 | 415 | /* 416 | * If you've got a truly old version of Java, you can omit these two next methods. 417 | */ 418 | 419 | private synchronized void writeObject(ObjectOutputStream out) 420 | throws IOException 421 | { 422 | // just so we're synchronized. 423 | out.defaultWriteObject(); 424 | } 425 | 426 | private synchronized void readObject(ObjectInputStream in) 427 | throws IOException, ClassNotFoundException 428 | { 429 | // just so we're synchronized. 430 | in.defaultReadObject(); 431 | } 432 | 433 | /** 434 | * This method is missing from jdk 1.0.x and below. JDK 1.1 includes this for us, but what the 435 | * heck. 436 | */ 437 | public boolean nextBoolean() 438 | { 439 | return next(1) != 0; 440 | } 441 | 442 | /** 443 | * This generates a coin flip with a probability probability of returning true, else 444 | * returning false. probability must be between 0.0 and 1.0, inclusive. Not as precise 445 | * a random real event as nextBoolean(double), but twice as fast. To explicitly use this, 446 | * remember you may need to cast to float first. 447 | */ 448 | 449 | public boolean nextBoolean(float probability) 450 | { 451 | if (probability < 0.0f || probability > 1.0f) 452 | throw new IllegalArgumentException("probability must be between 0.0 and 1.0 inclusive."); 453 | if (probability == 0.0f) 454 | return false; // fix half-open issues 455 | else if (probability == 1.0f) 456 | return true; // fix half-open issues 457 | return nextFloat() < probability; 458 | } 459 | 460 | /** 461 | * This generates a coin flip with a probability probability of returning true, else 462 | * returning false. probability must be between 0.0 and 1.0, inclusive. 463 | */ 464 | 465 | public boolean nextBoolean(double probability) 466 | { 467 | if (probability < 0.0 || probability > 1.0) 468 | throw new IllegalArgumentException("probability must be between 0.0 and 1.0 inclusive."); 469 | if (probability == 0.0) 470 | return false; // fix half-open issues 471 | else if (probability == 1.0) 472 | return true; // fix half-open issues 473 | return nextDouble() < probability; 474 | } 475 | 476 | /** 477 | * This method is missing from JDK 1.1 and below. JDK 1.2 includes this for us, but what the 478 | * heck. 479 | */ 480 | 481 | public int nextInt(int n) 482 | { 483 | if (n <= 0) 484 | throw new IllegalArgumentException("n must be positive, got: " + n); 485 | 486 | if ((n & -n) == n) 487 | return (int) ((n * (long) next(31)) >> 31); 488 | 489 | int bits, val; 490 | do { 491 | bits = next(31); 492 | val = bits % n; 493 | } 494 | while (bits - val + (n - 1) < 0); 495 | return val; 496 | } 497 | 498 | /** 499 | * This method is for completness' sake. Returns a long drawn uniformly from 0 to n-1. Suffice 500 | * it to say, n must be > 0, or an IllegalArgumentException is raised. 501 | */ 502 | 503 | public long nextLong(long n) 504 | { 505 | if (n <= 0) 506 | throw new IllegalArgumentException("n must be positive, got: " + n); 507 | 508 | long bits, val; 509 | do { 510 | bits = (nextLong() >>> 1); 511 | val = bits % n; 512 | } 513 | while (bits - val + (n - 1) < 0); 514 | return val; 515 | } 516 | 517 | /** 518 | * A bug fix for versions of JDK 1.1 and below. JDK 1.2 fixes this for us, but what the heck. 519 | */ 520 | public double nextDouble() 521 | { 522 | return (((long) next(26) << 27) + next(27)) / (double) (1L << 53); 523 | } 524 | 525 | /** 526 | * Returns a double in the range from 0.0 to 1.0, possibly inclusive of 0.0 and 1.0 themselves. 527 | * Thus: 528 | * 529 | *
530 | *
| 532 | * | Expression 533 | * | Interval 534 | * |
|---|---|
| nextDouble(false, false) 536 | * | (0.0, 1.0) 537 | * |
| nextDouble(true, false) 539 | * | [0.0, 1.0) 540 | * |
| nextDouble(false, true) 542 | * | (0.0, 1.0] 543 | * |
| nextDouble(true, true) 545 | * | [0.0, 1.0] 546 | * |
549 | * This version preserves all possible random values in the double range. 550 | */ 551 | public double nextDouble(boolean includeZero, boolean includeOne) 552 | { 553 | double d = 0.0; 554 | do { 555 | d = nextDouble(); // grab a value, initially from half-open [0.0, 1.0) 556 | if (includeOne && nextBoolean()) 557 | d += 1.0; // if includeOne, with 1/2 probability, push to [1.0, 2.0) 558 | } 559 | while ((d > 1.0) || // everything above 1.0 is always invalid 560 | (!includeZero && d == 0.0)); // if we're not including zero, 0.0 is invalid 561 | return d; 562 | } 563 | 564 | /** 565 | * A bug fix for versions of JDK 1.1 and below. JDK 1.2 fixes this for us, but what the heck. 566 | */ 567 | 568 | public float nextFloat() 569 | { 570 | return next(24) / ((float) (1 << 24)); 571 | } 572 | 573 | /** 574 | * Returns a float in the range from 0.0f to 1.0f, possibly inclusive of 0.0f and 1.0f 575 | * themselves. Thus: 576 | * 577 | *
578 | *
| 580 | * | Expression 581 | * | Interval 582 | * |
|---|---|
| nextFloat(false, false) 584 | * | (0.0f, 1.0f) 585 | * |
| nextFloat(true, false) 587 | * | [0.0f, 1.0f) 588 | * |
| nextFloat(false, true) 590 | * | (0.0f, 1.0f] 591 | * |
| nextFloat(true, true) 593 | * | [0.0f, 1.0f] 594 | * |
597 | * This version preserves all possible random values in the float range. 598 | */ 599 | public float nextFloat(boolean includeZero, boolean includeOne) 600 | { 601 | float d = 0.0f; 602 | do { 603 | d = nextFloat(); // grab a value, initially from half-open [0.0f, 1.0f) 604 | if (includeOne && nextBoolean()) 605 | d += 1.0f; // if includeOne, with 1/2 probability, push to [1.0f, 2.0f) 606 | } 607 | while ((d > 1.0f) || // everything above 1.0f is always invalid 608 | (!includeZero && d == 0.0f)); // if we're not including zero, 0.0f is invalid 609 | return d; 610 | } 611 | 612 | /** 613 | * A bug fix for all versions of the JDK. The JDK appears to use all four bytes in an integer as 614 | * independent byte values! Totally wrong. I've submitted a bug report. 615 | */ 616 | 617 | public void nextBytes(byte[] bytes) 618 | { 619 | for (int x = 0; x < bytes.length; x++) 620 | bytes[x] = (byte) next(8); 621 | } 622 | 623 | /** For completeness' sake, though it's not in java.util.Random. */ 624 | 625 | public char nextChar() 626 | { 627 | // chars are 16-bit UniCode values 628 | return (char) (next(16)); 629 | } 630 | 631 | /** For completeness' sake, though it's not in java.util.Random. */ 632 | 633 | public short nextShort() 634 | { 635 | return (short) (next(16)); 636 | } 637 | 638 | /** For completeness' sake, though it's not in java.util.Random. */ 639 | 640 | public byte nextByte() 641 | { 642 | return (byte) (next(8)); 643 | } 644 | 645 | /** 646 | * A bug fix for all JDK code including 1.2. nextGaussian can theoretically ask for the log of 0 647 | * and divide it by 0! See Java bug 649 | * http://developer.java.sun.com/developer/bugParade/bugs/4254501.html 650 | */ 651 | 652 | synchronized public double nextGaussian() 653 | { 654 | if (__haveNextNextGaussian) { 655 | __haveNextNextGaussian = false; 656 | return __nextNextGaussian; 657 | } 658 | else { 659 | double v1, v2, s; 660 | do { 661 | v1 = 2 * nextDouble() - 1; // between -1.0 and 1.0 662 | v2 = 2 * nextDouble() - 1; // between -1.0 and 1.0 663 | s = v1 * v1 + v2 * v2; 664 | } 665 | while (s >= 1 || s == 0); 666 | double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s) / s); 667 | __nextNextGaussian = v2 * multiplier; 668 | __haveNextNextGaussian = true; 669 | return v1 * multiplier; 670 | } 671 | } 672 | 673 | /** 674 | * Tests the code. 675 | */ 676 | public static void main(String args[]) 677 | { 678 | int j; 679 | 680 | MersenneTwister r; 681 | 682 | // CORRECTNESS TEST 683 | // COMPARE WITH http://www.math.keio.ac.jp/matumoto/CODES/MT2002/mt19937ar.out 684 | 685 | r = new MersenneTwister(new int[] { 0x123, 0x234, 0x345, 0x456 }); 686 | System.out.println("Output of MersenneTwister with new (2002/1/26) seeding mechanism"); 687 | for (j = 0; j < 1000; j++) { 688 | // first, convert the int from signed to "unsigned" 689 | long l = (long) r.nextInt(); 690 | if (l < 0) 691 | l += 4294967296L; // max int value 692 | String s = String.valueOf(l); 693 | while (s.length() < 10) 694 | s = " " + s; // buffer 695 | System.out.print(s + " "); 696 | if (j % 5 == 4) 697 | System.out.println(); 698 | } 699 | 700 | // SPEED TEST 701 | 702 | final long SEED = 4357; 703 | 704 | int xx; 705 | long ms; 706 | System.out.println("\nTime to test grabbing 100000000 ints"); 707 | 708 | r = new MersenneTwister(SEED); 709 | ms = System.currentTimeMillis(); 710 | xx = 0; 711 | for (j = 0; j < 100000000; j++) 712 | xx += r.nextInt(); 713 | System.out.println("Mersenne Twister: " + (System.currentTimeMillis() - ms) 714 | + " Ignore this: " + xx); 715 | 716 | System.out 717 | .println("To compare this with java.util.Random, run this same test on MersenneTwisterFast."); 718 | System.out 719 | .println("The comparison with Random is removed from MersenneTwister because it is a proper"); 720 | System.out 721 | .println("subclass of Random and this unfairly makes some of Random's methods un-inlinable,"); 722 | System.out.println("so it would make Random look worse than it is."); 723 | 724 | // TEST TO COMPARE TYPE CONVERSION BETWEEN 725 | // MersenneTwisterFast.java AND MersenneTwister.java 726 | 727 | System.out.println("\nGrab the first 1000 booleans"); 728 | r = new MersenneTwister(SEED); 729 | for (j = 0; j < 1000; j++) { 730 | System.out.print(r.nextBoolean() + " "); 731 | if (j % 8 == 7) 732 | System.out.println(); 733 | } 734 | if (!(j % 8 == 7)) 735 | System.out.println(); 736 | 737 | System.out 738 | .println("\nGrab 1000 booleans of increasing probability using nextBoolean(double)"); 739 | r = new MersenneTwister(SEED); 740 | for (j = 0; j < 1000; j++) { 741 | System.out.print(r.nextBoolean((double) (j / 999.0)) + " "); 742 | if (j % 8 == 7) 743 | System.out.println(); 744 | } 745 | if (!(j % 8 == 7)) 746 | System.out.println(); 747 | 748 | System.out 749 | .println("\nGrab 1000 booleans of increasing probability using nextBoolean(float)"); 750 | r = new MersenneTwister(SEED); 751 | for (j = 0; j < 1000; j++) { 752 | System.out.print(r.nextBoolean((float) (j / 999.0f)) + " "); 753 | if (j % 8 == 7) 754 | System.out.println(); 755 | } 756 | if (!(j % 8 == 7)) 757 | System.out.println(); 758 | 759 | byte[] bytes = new byte[1000]; 760 | System.out.println("\nGrab the first 1000 bytes using nextBytes"); 761 | r = new MersenneTwister(SEED); 762 | r.nextBytes(bytes); 763 | for (j = 0; j < 1000; j++) { 764 | System.out.print(bytes[j] + " "); 765 | if (j % 16 == 15) 766 | System.out.println(); 767 | } 768 | if (!(j % 16 == 15)) 769 | System.out.println(); 770 | 771 | byte b; 772 | System.out.println("\nGrab the first 1000 bytes -- must be same as nextBytes"); 773 | r = new MersenneTwister(SEED); 774 | for (j = 0; j < 1000; j++) { 775 | System.out.print((b = r.nextByte()) + " "); 776 | if (b != bytes[j]) 777 | System.out.print("BAD "); 778 | if (j % 16 == 15) 779 | System.out.println(); 780 | } 781 | if (!(j % 16 == 15)) 782 | System.out.println(); 783 | 784 | System.out.println("\nGrab the first 1000 shorts"); 785 | r = new MersenneTwister(SEED); 786 | for (j = 0; j < 1000; j++) { 787 | System.out.print(r.nextShort() + " "); 788 | if (j % 8 == 7) 789 | System.out.println(); 790 | } 791 | if (!(j % 8 == 7)) 792 | System.out.println(); 793 | 794 | System.out.println("\nGrab the first 1000 ints"); 795 | r = new MersenneTwister(SEED); 796 | for (j = 0; j < 1000; j++) { 797 | System.out.print(r.nextInt() + " "); 798 | if (j % 4 == 3) 799 | System.out.println(); 800 | } 801 | if (!(j % 4 == 3)) 802 | System.out.println(); 803 | 804 | System.out.println("\nGrab the first 1000 ints of different sizes"); 805 | r = new MersenneTwister(SEED); 806 | int max = 1; 807 | for (j = 0; j < 1000; j++) { 808 | System.out.print(r.nextInt(max) + " "); 809 | max *= 2; 810 | if (max <= 0) 811 | max = 1; 812 | if (j % 4 == 3) 813 | System.out.println(); 814 | } 815 | if (!(j % 4 == 3)) 816 | System.out.println(); 817 | 818 | System.out.println("\nGrab the first 1000 longs"); 819 | r = new MersenneTwister(SEED); 820 | for (j = 0; j < 1000; j++) { 821 | System.out.print(r.nextLong() + " "); 822 | if (j % 3 == 2) 823 | System.out.println(); 824 | } 825 | if (!(j % 3 == 2)) 826 | System.out.println(); 827 | 828 | System.out.println("\nGrab the first 1000 longs of different sizes"); 829 | r = new MersenneTwister(SEED); 830 | long max2 = 1; 831 | for (j = 0; j < 1000; j++) { 832 | System.out.print(r.nextLong(max2) + " "); 833 | max2 *= 2; 834 | if (max2 <= 0) 835 | max2 = 1; 836 | if (j % 4 == 3) 837 | System.out.println(); 838 | } 839 | if (!(j % 4 == 3)) 840 | System.out.println(); 841 | 842 | System.out.println("\nGrab the first 1000 floats"); 843 | r = new MersenneTwister(SEED); 844 | for (j = 0; j < 1000; j++) { 845 | System.out.print(r.nextFloat() + " "); 846 | if (j % 4 == 3) 847 | System.out.println(); 848 | } 849 | if (!(j % 4 == 3)) 850 | System.out.println(); 851 | 852 | System.out.println("\nGrab the first 1000 doubles"); 853 | r = new MersenneTwister(SEED); 854 | for (j = 0; j < 1000; j++) { 855 | System.out.print(r.nextDouble() + " "); 856 | if (j % 3 == 2) 857 | System.out.println(); 858 | } 859 | if (!(j % 3 == 2)) 860 | System.out.println(); 861 | 862 | System.out.println("\nGrab the first 1000 gaussian doubles"); 863 | r = new MersenneTwister(SEED); 864 | for (j = 0; j < 1000; j++) { 865 | System.out.print(r.nextGaussian() + " "); 866 | if (j % 3 == 2) 867 | System.out.println(); 868 | } 869 | if (!(j % 3 == 2)) 870 | System.out.println(); 871 | 872 | } 873 | 874 | } 875 | --------------------------------------------------------------------------------