Floating Point Limitations

27,780

Solution 1

I think it reflects more on your understanding of floating point types than on Python. See my article about floating point numbers (.NET-based, but still relevant) for the reasons behind this "inaccuracy". If you need to keep the exact decimal representation, you should use the decimal module.

Solution 2

This is not a drawback of python, rather, it is a drawback of the way floating point numbers are stored on a computer. Regardless of implementation language, you will find similar problems.

You say that you want to 'display' A as a floating point, why not just display the string? Visually it will be identical to what you expect.

As Jon mentioned, if your needs are more than just 'displaying' the floating point number, you should use the decimal module to store the exact representation.

Solution 3

Excellent answers explaining reasons. I just wish to add a possible practical solution from the standard library:

>>> from decimal import Decimal
>>> a = Decimal('2.3')
>>> print a
2.3

This is actually a (very) F.A.Q. for Python and you can read the answer here.


Edit: I just noticed that John Skeet already mentioned this. Oh well...
Share:
27,780
user46646
Author by

user46646

Updated on August 05, 2022

Comments

  • user46646
    user46646 over 1 year

    My code:

    a = '2.3'
    

    I wanted to display a as a floating point value.

    Since a is a string, I tried:

    float(a)
    

    The result I got was :

    2.2999999999999998
    

    I want a solution for this problem. Please, kindly help me.

    I was following this tutorial.

  • user46646
    user46646 almost 15 years
    decimal returns a string.I want a float type only.
  • Jason Coco
    Jason Coco almost 15 years
    @rejinacm - float types are not exact, your paper actually explains this at the end and explains why this happens.
  • Jon Skeet
    Jon Skeet almost 15 years
    Decimal doesn't "return" a string - you can convert it to a string, but a decimal value is just a value, which you can manipulate separately etc. If you really need float for whatever reason, you need to accept that you're not going to be able to represent 2.3 exactly in it.
  • Jon Skeet
    Jon Skeet almost 15 years
    @rejinacm: How about you read the page that I linked to? It gives lots of examples, including division.
  • jason
    jason almost 15 years
    In addition to Jon's article, I also recommend reading What Every Computer Scientist Should Know About Floating-Point Arithmetic. A copy is available on docs.sun.com/source/806-3568/ncg_goldberg.html.
  • Mr_and_Mrs_D
    Mr_and_Mrs_D almost 2 years
    Not sure how is the link related?