[Python-Dev] Adventures with Decimal

Facundo Batista facundobatista at gmail.com
Thu May 19 15:53:54 CEST 2005


On 5/18/05, Raymond Hettinger <python at rcn.com> wrote:


> >>> from decimal import getcontext
> >>> context = getcontext()
> >>> x = context.create_decimal('3.104')
> >>> y = context.create_decimal('2.104')
> >>> z = context.create_decimal('0.000')
> >>> context.prec = 3
> >>> x + y
> Decimal("5.21")
> >>> x + z + y
> Decimal("5.20")

My point here is to always remind everybody that Decimal solves the
problem with binary floating point, but not with representation
issues. If you don't have enough precision (for example to represent
one third), you'll get misterious results.

That's why, IMO, the Spec provides two traps, one for Rounded, and one
for Inexact, to be aware of what exactly is happening.


> As for why the normal Decimal constructor is context free, PEP 327
> indicates discussion on the subject, but who made the decision and why
> is not clear.

There was not decision. Originally the context didn't get applied in
creation time. And then, the situation arised where it would be nice
to be able to apply it in creation time (for situations when it would
be costly to not do it), so a method in the context was born.

.    Facundo

Blog: http://www.taniquetil.com.ar/plog/
PyAr: http://www.python.org/ar/


More information about the Python-Dev mailing list