round(22.47,2) gives 22.469999999999999?

  • Thread starter Eric van Riet Paap
  • Start date
E

Eric van Riet Paap

Hi,

On python2.1.3, python2.2.1 and python2.2.3 round(22.47,2) gives
22.469999999999999 . Does anyone know if this is a bug or some weird, yet
unexpected, behaviour?

P.S. I haven't tested python2.3, but python1.5.2 doesn't have this problem.
 
T

Thomas Andrews

Eric said:
Hi,

On python2.1.3, python2.2.1 and python2.2.3 round(22.47,2) gives
22.469999999999999 . Does anyone know if this is a bug or some weird, yet
unexpected, behaviour?

P.S. I haven't tested python2.3, but python1.5.2 doesn't have this problem.

In IDLE, just typing:
22.469999999999999

That seems to indicate that 22.47 is best approximated by the floating
number 22.499999999999.

Rounding should probably not be used for gettting "formatable" values.
Instead, you can do something like:
'22.47'

if you want a string version of the number rounded to 2 decimal places.

=thomas
 
J

John Machin

Daniel Klein said:
Wouldn't

int(22.47 + .5)

get you to where you want to go?

Sure would, if 22 was where you wanted to go. One trusts that you
would be lonely on arrival, though. Perhaps you might then notice a
bunch of folks over at 22.47 ...
 
H

Helmut Jarausch

Eric said:
Hi,

On python2.1.3, python2.2.1 and python2.2.3 round(22.47,2) gives
22.469999999999999 . Does anyone know if this is a bug or some weird, yet
unexpected, behaviour?

You're asking too much. There simply is no number 22.47 representable in
binary arithmetic with a finite number of bits. Remember most current
CPUs use binary and not decimal arithmetic.
So 22.469999999999999 is the best you can get and it doesn't make sense
to print a rounded number with many more digits after the decimal point.

If you printed

print '%6.2f' % 22.47

you got '22.47'
so this limited precision (nearly 16 decimal digits)
doesn't hurt.
You still could write a fix-point class which internally
store the value multiplied by 10**d with a given 'd'.
You'd have to overload the standard math operators (and perhaps
functions) and especially the '__str__' method.



--
Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
 
J

John Machin

Bernhard Herzog said:
Even if he would want to round to an int, using int(x + 0.5) would fail
for negative values:

-2.0


Bernhard

"Fail" depends on your/his definition of "round to an int" -- up?
down? towards zero? away from zero? closest in either direction [ties
broken how?]?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,083
Messages
2,570,591
Members
47,212
Latest member
RobynWiley

Latest Threads

Top