# Mersenne twister random number generator in Java for Monte Carlo Sim.

I am using the Mersenne twister random number generator in Java for a Monte Carlo Simulation. I need a uniform distribution of values between -1 and 1. My code is below (I am importing org.apache.commons.math.random.MersenneTwister, which is a Apache Commons library that contains the methods I am calling).

for(int i = 0; i<= NumberOfTrials-1; i++ ) {
MersenneTwister mtsign = new MersenneTwister();
boolean sign = mtsign.nextBoolean();            // random true or false
MersenneTwister mt = new MersenneTwister();
if (sign=true){
random[i] = mt.nextDouble(); }  //i.e. (random number between 0 and 1)
else if (sign=false){
random[i] = - mt.nextDouble(); }   // i.e. random number beween -1 and 0
}


Each index of the resulting array, random[], contains the same value for some reason (and all are positive as boolean keeps returning true). Any thoughts/advice is greatly appreciated.

• "I am implementing a Mersenne twister random number generator" -- Actually, you are just using an existing Mersenne twister implementation/library. "Implementing" means writing your own. Commented Mar 20, 2011 at 13:40
• The OP should edit their post to remove the unfounded claim. Commented Mar 24, 2011 at 21:01
• I'm noticing a common Java mistake that you probably have already found and corrected. When you say if (sign=true), you are not just testing sign, you also assigning sign to true and then testing it (and it will always be true). You probably intended to say if (sign == true), but in Java this could (and should) be abbreviated to if (sign). Similar problem with else if (sign=false): you probably intended else if (sign == false). This could be correctly written as simply else (because if sign is not true then it must be false). Commented Nov 10, 2011 at 16:29

The problem is that you are creating a new random number generator for each iteration. Move new MersenneTwister() out of the loop:

MersenneTwister mtsign = new MersenneTwister();
MersenneTwister mt = new MersenneTwister();
for(int i = 0; i<= NumberOfTrials-1; i++ ) {
// use mtsign and mt here
...
}


Furthermore, you don't need two generators, you can just rescale:

MersenneTwister mt = new MersenneTwister();
for(int i = 0; i<= NumberOfTrials-1; i++ ) {
random[i] = mt.nextDouble() * 2 - 1;
}


Lastly, in your code, you may need to push the generator even further up the call tree to avoid generating the same sequence repeatedly.

• In practical applications you usually want to recreate the generator (with a fixed seed) for every simulation set, to ensure that the results are reproducible. This is not cryptography, you don't need "true" randomness. Commented Mar 19, 2011 at 17:26
• @quant_dev I smiled when I read: This is not cryptography. You're right! Commented Jan 7, 2012 at 9:36