Velocity Reviews > Vectorization and Numeric (Newbie)

Vectorization and Numeric (Newbie)

Ronny Mandal
Guest
Posts: n/a

 02-28-2006
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

--

Support bacteria - it's the only culture some people have!

Juho Schultz
Guest
Posts: n/a

 02-28-2006
Ronny Mandal wrote:
> 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

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

johnzenger@gmail.com
Guest
Posts: n/a

 02-28-2006
"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:

>>> [f(x) for x in numbers]

[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]