Precision issue

Alex Martelli aleax at aleax.it
Fri Oct 10 05:54:12 EDT 2003


Ladvánszky Károly wrote:

> Entering 3.4 in Python yields 3.3999999999999999.
> I know it is due to the fact that 3.4 can not be precisely expressed by
> the powers of 2. Can the float handling rules of the underlying layers be
> set from Python so that 3.4 yield 3.4?

It seems, from the question, that you might not have entirely understood
and grasped the explanations you can find at:
http://www.python.org/doc/current/tut/node14.html
and I quote, in particular:
"""
no matter how many base 2 digits you're willing to use, the decimal value
0.1 cannot be represented exactly as a base 2 fraction.
"""
and the same holds for 3.4 for exactly the same reason.  As long as
binary is used -- and today's machines don't offer options -- that's it.

Only by using Decimal or Rational fractional numbers would that be possible,
and today's hardware doesn't really support them, so you would need to do
everything in software.  If you don't mind the resulting huge slowdown in
computation speed (many apps don't really do many computations, so don't
care) there are quite a few packages on the net, though none, AFAIK, which
is considered "ready for production use".  The speediest way to do Rational
arithmetic is, I suspect, with gmpy (the mpq type) -- but "speedy" is in
the eye of the beholder.  Let me give you an example...:

according to timeit.py, after x=3.4 (a native float), int(x*10) takes
2.46 microseconds; but after x=mpq(3.4) [having imported mpq fm gmpy],
int(x*10) takes 9.72 microseconds!  That's FOUR times slower...

Also, mpq(3.4)'s default representation is as a fraction, 17/5; so,
you would still need some formatting work to display it as 3.4 instead.


Alex





More information about the Python-list mailing list