Java 中或 Apache Commons Math 等库中是否有等同于 MATLAB 函数的函数 randsample ?
更具体地说,我想找到一个函数 randSample
,它根据我指定的概率分布返回独立同分布随机变量的 vector 。
例如:
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
表示采样替换。
如果不存在这样的函数,我该如何编写一个?
注意:我知道 similar question已在 Stack Overflow 上被问及,但遗憾的是尚未得到答复。
最佳答案
我很确定不存在这样的函数,但是制作一个可以生成这样的样本的函数非常容易。首先,Java 确实带有一个随机数生成器,特别是一个带有函数 Random.nextDouble()
的函数,它可以生成 0.0 到 1.0 之间的随机 double 值。
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 提供的随机 double 来创建随机数据集,方法是查看它落在 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 数组大小相同)和一些其他功能,您可以通过重载它来提供其他功能来实现,但希望这足以让您开始。干杯!
关于java - 在 Java 中带替换的加权采样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20863638/