Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
773 views
in Technique[技术] by (71.8m points)

random - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...