[Tutor] decimal module and precision

Richard D. Moores rdmoores at gmail.com
Sun Jan 30 22:43:43 CET 2011


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))

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()

print('addition')
x = D('123.2345274523452345235432452345')+D('2.3')
x2 = d(123.2345274523452345235432452345)+d(2.3)
print('x =', x)
print('x2 =', x2)
print()

print('division')
y = D('123.2345274523452345235432452345')/D('2.3')
y2 = d(123.2345274523452345235432452345)/d(2.3)
print('y =', y)
print('y2 =', y2)
print()

print('multiplication')
z = D('123.2345274523452345235432452345')*D('2.3')
z2 = d(123.2345274523452345235432452345)*d(2.3)
print('z =', z)
print('z2 =', z2)
=================================

=============Output================
power
a = 64370.15122802469152726635110412345417588163863981991324
a2 = 64370.15122760993409213289215777394902129746619501742003

addition
x = 125.5345274523452345235432452345
x2 = 125.534527452

division
y = 53.58022932710662370588836749326086956521739130434782609
y2 = 53.58022932695652173913043478260869565217391304347826087

multiplication
z = 283.43941314039403940414946403935
z2 = 283.4394131396
=========end of Output=======================

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

Thanks,

Dick Moores


More information about the Tutor mailing list