Why is 2.3+3.4=5.6999...?


#1

Location:
https://www.codecademy.com/en/courses/learn-python/lessons/conditionals--control-flow/exercises/mix-n-match

Problem:
I enter the following code and bool_four evaluates to False, since not False evaluates to True. It must have something to do with the math expression after the “and”.

Expectations:
Since 2.3 + 3.4 = 5.7 in real life, I expect the expression 2.3 + 3.4 == 5.7 to evaluate to True, but it does not. In the Python Shell on my computer I computed this and similar expressions and the result was:

A Codecademy advisor referred me to this site for an explanation: https://stackoverflow.com/questions/3049101/floating-point-equality-in-python-and-in-general, but I do not understand. Could anyone explain this weirdness?

Code:
bool_four = not False and 2.3 + 3.4 == 5.7

Thanks.


#2

understanding this stays difficult, here at least something which is slightly better to understand:

https://docs.python.org/2/tutorial/floatingpoint.html

the shortest (and then i am cutting a few corners) is that represent base 10 numbers (what we humans use for counting) as base 2 numbers (binary, which computers use) doesn’t always go extremely well

this can have massive consequences, see bug number 3 here:

clocks work by simply adding add numbers from a starting point, its basically the same problem you are experiencing. It can have big consequences, so understanding it is important


#3

So why in the Python Shell exactly do I get 2.3 + 3.4 = 5.69999999999999… and 3.4 + 2.3 = 5.69999999999999… but I don’t get something like 2.3 + 3.3 = 5.59999999999999… or 3.4 + 2.4 = 5.79999999999999…? That is, why does this rounding error occur for some floating point values but not others?


#4

did you read the link i placed:

https://docs.python.org/2/tutorial/floatingpoint.html

certain decimal numbers (base 10) can represented fine in binary (base 2) while others can not


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.