4 ms·
Python's print method is actually fairly clever picking the "nicest" representation that's still correct. https://docs.python.org/2/tutorial/floatingpoint.html
by teh 11y ago
Python's print method is actually fairly clever picking the "nicest" representation that's still correct.
https://docs.python.org/2/tutorial/floatingpoint.html#tut-fp-issues https://docs.python.org/2/tutorial/floatingpoint.html#tut-fp...
Quote:
"In current versions, Python displays a value based on the shortest decimal fraction that rounds correctly back to the true binary value, resulting simply in ‘0.1’."
- mkesper 11y agoAdditionally, for exact calculations you might want to use the decimal module. https://docs.python.org/3.5/library/decimal.html#module-decimal https://docs.python.org/3.5/library/decimal.html#module-deci...
- Spidler 11y agoBut be wary so you don't pass in floats when creating your decimals In [10]: from decimal import Decimal In [11]: Decimal(0.1) + Decimal(0.2) - Decimal(0.3) Out[11]: Decimal('2.775557561565156540423631668E-17') In [12]: Decimal("0.1") + Decimal("0.2") - Decimal("0.3") Out[12]: Decimal('0.0')
- fulafel 11y agoTry the usual decimally-unrepresentable numbers (like 1/3).
- mkesper 11y agoAs illumen pointed out, Python has also got fractions. For things like Pi however, there is no exact numerical representation and you'd probably want sympy or something similar.
- fulafel 11y agoSure. But the inability to represent 1/3 in decimal is just the same as inability to represent 1/10 in binary. The binary case just seems different because we are using a foreign base (decimal) literal "0.1" to express the binary number.
- scrollaway 11y agoThis doesn't seem true for me (Python 3.5.0 (default, Sep 20 2015, 11:28:25) [GCC 5.2.0] on linux). >>> print(.1 + .2) 0.30000000000000004
- deleted 11y ago[deleted]