By: Nicholas Duchon.

Using the Random class produces a set of random numbers, either as int's or as float's, or other options.

Floating and double random numbers:

Code:

Random rn = new Random(); // declare and instantiate a new variable

double x, y, g;

g = x + y * rn.nextDouble(); // get next double random number and scale it

What are the meanings of x and y in the last expression?

If we let x = 2 and y = 3 in the expression, we can illustrate
the result in the two figures above.

The first figure shows the range [0,1) multiplied by 3 to get the range [0,3). Note that all of the numbers will begin with whole parts of 0, 1 or 2 (i.e., 0.2324, or 2.2322, or 1.4432; NOT 3.0000).

When 2 is added to this range, the final range is [2,5), but as you can see, no number starting with 5 will be included. The result will numbers in the 2's, 3's and 4's.

This answers the question of how to get a uniform distribution of numbers starting with 2, 3 and 4, but not 5. Let us assume that I was asked to produce a method that will accept two integers (say 1 and 6) and produce a set of random numbers in that range. This would be like simulating die rolls. I want all of the numbers between 1 and 6 (inclusive) to come up with a probability of 1/6, so I need to multiply the range by 6.

BUT 6-1 is 5, which is not the right range! The solution is
to take the range (6 - 1 + 1) or in general (top - bottom +
1), then add the lowest number (1 in the 1-6 example, bottom
in the general example).

ND.