Example 3: General Discrete Random Numbers

In this example, nextDiscrete is used to generate 2 groups of five pseudorandom variates from the discrete distribution:

\begin{array}{c}\operatorname{Pr}(X=1)=0.05\\ \operatorname{Pr}(X=2)=0.45\\\operatorname{Pr}(X=3)=0.31 \\ \operatorname{Pr}(X=4)=0.04\\\operatorname{Pr}(X=5)=0.15\end{array}

import com.imsl.stat.*;
import com.imsl.math.*;

public class RandomEx3 {

    static Random IMSLRandom() {
        Random r = new Random();
        r.setSeed(123457);
        r.setMultiplier(16807);
        return r;
    }

    public static void main(String args[]) {
        int[] deviates = new int[5];
        double[] prob1 = {.05, .45, .31, .04, .15};
        PrintMatrix pm = new PrintMatrix("Random deviates");
        PrintMatrixFormat pmf = new PrintMatrixFormat();
        Random r = IMSLRandom();

        for (int i = 0; i < 5; i++) {
            deviates[i] = r.nextDiscrete(1, prob1);
        }

        pmf.setNoColumnLabels();
        pmf.setNoRowLabels();
        pm.print(pmf, deviates);

        for (int i = 0; i < 5; i++) {
            deviates[i] = r.nextDiscrete(1, prob1);
        }

        pm.print(pmf, deviates);
    }
}

Output

Random deviates
     
3  
2  
2  
3  
5  

Random deviates
     
1  
3  
4  
5  
3  

Link to Java source.