Tag Archives: scipy

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:


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.