Where is the extra 0.0...5 coming from?

In this Exercise (Tread Shed):

total_sales = 0.00
for x in sales:
  total_sales += float(x)

print(total_sales)

>>>1498.7400000000005

Why is the number such a weird one? In the list “Sales” are no numbers that have more than two decimal places.

python has documentation about it:

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

the short version is that the computer uses binary fractions (base 2), while we humans are used to base 10 fractions

3 Likes

Thanks for your reply!

So if the list in this exercise would be very long we would come up with a “wrong” result for total_sales, right?

Is there an easier way than this to get the correct outcome?:

total_sales_cents = 0

for x in sales:
    x100 = float(x)*100
    total_sales_cents += int(x100)
    
total_sales = float(total_sales_cents)/100

print(total_sales)

>>>1498.71

Or is this even the correct outcome? Why do I get 0.03 less than in the first approach?

edit:
okay, I know it’s wrong, but why?

There’s a really horrible…but interesting, famous programming bug involving this!
The patriot missile system dived by 1/10th as part of its calculations. In binary this is a repeating decimal, not so for base10.
The registers had 24 bits so there was a small amount of error built into the system.

Well…the longer the system ran the bigger the error became.
A system was left on for 100 hours leading to an error of 3/10ths a second

Well a scud missile won’t be where it was three tenths a seconds ago - and that’s what happened. The patriot missed and sadly people died.
Because of float math. Computing is crazy

1 Like

i was looking for a source for this to post it, but couldn’t find it quickly

1 Like

i would just go for the first approach, which is correct, just use floor or round so less digits are displayed

2 Likes

Patriot missile failure

Super short read, very interesting

2 Likes