Python 3, Thread Shed, Step 14: How did python return a decimal in the ten-trillionths when the inputs only went to the hundredths?

I was working through the Thread Shed project in the Python 3 course and when I added decimals that only ran to the hundredths, the terminal produced a number that went all the way to the ten-trillionths. How could this have happened?

total_sales = 0
for i in sales:
  e = i.strip('$')
  e = float(e)
  total_sales += e
print(total_sales)
#All of the values in sales are dollar amounts
#Result is 1498.7400000000005

It has to do with how floats are stored/interpreted in python.

Look at this article for some ideas to work around this How To Stop Floating Point Arithmetic Errors in Python | by Jonathan Hsu | Code 85 | Medium

And if you want a beefier answer documentation is a great place to go: 15. Floating Point Arithmetic: Issues and Limitations — Python 3.9.1 documentation

Just a little snippet of the docs:

Many users are not aware of the approximation because of the way values are displayed. Python only prints a decimal approximation to the true decimal value of the binary approximation stored by the machine. On most machines, if Python were to print the true decimal value of the binary approximation stored for 0.1, it would have to display

>>> 0.1
0.1000000000000000055511151231257827021181583404541015625

That is more digits than most people find useful, so Python keeps the number of digits manageable by displaying a rounded value instead

>>> 1 / 10
0.1

And for fun here’s a tangentially related scene from Superman 3 (referenced in Office Space): Superman III — Richard Pryor — half cents and Ferrari scenes - YouTube

2 Likes