[Tutor] decimal module and precision

Steven D'Aprano steve at pearwood.info
Mon Jan 31 10:32:03 CET 2011


Richard D. Moores wrote:
> Python 3.1
> The decimal module continues to puzzle me from time to time. Here's
> one of those. I want to use Alex Martelli's factory function as much
> as possible. Turns out it has a problem with precision in addition and
> multiplication.
> 
> =========================================
> from decimal import Decimal as D
> import decimal
> 
> #Alex Martelli's factory function from 'Python in a Nutshell', 2nd ed., p.373
> def d(x):
>     return decimal.Decimal(str(x))


I don't have the second edition of the book, only the first. Are you 
sure that Alex Martelli calls this a *factory* function? It doesn't look 
like a factory to me.

> decimal.getcontext().prec = 55
> 
> print('power')
> a = D('123.2345274523452345235432452345')**D('2.3')
> a2 = d(123.2345274523452345235432452345)**d(2.3)
> print('a =', a)
> print('a2 =', a2)
> print()

And here is your problem:

 >>> str(123.2345274523452345235432452345)
'123.234527452'

Consequently:

 >>> D(str(123.2345274523452345235432452345))
Decimal('123.234527452')


> Why in the world does precision not work for addition and
> multiplication (see x2 and z2)?

It does. You are misinterpreting the error. The problem is not with the 
addition, but with the construction *before* the addition.


By the way, if you are using Python 2.7 or 3.1, you should consider 
using the Decimal.from_float method.



-- 
Steven



More information about the Tutor mailing list