Learn more from fewer runsLesson 43 of 76 · 8 min
Vectorise without changing the question
Replace a loop with array operations and verify the same calculation.
Vectorisation applies an operation to arrays rather than executing a Python loop for each scalar. It can reduce interpreter overhead, but the main requirement is that the numerical procedure still represents the same trials.
Generate the random inputs once, then calculate the outcome using a loop and an array expression. This paired check isolates the implementation of the calculation from differences in random draws. Equal-looking averages from different draws would be a much weaker equivalence check.
Large arrays also consume memory. If a simulation needs more draws than fit comfortably, process chunks and combine counts or stable summaries. Do not change the trial definition at chunk boundaries. Timing claims require actual measurements of the relevant environment; this lesson checks answers and storage rather than inventing a speedup.
In the code, array_equal checks exact equality of the two arrays. allclose is a related check allowing small rounding differences; either checks values and shape, not model validity.
- Keep the same inputs
- Loop or array operations
- Verify agreement
What should be held fixed when comparing a loop and a vector expression for correctness?
Write a prediction (optional)
Seeded teaching simulation
Select Run Python below with the code unchanged.
A saved draft is open. To run the published example, open Tools and select Restore example. Recover draft brings your code back.
Execution error
Technical error details
Your result
Published example output
This result comes from the original Python. Your runs appear above. Build environment ↗
Loop/vector/chunk answers identical: True Input array bytes: 48000 Mean outcome: 21.1002
Read the first result
All implementations use exactly the same random inputs and trial rule. That is why exact equality is a useful check here.
Try an edit
Add + row[0]*row[0] after the maximum in loop_result, + inputs[:, 0]*inputs[:, 0] after the maximum in array_result, and + chunk[:, 0]*chunk[:, 0] after the maximum in chunked. Keep both equality checks. Select Run Python again. Does Loop/vector/chunk answers identical still say True? Which changed output shows that you chose a different trial rule?
Scope. Answer equivalence does not establish relative execution speed or suitability for every array size.
Try a fresh case
Two implementations have similar mean outputs from different random samples. Does that establish equivalence?
Need a hint?
Hint 1
Separate random-input variation from implementation differences.
Hint 2
Compare the same trial in both versions.