skurtsky
skurtsky

Reputation: 13

How to manage probabilities in an array?

I have 2 2D arrays that store data for a fractal. My first array has 3 rows and the last value of each row is the probability.

Row 1 has 0.33 probability, Row 2 has 0.33 probability, and Row 3 has 0.34 probability

Right now what I am doing is I generate a random double from 0-1. and I use if statements to determine which row I should be using.

here are my arrays:

    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

here is the code to determine which row to use:

            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; 

I feel as if there should be a better way to do this. Also, my second array has 4 rows and different probabilities and I would like to use the same method for that array.

Upvotes: 0

Views: 242

Answers (1)

Andreas
Andreas

Reputation: 159114

If you want a general solution, just iterate the array until you reach the threshold. The result is not really any slower than what you're doing.

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];
}

Upvotes: 2

Related Questions