Practice question · Sort into groups
Sort each code pattern by its style.
Groups: Vectorised · Explicit loop
- total = sum(a)
- for each x in a, set total = total + x
- c = a + b
- d = 2 * a
- for each index i, set c[i] = a[i] + b[i]
Hints
- Look for whether an index appears anywhere in the code.
- Each pair here computes exactly the same thing in the two styles.
Show the answer
Vectorised: c = a + b, total = sum(a), d = 2 * a
Explicit loop: for each index i, set c[i] = a[i] + b[i], for each x in a, set total = total + x
Why
Vectorised code names whole arrays and no indices; the loop versions compute identical results far more slowly. The pairs are deliberately equivalent so that the only difference is the idiom, and hence the speed.
Practise Vectorised Computation and Libraries
The app has 5 more questions on this lesson, and keeps your place in the course. Mathematics I is free to start.
More questions on Vectorised Computation and Libraries
- Monte Carlo error falls like 1/√(N) regardless of the dimension, which is why it wins in high dimensions.
- A Monte Carlo simulation run twice with different random seeds gives two different answers. Why is that a…
- An interpreted loop processes 2 million elements per second while the vectorised version processes 500…
- Complete the reason vectorised code is faster.
- Monte Carlo error falls like 1/√N. To gain one more decimal digit of accuracy, what does that cost?