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.
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 sayif (sign == true)
, but in Java this could (and should) be abbreviated toif (sign)
. Similar problem withelse if (sign=false)
: you probably intendedelse if (sign == false)
. This could be correctly written as simplyelse
(because if sign is not true then it must be false). $\endgroup$