Java 中或 Apache Commons Math 等库中是否有与 MATLAB 函数等效的函数随机样本 http://www.mathworks.com/help/stats/randsample.html?
更具体地说,我想找到一个函数randSample
它根据我指定的概率分布返回独立且同分布的随机变量的向量。
例如:
int[] a = randSample(new int[]{0, 1, 2}, 5, new double[]{0.2, 0.3, 0.5})
// { 0 w.p. 0.2
// a[i] = { 1 w.p. 0.3
// { 2 w.p. 0.5
输出与 MATLAB 代码相同randsample([0 1 2], 5, true, [0.2 0.3 0.5])
哪里的true
表示放回抽样。
如果这样的函数不存在,我该如何编写呢?
Note:我知道一个类似的问题 https://stackoverflow.com/questions/19262558/equivalent-of-matlabs-randsample-random-sample已在 Stack Overflow 上询问,但遗憾的是尚未得到答复。
我很确定这个函数不存在,但是创建一个生成这样的样本的函数非常容易。首先,Java 确实带有一个随机数生成器,特别是一个带有函数的随机数生成器,Random.nextDouble()
可以产生 0.0 到 1.0 之间的随机双精度数。
import java.util.Random;
double someRandomDouble = Random.nextDouble();
// This will be a uniformly distributed
// random variable between 0.0 and 1.0.
如果您有放回抽样,如果您将作为输入的 pdf 转换为 cdf,则可以使用 Java 提供的随机双精度数通过查看它落在 cdf 的哪一部分来创建随机数据集。因此,首先您需要将 pdf 转换为 cdf。
int [] randsample(int[] values, int numsamples,
boolean withReplacement, double [] pdf) {
if(withReplacement) {
double[] cdf = new double[pdf.length];
cdf[0] = pdf[0];
for(int i=1; i<pdf.length; i++) {
cdf[i] = cdf[i-1] + pdf[i];
}
然后创建适当大小的整数数组来存储结果并开始查找随机结果:
int[] results = new int[numsamples];
for(int i=0; i<numsamples; i++) {
int currentPosition = 0;
while(randomValue > cdf[currentPosition] && currentPosition < cdf.length) {
currentPosition++; //Check the next one.
}
if(currentPosition < cdf.length) { //It worked!
results[i] = values[currentPosition];
} else { //It didn't work.. let's fail gracefully I guess.
results[i] = values[cdf.length-1];
// And assign it the last value.
}
}
//Now we're done and can return the results!
return results;
} else { //Without replacement.
throw new Exception("This is unimplemented!");
}
}
有一些错误检查(确保值数组和 pdf 数组大小相同)以及一些其他功能,您可以通过重载它来实现以提供其他功能,但希望这足以让您开始。干杯!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)