- Why are floating point calculations so inaccurate in Python?
- How do you stop a floating arithmetic error in Python?
- What is floating point error in Python?
- How do I get rid of floating point errors?
- Why am I getting strange results with simple arithmetic operations?
- --
- Why are floating-point calculations so inaccurate?
- ==================================================
- Users are often surprised by results like this:
- >>> 1.2 - 1.0
- 0.19999999999999996
- and think it is a bug in Python. It's not. This has little to do
- with Python, and much more to do with how the underlying platform
- handles floating-point numbers.
- The "float" type in CPython uses a C "double" for storage. A "float"
- object's value is stored in binary floating-point with a fixed
- precision (typically 53 bits) and Python uses C operations, which in
- turn rely on the hardware implementation in the processor, to perform
- floating-point operations. This means that as far as floating-point
- operations are concerned, Python behaves like many popular languages
- including C and Java.
- Many numbers that can be written easily in decimal notation cannot be
- expressed exactly in binary floating-point. For example, after:
- >>> x = 1.2
- the value stored for "x" is a (very good) approximation to the decimal
- value "1.2", but is not exactly equal to it. On a typical machine,
- the actual stored value is:
- 1.0011001100110011001100110011001100110011001100110011 (binary)
- which is exactly:
- 1.1999999999999999555910790149937383830547332763671875 (decimal)
- The typical precision of 53 bits provides Python floats with 15--16
- decimal digits of accuracy.
- For a fuller explanation, please see the floating point arithmetic
- chapter in the Python tutorial.
- Are Python floats are broken? 3 solutions in python for beginner
- https://www.youtube.com/watch?v=9-Cpi3hGjrY
- Why Are Floating Point Calculations So Inaccurate in Python?
- https://www.youtube.com/watch?v=oNhSbvG24jQ
- [inline]
Python software and documentation are licensed under the PSF License Agreement.
Starting with Python 3.8.6, examples, recipes, and other code in the documentation are dual licensed under the PSF License Agreement and the Zero-Clause BSD license.
Some software incorporated into Python is under different licenses. The licenses are listed with code falling under that license. See Licenses and Acknowledgements for Incorporated Software for an incomplete list of these licenses.
Python and it's documentation is:
Copyright © 2001-2022 Python Software Foundation. All rights reserved.
Copyright © 2000 BeOpen.com. All rights reserved.
Copyright © 1995-2000 Corporation for National Research Initiatives. All rights reserved.
Copyright © 1991-1995 Stichting Mathematisch Centrum. All rights reserved.
See History and License for complete license and permissions information:
https://docs.python.org/3/license.html#psf-license