Java Reference ยท java.lang
Java Math.random()
Reference for Java Math.random(): how it produces doubles in [0, 1), scaling to integer ranges, why it cannot be seeded, and better alternatives.
Math.random() returns a pseudo-random double that is greater than or equal to 0.0 and less than 1.0. It is the shortest way to get a random number in Java and is fine for games, simple simulations and quick demos.
Internally it uses one shared java.util.Random instance that the JVM creates on first use. You cannot seed it, so the sequence differs on every run and cannot be reproduced. When you need repeatable numbers, a bounded integer, or good behavior across many threads, use Random, ThreadLocalRandom or RandomGenerator instead.
double d = Math.random(); // e.g. 0.7312... int dice = (int) (Math.random() * 6) + 1; // 1..6
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public static double random()
Parameters: none.
Returns: a double r with 0.0 <= r < 1.0, approximately uniformly distributed.
Throws: nothing.
Usage notes
- Range formula. For integers from
mintomaxinclusive:min + (int) (Math.random() * (max - min + 1)). Forgetting the+ 1makes the upper bound unreachable; casting before multiplying ((int) Math.random() * n) always gives0. - No seed. You cannot make
Math.random()repeat. Tests that depend on random values should inject aRandomwith a fixed seed instead. - Slightly biased for huge ranges. A
doublehas 53 bits of precision, so ranges above about 2^53 cannot be covered, and modulo-free scaling has tiny non-uniformity. UseRandom.nextInt(bound)ornextLong(bound)for exact uniform integers. - Thread safety. It is safe from several threads, but they share one generator, so heavy contention slows it down.
ThreadLocalRandom.current()avoids that. - Not secure. The numbers are predictable from earlier output. Tokens, passwords and keys require
java.security.SecureRandom. - Modern API. Since Java 17,
RandomGenerator(andnextInt(origin, bound)) provide a uniform interface to many algorithms, and the same range code works for every generator. - Shuffling and sampling. Use
Collections.shuffle(list, random)rather than writing your own.
Related
Math,Math.round(),Integer- Lessons: Random numbers, Math