问题描述
给出一个大小为 n
的数组,我想为每个索引生成随机概率,以使 Sigma(a [0] .. a [n-1])= 1
Given an array of size n
I want to generate random probabilities for each index such that Sigma(a[0]..a[n-1])=1
一个可能的结果可能是:
One possible result might be:
0 1 2 3 4
0.15 0.2 0.18 0.22 0.25
另一个完全合法的结果可能是:
Another perfectly legal result can be:
0 1 2 3 4
0.01 0.01 0.96 0.01 0.01
如何才能轻松,快速地生成这些内容?任何语言的答案都可以,最好是Java.
How can I generate these easily and quickly? Answers in any language are fine, Java preferred.
推荐答案
您要完成的任务无异于从N维单位单纯形中绘制随机点.
The task you are trying to accomplish is tantamount to drawing a random point from the N-dimensional unit simplex.
http://en.wikipedia.org/wiki/Simplex#Random_sampling 可能帮助您.
天真的解决方案可能如下:
A naive solution might go as following:
public static double[] getArray(int n)
{
double a[] = new double[n];
double s = 0.0d;
Random random = new Random();
for (int i = 0; i < n; i++)
{
a [i] = 1.0d - random.nextDouble();
a [i] = -1 * Math.log(a[i]);
s += a[i];
}
for (int i = 0; i < n; i++)
{
a [i] /= s;
}
return a;
}
要从N维单位单纯形中均匀地绘制一个点,我们必须获取一个指数分布的分布随机变量的矢量,然后通过这些变量的总和对其进行归一化.要获得指数分布的值,我们对均匀分布的值取负 log .
To draw a point uniformly from the N-dimensional unit simplex, we must take a vector of exponentially distributed random variables, then normalize it by the sum of those variables. To get an exponentially distributed value, we take a negative log
of uniformly distributed value.
这篇关于生成总数为1的N个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!