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:
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
EasyA shop simulates a week that a rerun must repeat.
- Make
rng_afrom the seed and draw 7 customer counts, 20 to 60 inclusive, then 7 normal spends: mean 15, std 4. - Draw the counts again from
rng_bon the same seed andrng_con the seed plus 1. - 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: 1Try it yourself
import numpy as np
seed = int(input())
# Write your code below
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Data and Plots
2NumPy Arrays
Creating ArraysShape and SizeRanges of NumbersIndexing and SlicingRecap: Temperature GridPractice on your own: Online Python compiler