CCA Guide
Random Numbers

Random Numbers

Curated by Last modified: 1 min read

View Markdown

Math.random()

Returns a pseudorandom double in , using a shared random-number generator internally.

Generate an integer in

For integer bounds a < b and a positive b - a that fits in int:

int myRandInt = a + (int) (Math.random() * (b - a));

Correction to the original example

The original cast surrounded the addition of a: (int) (Math.random() * (b - a) + a). Casting truncates toward zero, so that version gives the wrong interval for negative lower bounds. Cast the nonnegative offset first, then add a.

Source: Math.random.

Related: Type casting · Arithmetic

Linked to this page