Skip to the workspace
Pebellslearn by building
NumPy Arrays  ›  Capstone Project

Random Numbers and Linear Algebra Basics

Random Module 14 minA seeded random generator makes repeatable fake data, and the @ operator multiplies arrays in pairs and adds, provided the inner shapes match.

python data analysis / Random Numbers and Linear Algebra Basics

Explore each scene at your own pace.

01 · The rule

The rule

Random Numbers and Linear Algebra Basics

The bookshop wants to test a report before real data arrives, so it needs believable fake sales. Later it wants one number from two lists: total revenue from copies and prices. The first job is NumPy's random generator; the second is the simplest piece of linear algebra, the dot product.

The rule

Seed the generator to repeat randomness; @ multiplies and adds in one step.

Modern NumPy makes random numbers through a generator object:

rng = np.random.default_rng(42)       # 42 is the seed

rng.integers(1, 7, size=5)            # five whole numbers from 1 to 6
rng.random(3)                         # three floats in [0, 1)
rng.normal(loc=3, scale=1, size=4)    # four values around 3
rng.choice(["Pune", "Delhi", "Chennai"], size=4)

Note that integers(1, 7) never returns 7: the upper bound is excluded, the same rule as slicing.

The seed fixes the starting point. Create two generators with the same seed and they produce the same sequence, so a colleague who reruns your notebook gets your exact numbers. Without a seed, every run differs.

Now the linear algebra. The dot product of two equal-length arrays multiplies them position by position and adds the results:

copies = np.array([3, 5, 2, 4, 1, 6, 2, 3])
price  = np.array([250, 400, 400, 250, 250, 120, 120, 400])

copies @ price          # 6960, same as (copies * price).sum()
np.dot(copies, price)   # 6960, the older spelling

For 2-D arrays, @ is matrix multiplication: each row of the left meets each column of the right. The inner sizes must match: (2, 3) @ (3, 4) is allowed and gives (2, 4). A.T flips rows and columns (the transpose).

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.