Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialcb123
Courses Plus Student 9,858 PointsWhy does Python produce incorrect floating point math results?
One of the beginner Python lessons showcases this problem
0.1+0.1+0.1
and Python produces the result of
0.30000000000000004
Why? And why isn't this fixed in Python after all these years? Seems like so much logic would fail expected from this kind of thing and would require so much handling.
Is this by design to have bad results and how does this make sense?
2 Answers
Per Schrijver
3,435 PointsThis is because of the fact that computers, and therefore also python, use binary. The 0.300...004 is an approximation in binary.
For me trying the same thing does yield the correct answer, so some changes may havd been made through different versions.
Craig Webber
5,677 Pointscomputers are actually not very good at exact maths. If you want to look deeper into why I suggest watching the CS50 videos they are great. https://www.youtube.com/channel/UCcabW7890RKJzL968QWEykA
cb123
Courses Plus Student 9,858 Pointscb123
Courses Plus Student 9,858 Pointsthe workspace Python shell I am using is 3.6.4. Is this the same version you are using? Or are you using something different?
here is another one. .2+.2+.2+.2+.2+.2+.2+.2
and the result is 1.5999999999999999