Decimal can be Binary Too (was decimal or rational)

Tim Peters tim.one at home.com
Fri Jun 1 21:30:40 EDT 2001


[Don O'Donnell]
> ...
> If by "floating-point-decimal" you mean internal representation of
> both the mantissa and the exponent by some sort of a binary-coded
> decimal, let me point out that it is not necessary to go to full
> decimal in order to to achieve the `7.35` == "7.35" goal.>
> By letting the exponent represent powers of 10 rather than 2, the
> base (or mantissa) and exponent can both be represented in binary
> as an int or long.  Thus, the internal calculations can use the
> fast integer hardware instructions, rather than decimal arithmetic
> which would have to be done by software.
> ...

See

<ftp://ftp.python.org/pub/python/contrib-09-Dec-1999/DataStructures/FixedPoi
nt.py>

for a fixed-point version of that.  For "typical" commercial use, the
problem is that converting between base-2 (internal) and base-10 (string) is
very expensive relative to the one or two arithmetic operations typically
performed on each input.  For example, hook up to a database with a million
sales records, and report on the sum.  The database probably delivers the
sale amounts as strings, like "25017.18".  Even adding them into the total
*as* strings would be cheaper than converting them to a binary format first.

In addition, once you're outside the range of a native platform integer,
you're doing multiprecision operations by hand anyway.  Python's longs use
"digits" in base 2**15 internally, but *could* use, say, base 10**4 instead.
The code would be almost the same, except for using different low-level
tricks to find twodigits/base and twodigits%base efficiently.





More information about the Python-list mailing list