

The pure Python solution is the following:įor i in xrange ( 1 ,nx - 1 ) : for j in xrange ( 1, ny - 1 ) : The code finds a two-dimensional function, u, where ∇ 2 u = 0, given some fixed boundary conditions. This example solves Laplace's equation over a 2-d rectangular grid using a simple iterative method. Recently I re-did the same example that Prabhu Ramachandran first created several years ago which is reported here. Even though I feel quite comfortable in C, my appreciation for Cython has been growing over the past few years, and I know am an avid supporter of the Cython community and like to help it whenever I can. Cython has been gaining a lot of momentum in recent years as people who have never learned C, can use Cython to get C-speeds exactly where they want them starting from working Python code. Cython translates Python-looking code into "not-for-human-eyes" C-code that compiles to reasonably fast C-code. The compiled code is then cached on-disk and made available for immediate later use if it is called again.Ĭython is an extension-module generator for Python that allows you to write Python-looking code (Python syntax with type declarations) that is then pre-compiled to an extension module for later dynamic linking into the Python run-time. The code is compiled and linked at run-time the very first time the code is executed.

Weave is a sub-package of SciPy and allows you to inline arbitrary C or C++ code into an extension module that is dynamically loaded into Python and executed in-line with the rest of your Python code. For those parts of the application, there are two general approaches that work really well to get you back to compiled speeds: weave or Cython. It is also sometimes just easier to express the calculation with a simple loop. With NumPy's rich slicing and broadcasting capabilities, as well as its full suite of vectorized calculation routines, I can quite often do the number crunching I am trying to do with very little effort.Įven with NumPy's fast vectorized calculations, however, there are still times when either the vectorization is too complex, or it uses too much memory. In those cases, I first reach for NumPy which provides high-level expressions of fast low-level calculations over large arrays. No matter how fast computers get, there will always be cases where you still need the code to be as fast as you can get it. It is not rare, however, to need to do many calculations over a lot of data. Others express it as "Python fits your brain." My experience resonates with both of these comments.

For example, Robert Kern once told me that "Python gets out of my way" when I asked him why he likes Python. Many programmers report being more productive in Python. The high-level nature of Python makes it very easy to program, read, and reason about code.
