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. –  eevar Mar 20 '11 at 13:40
The OP should edit their post to remove the unfounded claim. –  quant_dev Mar 24 '11 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). –  rajah9 Nov 10 '11 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.

-
Thanks - This is perfect! –  pd123 Mar 18 '11 at 22:23
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. –  quant_dev Mar 19 '11 at 17:26
@quant_dev I smiled when I read: This is not cryptography. You're right! –  Feral Oink Jan 7 '12 at 9:36