Java: Generating Random Integers Using Math.random()

Math.random() generates a double between 0 inclusive and 1 exclusive. An easier way to think of this is that Math.random() generates a random double between [0, 1) where “[” is inclusive and “)” is exclusive.

I like this notation better because it helps to make a connection between programming classes and math classes. This connection makes it easier to understand how to generate integers with Math.random() because the experience shifting graphs in math will transfer over to generating random numbers.

So to generate an integer between a certain range, we can just shift the decimal generation and then cast it to an integer. It is important to note that an integer cast will always round down.

//Random decimal between [0, 1)

double randomDecimalBetweenZeroAndOne = Math.random();

//Random integer between [0 * 10, 1 * 10) which equals [0, 10)

int randomIntegerBetweenZeroAndNineInclusive = (int) (Math.random() * 10);

//Random integer between [0*6 + 5, 1*6 + 5) which equals [5, 11)

int randomIntegerBetweenFiveAndTenInclusive = (int)(Math.random() * 6 + 5)

Can you figure out how to write an inclusive method to generate random numbers? Comment below!

Leave a Reply

Your email address will not be published. Required fields are marked *