Download code

Jump to: navigation, search

Back to Mersenne_twister_(Java)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

MT.java

 1 /* The authors of this work have released all rights to it and placed it
 2 in the public domain under the Creative Commons CC0 1.0 waiver
 3 (http://creativecommons.org/publicdomain/zero/1.0/).
 4 
 5 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 
13 Retrieved from: http://en.literateprograms.org/Mersenne_twister_(Java)?oldid=5676
14 */
15 
16 public final class MT {
17     private int mt_index;
18     private int[] mt_buffer = new int[624];
19 
20     public MT() {
21         java.util.Random r = new java.util.Random();
22         for (int i = 0; i < 624; i++)
23             mt_buffer[i] = r.nextInt();
24         mt_index = 0;
25     }
26 
27     public int random() {
28         if (mt_index == 624)
29         {
30             mt_index = 0;
31             int i = 0;
32             int s;
33             for (; i < 624 - 397; i++) {
34                 s = (mt_buffer[i] & 0x80000000) | (mt_buffer[i+1] & 0x7FFFFFFF);
35                 mt_buffer[i] = mt_buffer[i + 397] ^ (s >> 1) ^ ((s & 1) * 0x9908B0DF);
36             }
37             for (; i < 623; i++) {
38                 s = (mt_buffer[i] & 0x80000000) | (mt_buffer[i+1] & 0x7FFFFFFF);
39                 mt_buffer[i] = mt_buffer[i - (624 - 397)] ^ (s >> 1) ^ ((s & 1) * 0x9908B0DF);
40             }
41         
42             s = (mt_buffer[623] & 0x80000000) | (mt_buffer[0] & 0x7FFFFFFF);
43             mt_buffer[623] = mt_buffer[396] ^ (s >> 1) ^ ((s & 1) * 0x9908B0DF);
44         }
45         return mt_buffer[mt_index++];
46     }
47 }
48 


hijacker
hijacker
hijacker
hijacker