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 spellingFor 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).
The shortcut
For matrix shapes, write them side by side and cancel the touching middle numbers: (2, 3) @ (3, 4) → the 3s touch and cancel → (2, 4). If the middle numbers differ, the multiplication is impossible.
Set up the shapes
qtyhas shape(3, 2): 3 branches, 2 genres.unit_pricehas shape(2,): one price per genre.
The trap is using * when you mean @. On 2-D arrays, * multiplies matching positions and returns a grid, not a matrix product.
Drills
Answer fast — trust the rule.
Which call can return the value 10?
Why pass a seed to default_rng?
What is np.array([1, 2, 3]) @ np.array([4, 5, 6])?
A has shape (4, 3) and B has shape (3, 2). What shape is A @ B?
With the same shapes, which product is impossible?
Remember
- Seed the generator to repeat randomness; upper bounds are excluded.
@multiplies in pairs and adds; for matrices, the touching middle sizes must match.*is position by position,@is the matrix product.
