Monday, April 26, 2010

Weekly Python module: NumPy

NumPy is basically module that provides really fast implementation of tables you may know form MATLAB. Yes, normally Pythons lists are just enough, but when performance matters NumPy comes to help You.

One note. I was reluctant to say only about NumPy, because it is almost always used together with other modules (at least one for presenting data as graphs). But then I can split those modules to separate posts so I have them more ;) So if you need NumPy stay tuned as I will make more posts about it (probably one for Matplotlib and one for SciPy).


Main NumPy advantages are:

  • fast tables
  • data must be the same type in table but it can be enything
  • vast range of data
  • Fortan and C support (no need for copying tables!!)
  • per element operations
  • mathematic functions
NumPy is really fast and many things are C-speed. Read this benchmark on your own risk ;D
Requirement for one type of data across table my sound odd but is tolerable. you gain speed and you can use any Python or NumPy data type including, tuples :D so if you need e.g. string + real number, just put them in tupe and than into NumPy table.
Next on the list is variety of types, I'll just direct You to docs.
If your calculations are something more than just 'y=sin(x)', you know C or Fortan librarys. Great news is that you can easily integrate them in NumPy. NumPy can also align your data in tables to mimic Fortan layout, so no extra calculations are needed.
The most exciting part of NumPy just see code below:
a + b*c

If it would be plain Python, you would expect b to be multiplied by c and then added to a. And a,b,c would be normal varibles.
In NumPy effect will be the same, but a,b,c may be whole tables and NumPy it self will do the necessary work to multiply element i of table b by element i of table c, and will do the same then for adding. You got cleaner code that behave as you would expect and it is much faster (no need for extra loop that would be interpreted by python).

Last thing I've pointed is set of math functions. But they are just to keep backward compatibility with old Numeric, precursor of NumPy. And if 'SciPy' installed NumPy will automagiclly use it.

No comments:

Post a Comment