Question

In java class there is random instance that is shared between two methods.

public class Utils{
    Random rand = new Random();

    public double nextGaussian1(){
          return rand.nextGaussian();
    }

    public double nextGaussian2(){
          return rand.nextGaussian();
    }   
}

Can I use only one Random instance to get Gaussian distributions from 2 methods?

Was it helpful?

Solution

Yes, you can use one instance of Random. The backing implementation for nextGaussian() is Box, Muller, & Marsaglia's Polar method which generates Gaussians in pairs. The first call to it will generate a pair and return the first of the two values, the next call will just return the previously generated second value. The pairs are mathematically independent(*) if the uniform inputs are. In theory this can be a problem if the uniforms come from a linear congruential generator with a bad lattice structure, but Java's LCG is pretty decent and in practice the results can be considered effectively independent for most uses.

The bigger question would be why do you need two different methods to be sources of Gaussians? What does that gain you that just calling rand.nextGaussian() wouldn't achieve?

(*) - the Gaussian return values are sine & cosine components of a vector generated in polar coordinates, and are thus orthogonal. For Gaussians, orthogonality implies independent.

OTHER TIPS

If the two methods are called randomly, this is fine, however if you call these in a pattern like follow, it won't work as intended as it generates pairs of Gaussian numbers

for(int i = 0; i < 100; i++ ) {
    values1[i] = Utils.nextGaussian1();
    values2[i] = Utils.nextGaussian2();
}

This is the same problem as

Random rand = new Random();
for(int i = 0; i < 100; i++ ) {
    values1[i] = rand.nextGaussian();
    values2[i] = rand.nextGaussian();
}

BTW A simple way to make a utility class is to use an enum with no instances

public enum Utils {;
     // class is final with a private constructor

     public static double nextGaussian() {
          return random.nextGaussian();
     }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top