Vectorization and Numeric (Newbie)

Juho Schultz juho.schultz at helsinki.fi
Tue Feb 28 08:38:16 EST 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 
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))



More information about the Python-list mailing list