Vectorization and Numeric (Newbie)

R

Ronny Mandal

Assume you have a mathematical function, e.g. f(x) = x + 4

To calculate all the values from 1 to n, a loop is one alternative.

But to make this function work with vectors instead i.e
f(x_vector) = result_vector,
how should the function then be implemented?

Thanks

RM
 
J

Juho Schultz

Ronny said:
Assume you have a mathematical function, e.g. f(x) = x + 4

To calculate all the values from 1 to n, a loop is one alternative.

Numeric and friends (numarray,numpy) have something like numarray.arange
- they return arrays similar to the lists returned by standard libs
range function. I would recommend using the built-in array operations as
much as possible - in most cases they are much faster than looping, and
your code remains simpler.
But to make this function work with vectors instead i.e
f(x_vector) = result_vector,
how should the function then be implemented?

In most numeric libraries, vectors and scalars can be added etc.
For the simple f(x) case you can use just the simplest approach:

def f(x):
return x+4

and call this with scalar and vector args.
f_pi = f(3.14159265)
f_1to200 = f(numarray.arange(1,200))
 
J

johnzenger

"map" takes a function and a list, applies the function to each item in
a list, and returns the result list. For example:
def f(x): return x + 4
numbers = [4, 8, 15, 16, 23, 42]
map(f, numbers)
[8, 12, 19, 20, 27, 46]

So, rather that ask if there is a different way to write f, I'd just
use f in a different way.

Another way to accomplish the same result is with a list comprehension:
[8, 12, 19, 20, 27, 46]

As you can see, if you wanted to "calculate all the values from 1 to
n," you could also use these techniques instead of a loop.
n = 10
[f(x) for x in xrange(1, n+1)]
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top