0

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)?

2
  • 3
    Your example does not fit the title. You are not filling an array, you are summing a function over a simple range of values. In numpy you 'vectorize' by expressing the problem in terms of functions that use fast compiled code. Commented Jan 31, 2015 at 18:17
  • @hpaulj thanks for pointing that out (+1). My (incorrect) assumption was that I can fill a numpy array by doing something like this: narray = np.array(f, range). I'll leave the title as-is for anyone who stumbles on this with the same assumptions. Commented Jan 31, 2015 at 18:57

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Much better explanation than the answer in the link I gave. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.