NumPy tip: Turn on error reporting when debugging

It’s been a relatively varied week so far. We got back (and discussed) the referee report for our recent paper on proving homogeneity with a generalised kinematic Sunyaev-Zel’dovich effect, I sent off a couple of comments on a nice draft paper by some collaborators of mine, and we’ve had a busy couple of schools outreach evenings. I’m also now a trained STEM ambassador. But most of my time this week has been sunk into getting a couple of NumPy/SciPy-based codes working properly.

I’ll keep it short and sweet: If you’re writing a numerical code in Python (integrating an ODE, or solving some equation with a root finder, or whatever), you might like to turn on floating point error reporting while you debug. Normally, NumPy has the good grace to suppress floating point errors – who wants to write an error handler for every time you have 0/0 in some plotting code? – but there are plenty of applications where you want to catch NaNs and infs as soon as they happen rather than waiting until the end of the calculation to inspect the result. Yeah, I’m looking at you, scipy.integrate.odeint(). Well, it turns out that NumPy has a nice and easy convenience function to control floating point error reporting: numpy.seterr(). Call it at the very top of your code, like this:

numpy.seterr(all='raise')

That’s all you need. Now, when your code comes across an invalid floating point number, it’ll raise an error ASAP and you can have fun debugging the problem. Don’t forget to remove it when you’ve fixed everything up.

As usual, I can’t believe how long it took me to find this.

About Phil Bull

I'm a theoretical cosmologist, currently working as a NASA NPP fellow at JPL/Caltech in Pasadena, CA. My research focuses on the effects of inhomogeneities on the evolution of the Universe and how we measure it. I'm also keen on stochastic processes, scientific computing, the philosophy of science, and open source stuff. View all posts by Phil Bull

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: