3 ms·
I didn't know of some of these limitations. For example - this decimal one is nasty: >>> from __future__ import division >>> 4 / 5 # normal division
by cturner 17y ago
I didn't know of some of these limitations. For example - this decimal one is nasty:
>>> from __future__ import division
>>> 4 / 5 # normal division
0.80000000000000004 # <-- there is an extra '4' at the end
>>> 4 // 5 # integer division
0
Are any of these things fixed in python 3?
- Erwin 17y agoThat's just how floating point math works in every language. Python intro: http://docs.python.org/tutorial/floatingpoint.html http://docs.python.org/tutorial/floatingpoint.html Comprehensive paper going into depth about many other issues: http://docs.sun.com/source/806-3568/ncg_goldberg.html http://docs.sun.com/source/806-3568/ncg_goldberg.html If you don't understand the above, your missiles may kill you and your rockets may explode: http://www.ima.umn.edu/~arnold/455.f96/disasters.html http://www.ima.umn.edu/~arnold/455.f96/disasters.html However if you don't care about performance but want precision, you can use e.g. the Decimal module (which is a little annoying with syntax help from the compiler) or perhaps various wrappers for arbitrary precision libraries that are around.
- bluetech 17y agoWhat about this: http://docs.python.org/dev/py3k/whatsnew/3.1.html#other-language-changes http://docs.python.org/dev/py3k/whatsnew/3.1.html#other-lang... (the fifth bullet) It seems to make things more reasonable. After all, Python has showed that saying "that just how it works" can be avoided, as in the case of / defaulting to floating-point division.
- Radix 17y agoI'm not a programmer, but IIRC normal division, as shown (4/5), used to do integer division, but now in python 3 it follows the behavior you show. Notice the "from __future__ ..."line implies that the following lines all follow the python 3 behavior, I assume from 2.6.
- timwiseman 17y agoThey aren't really problems. As was pointed out, this is the way floating point works. It trades (decimal) precision for speed. Personally, I do wish that Python would default to a fixed precision decimal style instead of defaulting to floating point. But, you can make Python use the decimal style if you use the Decimal (or similar) library. Also, you can use certain wrappers for Python such as Sage to do something similar. I am a great fan of Sage for certain tasks personally.