javarandomlimitgaussian

Does Java ThreadLocalRandom.current().nextGaussian() have a limit?


I'm writing some software that requires the generation of random numbers normally distributed around 0, but with a reliable, known limit of +/- 10.

Consider the following Java 8 code:

int floorMax = 10;
int totalRuns = 1000000000;

int[] floorCounts = new int[floorMax+1];

for (int i = 0; i < totalRuns; i++)
  floorCounts[
    (int) Math.floor(Math.abs(
      ThreadLocalRandom.current().nextGaussian()
    ))
    ]++;

for (int c = 0; c < floorMax; c++)
  System.out.println(
    "# of values between " + String.valueOf(c) +
      " and " + String.valueOf(c + 1) +
      ": " + floorCounts[c]);

It executes on my local machine in 42 seconds:

# of values between 0 and 1: 682679980
# of values between 1 and 2: 271828237
# of values between 2 and 3: 42795770
# of values between 3 and 4: 2633149
# of values between 4 and 5: 62319
# of values between 5 and 6: 544
# of values between 6 and 7: 1
# of values between 7 and 8: 0

Besides the obvious hard limit of Java double value, is there a limit of nextGaussian()? Since this is being generated by random noise, I assume that the output of nextGaussian() could be any double value. However, with an (observed) 1 in 1000000000 chance of being above 6.0, it appears this could still be a useful solution to my problem, if a limit is enforced.


Solution

  • nextGaussian() can return any value that can represented by a double data type. Gaussian distribution approaches but never reaches 0 on either side. So it's theoretically possible to get a value of Double.MAX_VALUE, but very unlikely.

    Gaussian distribution looks like this: enter image description here (http://hyperphysics.phy-astr.gsu.edu/hbase/Math/gaufcn.html)

    The distribution stretches to positive and negative infinity, so there is theoretically no absolute limit. Since we're running in the VM, and nextGaussian() returns a double, we're constrained to the magnitude and precision that a double can represent.