Java 中有没有一种方法可以按照固定的均值和标准差生成随机数?

Is there a way in Java to generate random numbers following fixed mean and standard deviation?

问题

我知道如何生成具有固定均值和标准差的随机数。

我还希望将这些值限制在一个范围内(我知道这意味着结果不会是真正的高斯分布,而是剪裁的高斯分布)

上下文

我要回答的更广泛的问题是

Assume you have a black box that gives out a monkey every 10 sec, the height of the monkey is between 24 and 36 inches. The height of the monkeys generated over half n hour follows a normal distribution with mean 30.5 inches and standard deviation 2.5. While there is another box in the room that causes a monkey to vanish if it’s height is below 28 inches, this happens every 20 secs. Write a program to calculate the number of monkeys left in the room after n-days (n is a user input). For the sake of logic assume room is large enough to accommodate an infinite number of monkeys and they have food.

As VGR mentioned in their comment you can use Random.nextGaussian() 生成高斯分布随机数,均值为零,标准差为 1。您可以通过与该值相加来影响均值,通过与该值相乘来影响标准差。因此,您可以一起使用您的嘲笑属性生成随机数。你会想要

desiredMean + desiredStandardDeviation * Random.nextGaussian()

您已经声明了一个额外的要求,即值必须在一个范围内,您可以轻松地实现这一点,只需重新滚动一个新值,直到您获得该范围内的一个值。

nextGaussian() 方法returns 均值为 0,标准差为 1 的随机数。

这意味着 nextGaussian() 返回的数字将倾向于 "cluster" 0 左右,并且(大约)70% 的值将介于 -1 和 1 之间。基于 nextGaussian( ),您可以缩放和移动它们以获得其他正态分布:

  • 要更改分布的平均数,请添加所需的 值;

  • 要更改标准偏差,乘以该值。

例子: 生成平均值为 500 且标准差为 100 的值:

double val = r.nextGaussian() * 100 + 500;

生成平均值为 30.5 且标准差为 2.5 的值:

double val = r.nextGaussian() * 2.5 + 30.5;

这 70% 的值将在 28 到 33 之间。由于 99.7% 的值位于 3-sigma 范围内,因此猴子的身高在 24 到 36 之间。