Menu
CoddyTech

Random Numbers

Part of the Data and Plots section of Coddy's Machine Learning journey. Lesson 18 of 60.

Simulations, shuffled data and untrained models all start from random numbers. These 1,000 made-up heights took one line:

A histogram of 1,000 random heights shaped like a bell, tallest around the mean of 170 cm and thinning out toward 140 and 200

NumPy draws them from a generator, started by a seed:

rng = np.random.default_rng(42)
heights = rng.normal(170, 10, size=1000)
print(np.round(heights[:4], 1))
print(rng.integers(1, 7, size=5))
print(np.round(rng.random(3), 2))

This prints:

[173.  159.6 177.5 179.4]
[2 4 3 3 5]
[0.44 0.13 0.09]

normal(mean, std, size) clusters around its mean. integers leaves out its stop, like range. random gives decimals from 0 to 1.

The same seed gives the same numbers on any computer, so anyone can repeat your experiment. Each draw moves the generator on.

challenge icon

Challenge

Easy

A shop simulates a week that a rerun must repeat.

  1. Make rng_a from the seed and draw 7 customer counts, 20 to 60 inclusive, then 7 normal spends: mean 15, std 4.
  2. Draw the counts again from rng_b on the same seed and rng_c on the seed plus 1.
  3. Print as below: spends to 1 decimal, and how many days b and c match a.

For the seed 12:

Customers: [45 30 59 58 22 27 28]
Spend: [21.5 10.2 12.5  9.7 14.6 19.  14.9]
Same seed, days that match: 7
Seed + 1, days that match: 1

Try it yourself

import numpy as np

seed = int(input())

# Write your code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Data and Plots

Practice on your own: Online Python compiler