Fixed-point [was Re: Rational Numbers]

Nick Maclaren nmm1 at cus.cam.ac.uk
Sun Jan 14 08:21:39 EST 2007


In article <mailman.2705.1168750931.32031.python-list at python.org>,
"Hendrik van Rooyen" <mail at microcorp.co.za> writes:
|> 
|> Ok I will throw in a skewed ball at this point - use integer arithmetic,
|> and work in tenths of cents or pennies or whatever, and don't be too 
|> lazy to do your own print formatting...

If anyone is interested in doing this, here are a few notes on some of
the non-trivial aspects.  Please feel free if you want to contact me
for more information.

All numbers are held as (precision, value).  Precision is the number of
digits after the decimal point (a small, often constant, integer) and
the value is held as an integer.

It would be possible to have a separate subclass or context for every
precision (like Decimal), but that would be an unnecessary complication.

+, - and % return a precision that is the maximum of their input
precisions, and // returns a precision of 0.

* returns a precision that is the sum of its input precisions.

/ returns a floating-point number!

There is a divide function that takes a divisor, dividend and output
precision.  It also takes a rounding rule as an optional argument
(up, down, in, out, conventional nearest or IEEE 754R nearest).

There is a precision conversion function that takes a value and
output precision, and a rounding rule as an optional argument.

There is a conversion function that takes a string or floating-point
number and output precision, and a rounding rule as an optional
argument.  It raises an exception if a 1 ULP change in the floating-
point number would give a different answer; this is needed to make
certain operations reliable.

The default formatting does the obvious thing :-)

Er, that's about it ....


Regards,
Nick Maclaren.



More information about the Python-list mailing list