[Python-Dev] Adventures with Decimal

Michael Chermside mcherm at mcherm.com
Fri May 20 19:34:32 CEST 2005


Tim Peters writes:
> Other important
> implementations of the standard didn't make this mistake; for example,
> Java's BigDecimal|(java.lang.String) constructor follows the rules
> here:
           [...]
> Hmm -- or maybe it doesn't!  The text says:
           [...]


Here is the actual behavior:

  Jython 2.1 on java1.5.0_03 (JIT: null)
  Type "copyright", "credits" or "license" for more information.
  >>> import java.math.BigDecimal as BigDecimal
  >>> import java.math.MathContext as MathContext
  >>> BigDecimal("0.33333333333333333333333333333333333")
  0.33333333333333333333333333333333333
  >>> BigDecimal("0.33333333333333333333333333333333333", MathContext.DECIMAL32)
  0.3333333
  >>>

In other words, Java's behavior is much closer to the current behavior
of Python, at least in terms of features that are user-visible. The
default behavior in Java is to have infinite precision unless a context
is supplied that says otherwise. So the constructor that takes a string
converts it faithfully, while the constructor that takes a context
obeys the context.

One could argue that they are "following the rules" appropriately and it
just happens that their default context has infinite precision. But from
the point of view of the typical, non-floating-point-aware user, Java's
constructor gives "all the digits you told it to", and so does Python's
current string constructor. Using "+decimal.Decimal(s)" today "rounds off
the constant" (in the nieve user's viewpoint).

Of course, the user is going to be surprised in the NEXT step since the
Python *operations* respect context while the Java ones use infinite
precision for +, -, and * (and require you to specify the behavior for /).

(PS: No, I don't think we should design decimal.Decimal to match the
behavior of Java... but I don't think that the Java example really helps
make your point.)

Elsewhere, Tim writes:
> Sorry, I can't make more time for this now.

I understand!

> The short course is that
> a module purporting to implement an external standard should not
> deviate from that standard without very good reasons

Yes, but should we think of the constructor-from-string as an
implementation-specific means of creating Decimal objects, which is
separate from string-to-Decimal converter that the standard requires
(and which is provided by the Context objects)?

-- Michael Chermside



More information about the Python-Dev mailing list