001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.math3.random; 018 019import java.io.Serializable; 020 021import org.apache.commons.math3.util.FastMath; 022 023 024/** This class implements a powerful pseudo-random number generator 025 * developed by Makoto Matsumoto and Takuji Nishimura during 026 * 1996-1997. 027 028 * <p>This generator features an extremely long period 029 * (2<sup>19937</sup>-1) and 623-dimensional equidistribution up to 32 030 * bits accuracy. The home page for this generator is located at <a 031 * href="http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html"> 032 * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html</a>.</p> 033 034 * <p>This generator is described in a paper by Makoto Matsumoto and 035 * Takuji Nishimura in 1998: <a 036 * href="http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/ARTICLES/mt.pdf">Mersenne 037 * Twister: A 623-Dimensionally Equidistributed Uniform Pseudo-Random 038 * Number Generator</a>, ACM Transactions on Modeling and Computer 039 * Simulation, Vol. 8, No. 1, January 1998, pp 3--30</p> 040 041 * <p>This class is mainly a Java port of the 2002-01-26 version of 042 * the generator written in C by Makoto Matsumoto and Takuji 043 * Nishimura. Here is their original copyright:</p> 044 045 * <table border="0" width="80%" cellpadding="10" align="center" bgcolor="#E0E0E0"> 046 * <tr><td>Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, 047 * All rights reserved.</td></tr> 048 049 * <tr><td>Redistribution and use in source and binary forms, with or without 050 * modification, are permitted provided that the following conditions 051 * are met: 052 * <ol> 053 * <li>Redistributions of source code must retain the above copyright 054 * notice, this list of conditions and the following disclaimer.</li> 055 * <li>Redistributions in binary form must reproduce the above copyright 056 * notice, this list of conditions and the following disclaimer in the 057 * documentation and/or other materials provided with the distribution.</li> 058 * <li>The names of its contributors may not be used to endorse or promote 059 * products derived from this software without specific prior written 060 * permission.</li> 061 * </ol></td></tr> 062 063 * <tr><td><strong>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND 064 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, 065 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 066 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 067 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS 068 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, 069 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 070 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 071 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 072 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 073 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 074 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH 075 * DAMAGE.</strong></td></tr> 076 * </table> 077 078 * @since 2.0 079 080 */ 081public class MersenneTwister extends BitsStreamGenerator implements Serializable { 082 083 /** Serializable version identifier. */ 084 private static final long serialVersionUID = 8661194735290153518L; 085 086 /** Size of the bytes pool. */ 087 private static final int N = 624; 088 089 /** Period second parameter. */ 090 private static final int M = 397; 091 092 /** X * MATRIX_A for X = {0, 1}. */ 093 private static final int[] MAG01 = { 0x0, 0x9908b0df }; 094 095 /** Bytes pool. */ 096 private int[] mt; 097 098 /** Current index in the bytes pool. */ 099 private int mti; 100 101 /** Creates a new random number generator. 102 * <p>The instance is initialized using the current time plus the 103 * system identity hash code of this instance as the seed.</p> 104 */ 105 public MersenneTwister() { 106 mt = new int[N]; 107 setSeed(System.currentTimeMillis() + System.identityHashCode(this)); 108 } 109 110 /** Creates a new random number generator using a single int seed. 111 * @param seed the initial seed (32 bits integer) 112 */ 113 public MersenneTwister(int seed) { 114 mt = new int[N]; 115 setSeed(seed); 116 } 117 118 /** Creates a new random number generator using an int array seed. 119 * @param seed the initial seed (32 bits integers array), if null 120 * the seed of the generator will be related to the current time 121 */ 122 public MersenneTwister(int[] seed) { 123 mt = new int[N]; 124 setSeed(seed); 125 } 126 127 /** Creates a new random number generator using a single long seed. 128 * @param seed the initial seed (64 bits integer) 129 */ 130 public MersenneTwister(long seed) { 131 mt = new int[N]; 132 setSeed(seed); 133 } 134 135 /** Reinitialize the generator as if just built with the given int seed. 136 * <p>The state of the generator is exactly the same as a new 137 * generator built with the same seed.</p> 138 * @param seed the initial seed (32 bits integer) 139 */ 140 @Override 141 public void setSeed(int seed) { 142 // we use a long masked by 0xffffffffL as a poor man unsigned int 143 long longMT = seed; 144 // NB: unlike original C code, we are working with java longs, the cast below makes masking unnecessary 145 mt[0]= (int) longMT; 146 for (mti = 1; mti < N; ++mti) { 147 // See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. 148 // initializer from the 2002-01-09 C version by Makoto Matsumoto 149 longMT = (1812433253l * (longMT ^ (longMT >> 30)) + mti) & 0xffffffffL; 150 mt[mti]= (int) longMT; 151 } 152 153 clear(); // Clear normal deviate cache 154 } 155 156 /** Reinitialize the generator as if just built with the given int array seed. 157 * <p>The state of the generator is exactly the same as a new 158 * generator built with the same seed.</p> 159 * @param seed the initial seed (32 bits integers array), if null 160 * the seed of the generator will be the current system time plus the 161 * system identity hash code of this instance 162 */ 163 @Override 164 public void setSeed(int[] seed) { 165 166 if (seed == null) { 167 setSeed(System.currentTimeMillis() + System.identityHashCode(this)); 168 return; 169 } 170 171 setSeed(19650218); 172 int i = 1; 173 int j = 0; 174 175 for (int k = FastMath.max(N, seed.length); k != 0; k--) { 176 long l0 = (mt[i] & 0x7fffffffl) | ((mt[i] < 0) ? 0x80000000l : 0x0l); 177 long l1 = (mt[i-1] & 0x7fffffffl) | ((mt[i-1] < 0) ? 0x80000000l : 0x0l); 178 long l = (l0 ^ ((l1 ^ (l1 >> 30)) * 1664525l)) + seed[j] + j; // non linear 179 mt[i] = (int) (l & 0xffffffffl); 180 i++; j++; 181 if (i >= N) { 182 mt[0] = mt[N - 1]; 183 i = 1; 184 } 185 if (j >= seed.length) { 186 j = 0; 187 } 188 } 189 190 for (int k = N - 1; k != 0; k--) { 191 long l0 = (mt[i] & 0x7fffffffl) | ((mt[i] < 0) ? 0x80000000l : 0x0l); 192 long l1 = (mt[i-1] & 0x7fffffffl) | ((mt[i-1] < 0) ? 0x80000000l : 0x0l); 193 long l = (l0 ^ ((l1 ^ (l1 >> 30)) * 1566083941l)) - i; // non linear 194 mt[i] = (int) (l & 0xffffffffL); 195 i++; 196 if (i >= N) { 197 mt[0] = mt[N - 1]; 198 i = 1; 199 } 200 } 201 202 mt[0] = 0x80000000; // MSB is 1; assuring non-zero initial array 203 204 clear(); // Clear normal deviate cache 205 206 } 207 208 /** Reinitialize the generator as if just built with the given long seed. 209 * <p>The state of the generator is exactly the same as a new 210 * generator built with the same seed.</p> 211 * @param seed the initial seed (64 bits integer) 212 */ 213 @Override 214 public void setSeed(long seed) { 215 setSeed(new int[] { (int) (seed >>> 32), (int) (seed & 0xffffffffl) }); 216 } 217 218 /** Generate next pseudorandom number. 219 * <p>This method is the core generation algorithm. It is used by all the 220 * public generation methods for the various primitive types {@link 221 * #nextBoolean()}, {@link #nextBytes(byte[])}, {@link #nextDouble()}, 222 * {@link #nextFloat()}, {@link #nextGaussian()}, {@link #nextInt()}, 223 * {@link #next(int)} and {@link #nextLong()}.</p> 224 * @param bits number of random bits to produce 225 * @return random bits generated 226 */ 227 @Override 228 protected int next(int bits) { 229 230 int y; 231 232 if (mti >= N) { // generate N words at one time 233 int mtNext = mt[0]; 234 for (int k = 0; k < N - M; ++k) { 235 int mtCurr = mtNext; 236 mtNext = mt[k + 1]; 237 y = (mtCurr & 0x80000000) | (mtNext & 0x7fffffff); 238 mt[k] = mt[k + M] ^ (y >>> 1) ^ MAG01[y & 0x1]; 239 } 240 for (int k = N - M; k < N - 1; ++k) { 241 int mtCurr = mtNext; 242 mtNext = mt[k + 1]; 243 y = (mtCurr & 0x80000000) | (mtNext & 0x7fffffff); 244 mt[k] = mt[k + (M - N)] ^ (y >>> 1) ^ MAG01[y & 0x1]; 245 } 246 y = (mtNext & 0x80000000) | (mt[0] & 0x7fffffff); 247 mt[N - 1] = mt[M - 1] ^ (y >>> 1) ^ MAG01[y & 0x1]; 248 249 mti = 0; 250 } 251 252 y = mt[mti++]; 253 254 // tempering 255 y ^= y >>> 11; 256 y ^= (y << 7) & 0x9d2c5680; 257 y ^= (y << 15) & 0xefc60000; 258 y ^= y >>> 18; 259 260 return y >>> (32 - bits); 261 262 } 263 264}