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 trialA X
12,842 PointsWhy does 0.1 + 0.1 + 0.1 - 0.3 = 5.5...-e17 (really long scientific notation) in Python?
Hi all, Just starting to dip into Python, and I'm really curious to understand what's going on in "Python logic" that when we do a simple seeming math problem that should return 0 (like 0.1 + 0.1 + 0.1 - 0.3 should equal 0) we get scientific notation instead. It seems like there's other times when Python interprets math problems differently from what we'd expect. Why is this?
*Also please explain your answer in simplistic terms please, I'm still a beginner
3 Answers
jcorum
71,830 PointsThis isn't anything to do especially with Python. It occurs in all programming languages. And in math.
In decimal arithmetic if we add 1/4 + 1/4 + 1/4 + 1/4 we get 1.00, exactly. And if we add 1/3 + 1/3 + 1/3 we get 1.00 as the total. If we add 0.25 + 0.25 + 0.25 + 0.25 we also get 1.00. But if we add 0.333 + 0.333 + 0.333 we don't. We get a close approximation: 0.999. And it doesn't matter how many decimal places you go out to (0.3333333, or 0.33333333333333), you'll never get to 1.00. Some decimal fractions are "different", they go on forever.
The same is true in binary arithmetic. Some binary decimal fractions are also "different". Because they are finite representations of repeating decimals, they are approximations, just as 0.333 is an approximation of 1/3.
So, when you add them together, the result may not come out exactly as expected.
sethchristiansen
2,379 PointsThe thought process that the answer should equal zero comes from using the base 10 system. Python uses base 2 (binary). In this case, the number .1 in base 10 cannot be represented precisely in base 2, only approximately.
More can be found about this in the Python documentation: https://docs.python.org/2/tutorial/floatingpoint.html
jcorum
71,830 Pointsnekilof, you are right. They don't in decimal. But at least one of them does in binary.
docgunthrop
12,445 Pointsdocgunthrop
12,445 PointsI get what you're saying, but in the example, 0.1 and 0.3 do not have repeating decimals.