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