AP® Computer Science A · Unit 1 · Topic 1.11

Random Numbers in a Range

Math.random() only gives a decimal from 0 up to just under 1. To get a random integer in a chosen range, you multiply by the range's width, truncate to an int, then add the lowest value.

Math.random() is built to return a double greater than or equal to 0.0 and strictly less than 1.0. That tiny sliver, written [0, 1), is the raw material for every random integer expression you will write. Nothing comes back as exactly 1.0, which matters more than it looks.

To stretch that sliver onto a range of integers, you multiply by how many values you want, then truncate, then shift. Multiplying Math.random() by n scales the result up to something in [0, n). Casting that to (int) chops off the decimal part, leaving a whole number from 0 to n minus 1. Adding the low end of your target range slides that whole set of values up to where you actually want it. For a range from min to max inclusive, the width n is max minus min plus 1, because that is how many integers sit in that range. So a die roll uses width 6: (int) (Math.random() times 6) plus 1 gives 0 through 5, then 1 through 6. A range from 25 to 75 uses width 51: (int) (Math.random() times 51) plus 25 gives 0 through 50, then 25 through 75.

This pattern sits right alongside casting and truncation, because the (int) cast is doing real work here, not just decoration. It also sets up later topics like simulations and loops that repeat a random trial many times, where getting the range exactly right the first time saves you from an off by one bug that is easy to miss.

Key terms

Math.random()
A method that returns a random double greater than or equal to 0.0 and strictly less than 1.0.
Range width
The count of integers from min to max inclusive, calculated as max minus min plus 1.
Truncation
Cutting off the decimal part of a number when casting a double to an int, rounding toward zero.
Shifting
Adding the lowest desired value to a 0-based random result so it lands in the correct target range.

Watch it explained

  1. How it worksHow does multiplying and then shifting Math.random stretch it onto the range you want?
  2. Worked exampleFind the expression that produces a random integer from 1 to 6 for one die roll.
  3. Worked exampleFind the expression for a random integer from 25 to 75 inclusive, and check both ends.
  4. Common mistakeWhy doesn't (int) (Math.random()·6) ever produce a 6?
  5. Going furtherWhat happens to the spread of results when you roll two dice and add them together?

Check yourself

Your turn1 of 2
A program wants a random integer from 14 to 46 inclusive. How many different integer values are possible in that range?

End of topic.