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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…