Friday, October 11, 2013

IEEE 754/854, when it is needed

Linkedin

There was a post on linkedin IEEE Computer Society group, lamenting the division by zero exception raised by Python, instead of returning infinity (or -infinity). I replied, but it is not that readable. So I'm putting the properly formatted reply on my blog. [edit: no comments followed on linkedin, but many appeared on the original source after that]

IEEE decimal

If you want IEEE 754/854 decimal behaviour, what you want to use is the decimal module:

>>> import decimal
>>> help(decimal)

The above typed in the python interpreter will provide all the help you need. The examples are a little verbose, however.


ExtendedContext


If you want to be shorthand, you can copy/paste the following at the top of your program:

from decimal import setcontext,ExtendedContext, Decimal as ieee
setcontext(ExtendedContext)


Then whenever you want to use ieee behaviour use ieee(value):

>>> 1/ieee(0)
Infinity
>>> -1/ieee(0)
-Infinity

Python does it right



It is good that it has to be explicitly stated that you want this. A division by zero should raise an exception when dealing with financial data[*]. I would recommend numpy if dealing with scientific data.


François
@f_dion

* Unless you are calculating my bonus...

2 comments:

Brandon Rhodes said...

Could you provide a link to the mailing list discussion, so that we can see the criticism of Python that you are responding to? Thanks!

Francois Dion said...

Good point, I updated the first paragraph to include the link to linkedin (not sure if the group allows public view of articles and answers) and the external source.