Monday, July 26, 2010

How to prevent integer division errors in Python 2.x

When doing scientific computing, the usual assumption is that all numbers are floating point numbers. In Python 2.x, if two numbers are typed as integers, the result of division is the floor of the result. For example, dividing integer 3 by 4 results in 0 rather than 0.75. It is very easy to let subtle coding errors creep into a program because of this behavior.

>>> 3/4
0
>>> 3./4
0.75

What can make a bug really subtle is if a routine is defined which uses division. Then later a call is made with integers rather than floats.

>>> def testFunction(x,y):
...    return x/y
...
>>> testFunction(3,4)
0
>>> testFunction(3.,4)
0.75

One way to avoid this issue is to guard all divisions in your code with a float conversion. However, this required a lot of diligence to maintain. A potentially easier solution is to import the division definitions from the __future__ module. Once this module is imported, it redefined how the ‘/’ operator behaves and eliminates this potential source of errors.

>>> from __future__ import division
>>> 3/4
0.75

No comments:

Post a Comment