[Tutor] decimal precision in python

Steven D'Aprano steve at pearwood.info
Tue Feb 7 14:17:34 CET 2012


Col,

I think you wrote to me personally by accident, instead of to the Tutor list. 
Nothing you said seems to be private, so I've taken the liberty of answering 
back on the list.

col speed wrote:

> Just an idea - I'm not an expert by any means, just a dabbler, but:
> many years ago, when I was looking at options(I assume you mean the
> same as me as in puts etc.)
> they were quoted as fractions.
> Some fractions can't be quoted as exact decimals and some decimals as
> binary, so fractions *may* be more exact.
> I believe there is a fractions module, but it is quite easy to create
> your own Rational class.

Starting in Python 2.6, there is a fractions module in the standard library. 
Unlike float and Decimal, it is effectively infinite precision:

 >>> from fractions import Fraction
 >>> z = 1/Fraction(3)
 >>> z + z + z == 1
True


This comes at a cost, of course. Unless you are very careful, you can end up 
with fractions like this:

Fraction(2573485501354569, 18014398509481984)

That is very close to 1/7, and in fact it is the exact fraction equal to the 
binary float closest to 1/7:

 >>> Fraction.from_float(1/7.0)
Fraction(2573485501354569, 18014398509481984)


So Fraction is not a panacea either. Unless you take care, you can easily end 
up using an unlimited amount of memory for an extremely precise number, when a 
much lower precision would be close enough -- or possibly even BETTER:

 >>> Fraction.from_float(1/7.0).limit_denominator(10)
Fraction(1, 7)


But yes, Fractions are a sadly under-appreciated tool for numeric calculations.


-- 
Steven



More information about the Tutor mailing list