-
-
Notifications
You must be signed in to change notification settings - Fork 30k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Weird add operation of "0.2222 + 0.1111" #86086
Comments
If I add 0.2222 + 0.1111 in the python cli I get the value 0.33330000000000004 and not 0.3333. Also the other way around. >>> 0.22+0.11
0.33
>>> 0.222+0.111
0.333
>>> 0.22222+0.11111
0.33333
>>> 0.3333+0.7777
1.111
>>> 0.3333+0.6666
0.9999
>>> 0.3333+0.3333
0.6666
>>> 0.6666+0.1111
0.7777
>>> 0.2222+0.3333
0.5555 Python 3.8.5 I also tested that in a newly setup VM, same issue |
Same problem with 0.3333-0.1111 python returns 0.22219999999999998 and not 0.2222 |
Please forgive me if my answer is a little bit brusque, but we get essentially this same bug report regularly, only the numbers are different. This is not a bug in Python, it is an unavoidable consequence of how floating point arithmetic works in every single programming language that does floating point arithmetic. There's a FAQ about it: it's discussed in the tutorial: https://docs.python.org/3/tutorial/floatingpoint.html#tut-fp-issues there's probably a million websites, blog posts, Stackoverflow questions etc about it, and computer scientists write papers about it: https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html |
Some further resources: https://stackoverflow.com/questions/8215437/floating-point-accuracy-in-python https://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate https://randomascii.wordpress.com/category/floating-point/page/1/ If you google a bit you will find many other places that discuss this. |
Ok thank you for these resources. I didn't know that before. (; |
But this "bug" only affects floating numbers? |
Hi Leonard, Any number which has only fixed precision will experience similar In Python, float, complex and Decimal have fixed precision, so they can But for simple calculations, Decimal may be better for you, as it uses
But with Decimal, you have other numbers which are rounded off and so
ints are always exact, but you can only do whole numbers with ints.
Using Fraction is a good way to see what number a binary float really
|
Hi Steven, |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: