Skip to content
psambit9791 edited this page Dec 10, 2023 · 5 revisions

The Random class provides utilities to generate pseudo-random numbers based on some distribution.

Although JAVA provides a Random class, it does not provide a consistent way to generate Random numbers and especially matrices. This class allows us to generate random numbers as samples or as matrices (supported to generate upto 3-dimensional matrices).

Currently, it supports the following distributions:

  • Normal Distribution
  • Uniform Distribution
    • As doubles in the range of 0.0 and 1.0
    • As ints in a provided range
Generating from a Normal Distribution
CODE
long seed = 42;
Random r1 = new Random(seed);
r1.setMeanAndSD(10.0, 1.0); //Optional; default is mean = 0.0 and S.D = 1.0
double sample = r1.randomNormalSample();
double[] arrayOne = r1.randomNormal1D(new int[]{4});
double[] arrayTwo = r1.randomNormal2D(new int[]{3, 3});
double[] arrayThree = r1.randomNormal3D(new int[]{2, 2, 2});
Output:

Sample:

$$9.31$$

Array One:

$$[11.94, 10.01, 9.37, 9.55]$$

Array Two:

$$\begin{bmatrix} 11.40 & 11.91 & 9.73\\ 10.27 & 10.43 & 8.03\\ 10.49 & 10.59 & 10.36 \end{bmatrix}$$
Generating from a Uniform Distribution between 0.0 and 1.0
CODE
long seed = 42;
Random r1 = new Random(seed);
double sample = r1.randomDoubleSample();
double[] arrayOne = r1.randomDouble1D(new int[]{4});
double[] arrayTwo = r1.randomDouble2D(new int[]{3, 3});
double[] arrayThree = r1.randomDouble3D(new int[]{2, 2, 2});
Output:

Sample:

$$0.39$$

Array One:

$$[0.73, 0.68, 0.31, 0.28]$$

Array Two:

$$\begin{bmatrix} 0.67 & 0.9 & 0.37\\ 0.28 & 0.46 & 0.78\\ 0.92 & 0.44 & 0.75 \end{bmatrix}$$
Generating from a Uniform Distribution of Integers in a given range
CODE
long seed = 42;
Random r1 = new Random(seed);
int sample = r1.randomIntSample();
int[] arrayOne = r1.randomInt1D(new int[]{4}, 5, 10);
int[] arrayTwo = r1.randomInt2D(new int[]{3, 3}, 5, 10);
int[] arrayThree = r1.randomInt3D(new int[]{2, 2, 2}, 5, 10);
Output:

Sample:

$$5$$

Array One:

$$[7, 8, 5, 7]$$

Array Two:

$$\begin{bmatrix} 5 & 6 & 10\\ 7 & 6 & 10\\ 7 & 7 & 5 \end{bmatrix}$$
Clone this wiki locally