round function error???

Mark Dickinson dickinsm at gmail.com
Sun Jul 20 16:56:26 CEST 2008


On Jul 19, 12:20 am, John Machin <sjmac... at lexicon.net> wrote:
> On Jul 19, 8:05 am, Mark Dickinson <dicki... at gmail.com> wrote:
> > for more information.  But I'm guessing that you're
> > questioning the fact that a value that's apparently
> > *less* than 3499.35 is rounded up to 3499.4, rather
> > than down to 3499.3.  ?
>
> "apparently" being the operative word.

Well, it's not just an apparent problem:  the closest
floating-point number to 3499.35 really *is* less than
3499.35.  A nice way to check this is using the new
fractions module in 2.6, which allows exact conversions
of floats and Decimals into rational numbers:

Python 2.6b2+ (trunk:65155, Jul 20 2008, 15:39:46)
[GCC 4.0.1 (Apple Inc. build 5484)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from decimal import Decimal
>>> from fractions import Fraction
>>> x = 3499.35
>>> y = Decimal('3499.35')
>>> Fraction.from_float(x)
Fraction(7695152029315891, 2199023255552)
>>> Fraction.from_decimal(y)
Fraction(69987, 20)
[54933 refs]
>>> Fraction.from_float(x) < Fraction.from_decimal(y)
True

Mark



More information about the Python-list mailing list