如何管理数组中的概率?



我有 2 个 2D 数组来存储分形的数据。我的第一个数组有 3 行,每行的最后一个值是概率。

第 1 行的概率为 0.33, 第 2 行的概率为 0.33,并且 第 3 行的概率为 0.34

现在我正在做的是我从 0-1 生成一个随机双精度。 我使用 if 语句来确定我应该使用哪一行。

这是我的数组:

static double[][] SierpGasketMatrix = { { 0.5, 0, 0, 0.5, 0, 0, 0.33 }, //row 1
{ 0.5, 0, 0, 0.5, 0, 0.5, 0.33 }, //row 2
{ 0.5, 0, 0, 0.5, 0.43, 0.25, 0.34 } }; //row 3
static double[][] BarnsleyFernMatrix = { { 0, 0, 0, 0.16, 0, 0, 0.01 }, //row 1
{ 0.85, 0.04, -0.04, 0.85, 0, 1.6, 0.85 }, //row 2 
{ 0.2, -0.26, 0.23, 0.22, 0, 1.6, 0.07 }, //row 3
{ -0.15, 0.28, 0.26, 0.24, 0, 0.44, 0.07 } }; //row 4

下面是确定要使用的行的代码:

double randNum = Math.random();
int row = -1;
if (randNum < 0.33)
row = 0;
else if (randNum < 0.66)
row = 1;
else if (randNum < 1.00)
row = 2; 

我觉得应该有更好的方法来做到这一点。此外,我的第二个数组有 4 行和不同的概率,我想对该数组使用相同的方法。

如果你想要一个通用的解决方案,只需迭代数组,直到达到阈值。结果并不比你正在做的事情慢。

static double[] getRandomRow(double[][] data) {
double randNum = Math.random();
double threshold = 0.0;
for (double[] row : data) {
threshold += row[row.length - 1]; // probability = last value of row
if (threshold > randNum)
return row;
}
// We should never get here, but float math is imprecise, so just return last row.
// Could also be that input probabilities don't add to 1, so handle that if necessary.
return data[data.length - 1];
}

最新更新