[Python-numerics]Re: [Python-Dev] Re: WYSIWYG decimal fractions

Tim Peters tim.one@home.com
Thu, 15 Mar 2001 22:16:12 -0500


[M.-A. Lemburg]
> Just out of curiosity: is there a usable decimal type implementation
> somewhere on the net which we could beat on ?

ftp://ftp.python.org/pub/python/
    contrib-09-Dec-1999/DataStructures/FixedPoint.py

It's more than two years old, and regularly mentioned on c.l.py.  From the
tail end of the module docstring:

"""
The following Python operators and functions accept FixedPoints in the
expected ways:

    binary + - * / % divmod
        with auto-coercion of other types to FixedPoint.
        + - % divmod  of FixedPoints are always exact.
        * / of FixedPoints may lose information to rounding, in
            which case the result is the infinitely precise answer
            rounded to the result's precision.
        divmod(x, y) returns (q, r) where q is a long equal to
            floor(x/y) as if x/y were computed to infinite precision,
            and r is a FixedPoint equal to x - q * y; no information
            is lost.  Note that q has the sign of y, and abs(r) < abs(y).
    unary -
    == != < > <= >=  cmp
    min  max
    float  int  long    (int and long truncate)
    abs
    str  repr
    hash
    use as dict keys
    use as boolean (e.g. "if some_FixedPoint:" -- true iff not zero)
"""

> I for one would be very interested in having a decimal type
> around (with fixed precision and scale),

FixedPoint is unbounded "to the left" of the point but maintains a fixed and
user-settable number of (decimal) digits "after the point".  You can easily
subclass it to complain about overflow, or whatever other damn-fool thing you
think is needed <wink>.

> since databases rely on these a lot and I would like to assure
> that passing database data through Python doesn't cause any data
> loss due to rounding issues.

Define your ideal API and maybe I can implement it someday.  My employer also
has use for this.  FixedPoint.py is better suited to computation than I/O,
though, since it uses Python longs internally, and conversion between
BCD-like formats and Python longs is expensive.

> If there aren't any such implementations yet, the site that Tim
> mentioned  looks like a good starting point for heading into this
> direction... e.g. for mx.Decimal ;-)
>
> 	http://www2.hursley.ibm.com/decimal/

FYI, note that Cowlishaw is moving away from REXX's "string of ASCII digits"
representation toward a variant of BCD encoding.