Thread Shed - Tasks 14 & 15 - incorrect result

I am currently working through the Thread Shed exercises.

Task 14 asks me to

Now, consider the list sales . It is a list of strings that we want to sum. In order for us to sum these values, we will have to remove the $ , and set them equal to floats.

Iterate through sales and for each item, strip off the $ , set it equal to a float, and add it to total_sales

and Task 15 asks me to print it.

My initial ‘sales’ list looks like this:

My code is

total_sales = 0
for sale in sales:
  total_sales += float(sale.strip("$"))

print(total_sales)

This prints 1498.7400000000005.

I have two questions:

  1. Why is this happening? All of the numbers in the sales list stop at two decimal places, so a digit in the thirteenth ought to be impossible.
  2. How can it be fixed? I’ve searched through the previous questions on this exercise, and the closest answer I found was a link to Format Specification Mini-Language. That tells me how to ensure that my result is rounded to the second decimal place, but not how to actually fix the error.

Thank you very much.

Hello!

It should be, but the way floats work is that you sometimes get this. It has something to do with the way floats are stored. A “low-tech” solution would be to convert it into a string, and then snip off all of the digits past the 4 to the right of the decimal. This article is a long read, but I think it explains rounding errors nicely.

I hope this helps!

2 Likes

Thank you.

I started reading the article, but I think getting a basic understanding of it is going to have to wait until after the kids are in bed: that kind of math was sufficiently long ago for me that dividing my focus is not going to work!

I did laugh when I saw the title of the article: when I was writing my post, I’d initially considered referring to the mid-90s brouhaha over the Pentium FDIV bug to explain why this was bothering me so much. Apparently that actually wouldn’t have been irrelevant.

I’m not sure if this conveys my question clearly, but does the fact that this sometimes happens with floats have larger implications about how Python works or how I should approach working with numbers within it?

2 Likes

As far as I know, all languages deal with floats in the same way-you just need to be careful about how you use numbers-try not to use floats, if you can help it. In C# there are doubles-which are decimals, and I think more accurate. I’m not sure about Python, though.

1 Like

Thank you very much.

1 Like

For this exercise all the values are stored as strings so rounding can be done by .format()

'${:.2f}'.format(%float%)

(or similar with f-string).

1 Like