Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generating a discrete random variable in Java?

Today in interview they asked me this question? How to generate a discrete random variable in Java? I couldn’t do it but I wonder the solution.
They gave me an array:

double[] probabilities={.2,.1,.3,.4};
double[] outcomes ={4,5,8,11.5};

And this should give the answer:

double discreteRV = problem.randPMF(probabilities,outcomes);

I couldn’t understand how to solve this question.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Since all the probabilities will always add up to 1, you can generate a random number between 0 and 1 then iterate through the probabilities and subtract them. When the number is less than or equal to 0, the index of the last subtracted probability is the index of the outcome:

import java.util.Random;
public static double randPMF(double[] prob, double[] out) {
    double rand = Math.random();
    int index = -1;
    while (rand >= 0) {
        index++;
        rand -= prob[index];
    }
    return out[index];
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading