Random Numbers

NumPy can generate random numbers with a random number generator.

rng is the generator object. It can produce different kinds of random values.

Integers

rng.integers(1, 7, size=5)

This produces five integers from 1 up to, but not including, 7. It is a way to simulate five dice rolls.

Floating-point values

rng.random(5)

This produces five floating-point values in the half-open interval [0, 1): zero is possible, but one is not.

Generate random values

Runs locally with Python in your browser.

Ready to run.

The values are random-looking, but the seed makes this example rerunnable.

Shape still matters

Random arrays have shapes like any other arrays:

rng.random((2, 3))

produces a two-by-three array.

Exercise: Random array shape

What shape does rng.random((2, 3)) produce?

Answer it first, then check.

Hint

The tuple passed to random directly states the requested output shape.

Solution

The output shape is (2, 3): two rows and three columns.