PEP proposal for round(x,n) enhancement

Chris Barker chrishbarker at
Wed Sep 12 19:33:55 CEST 2001

Markus Schaber wrote:
> >(MATLAB had a chop() function that
> > did just this, though it must of been in a toolbox I don't currently
> > have, as I can't find it now)
> But - AFAIK - Matlab can do decimal calculations, while python is stuck
> to the clib's FP (usually IEEE those days) base-2 numbers which cannot

no, it doesn't. MATLAB used native FP as well. It is intended for heavy
numerical work, you simply can't get the performace required for that
without using native FP. 

> exactly represent such numbers. Just try
> >>> 1/5.
> 0.20000000000000001

The only differnce between Python and MATLAB here is that MATLAB doesn't
displya as many digits as Python, so you don't see that 1 on the end.

Besides it doesn't matter. There are a lot of issues with accuarcy with
floating point, but frankly, for scientific programing, the fact that it
is binary, rather than decimal, is a non-issue. Real numbers are
something different than either, whatever base you choose will be an
approximation. A significant-figures-round would actually help a lot.
For example:

x = 0
while x <> 1:
    x += .1

will never terminate, but:

while sig_fig_round(x,10) <> 1:
    x += .1

Would terminate just fine.

On 32 bit machines, a Python float carries enough bits to represent at
least 15 decimal significant figures. Your above example is only wrong
in the 17th digit: that's as good as you should expect a floating point
result to be, even if it was decimal.

The base issue really only causes problems with literals: people type in
1/5. and the expect to get exactly one-fifth. (they don't expect 1/3. to
give them exactly one third however). No one would be applying a sig fig
round to a literal, they would be applying it to the results of
calculations, and fp calculations are rarely accurate to the last digit

> Maybe we should think about fixed and floating point decimal numbers
> (using string or bcd internal representation) for inclusion in Python.
> Of course, this leads to complex decimals and even rationals composed
> of complex decimals, too :-)

Look at the PEPs, there are various versions of this in progress.


Christopher Barker,
ChrisHBarker at                 ---           ---           --- ---@@       -----@@       -----@@
                                   ------@@@     ------@@@     ------@@@
Oil Spill Modeling                ------   @    ------   @   ------   @
Water Resources Engineering       -------      ---------     --------    
Coastal and Fluvial Hydrodynamics --------------------------------------

More information about the Python-list mailing list