Alternative to Decimal type

Nick Craig-Wood nick at craig-wood.com
Thu Jun 12 04:01:49 CEST 2008


Frank Millman <frank at chagford.com> wrote:
>  Thanks to all for the various replies. They have all helped me to
>  refine my ideas on the subject. These are my latest thoughts.
> 
>  Firstly, the Decimal type exists, it clearly works well, it is written
>  by people much cleverer than me, so I would need a good reason not to
>  use it. Speed could be a good reason, provided I am sure that any
>  alternative is 100% accurate for my purposes.
> 
>  My approach is based on expressing a decimal number as a combination
>  of an integer and a scale, where scale means the number of digits to
>  the right of the decimal point.
> 
>  Therefore 0.04 is integer 4 with scale 2, 1.1 is integer 11 with scale
>  1, -123.456 is integer -123456 with scale 3. I am pretty sure that any
>  decimal number can be accurately represented in this form.
> 
>  All arithmetic is carried out using integer arithmetic, so although
>  there may be rounding differences, there will not be the spurious
>  differences thrown up by trying to use floats for decimal
>  arithmetic.

I used an identical scheme in a product some time ago (written in C
not python).  It was useful because it modelled the problem domain
exactly.

You might want to investigate the rational class in gmpy which might
satisfy your requirement for exact arithmetic :-

    >>> import gmpy
    >>> gmpy.mpq(123,1000)
    mpq(123,1000)
    >>> a = gmpy.mpq(123,1000)
    >>> b = gmpy.mpq(12,100)
    >>> a+b
    mpq(243,1000)
    >>> a*b
    mpq(369,25000)
    >>> a/b
    mpq(41,40)
    >>>

It is also *very* fast being written in C.

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list