# Random Numbers

Source: https://cca.twango.dev/AP-Computer-Science/random

# Random Numbers

## `Math.random()`

Returns a pseudorandom `double` in $[0.0, 1.0)$, using a shared random-number generator internally.

## Generate an integer in $[a, b)$

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

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

> [!warning] 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](https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#random--).

Related: [[type-casting|Type casting]] · [[variables|Arithmetic]]
