-1

I was trying to take advantage of the Broadcasting property of Python while replacing the for loop of this snippet:

import numpy as np
B = np.random.randn(10,1)
k = 25
for i in range(len(B)):
  B[i][0]= B[i][0] + k

with this:

for i in range((lenB)):
  B=B+k

I observed that I was getting different results. When I tried outside the loop, B = B+k, gave the same results as what I was expecting with B[i][0] = B[i][0] + k

Why is this so? Does Broadcasting follow different rules inside loops?

Ambareesh
  • 324
  • 1
  • 4
  • 18

1 Answers1

0

In your 2nd option you ment to do the following:

B=B+k

As you see, you don't need the for loop and it is MUCH faster than looping over the "vector" (numpy array).

It is some form of "Vectorization" calculation instead of iterative calculation which is better in terms of complexity and readability. Both will yield the same result.

You can see a lot of examples on Vectorization vs Iteration, including running time, here.

And you can see a great video of Andrew Ng going over numpy broadcasting property.

Eran Moshe
  • 3,062
  • 2
  • 22
  • 41