Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


Why does Python produce incorrect floating point math results?

One of the beginner Python lessons showcases this problem


and Python produces the result of


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

This 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.

the 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

Craig Webber
Craig Webber
5,677 Points

computers 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