Reputation: 17241
Normally, the summation of a function would be done like this in python
fsum = 0
for k in range(1, N+1):
fsum += f(k)
Where f
is some function.
The whole point of using numpy
is to vectorize everything. In this case, the loop is going to be slow for very large N
. How do I go about using numpy
to fill a numpy array
using a function f
(that may take multiple arguments)?
Upvotes: 0
Views: 862
Reputation: 1379
First I've expanded your code to the minimum required to actually execute it, including choose a specific f(k):
import numpy as np
def f(k):
return(np.log(k**2))
N=8
fsum = 0
for k in range(1, N+1):
fsum += f(k)
print fsum
Which gives and answer of 21.209. Now let's do the same thing but vectorized. Note the function f(k) is the same.
import numpy as np
def f(k):
return(np.log(k**2))
N=8
k = np.array(range(1, N+1))
print np.sum(f(k))
And this gives the same answer. The key difference is that I have defined a numpy array to contain the inputs you iterate over in your for loop. That is:
k = np.array(range(1, N+1))
Which, if you want to be even more efficient, can be simplified to:
k = np.arange(1, N+1)
Since f(k) was already written to use numpy math functions it was already vectorized. Then instead of using a loop containing a += operation, I instead used the numpy.sum vectorized function on f(k):
print np.sum(f(k))
As you can see the result is more concise, and for large arrays it will be significantly faster too.
Upvotes: 4