-1

I noticed in Python that if you use a value and subtract it from a float, it gives you a really long decimal, even though the number is something simple like 0.2. I ran a test, and it then gave me really long decimals like 301212.8000085571. Why does it do that?

Here's an example of code:

dairy = 0

# loop
running = True
while running:
    dairy += 0.2
    print(dairy)
mkrieger1
  • 19,194
  • 5
  • 54
  • 65

2 Answers2

-2

This could likely be due to python's slight inaccuracy of python's floating point calculations in the builtin math computation, causing it to return inaccurate decimal values for very large numbers due to lost digits.

ProPane865
  • 72
  • 1
  • 9
  • 2
    "python's floating point calculations" is misleading. That's a general problem of floating point calculations in all languages. But at least I learned something new: in nearly 2 decades of using Python I never heard the term "lost numbers". However, I don't understand how `0.2 + 0.1` is a "very large number". – Matthias May 02 '20 at 18:07
  • @Matthias This is being added repeatedly, after the numbers are added repeatedly, the sum becomes exceptionally large, causing python to do intermediate rounding while adding these decimals. This does NOT have anything to do with the numbers 0.2 and 0.1 being exceptionally large. – ProPane865 May 02 '20 at 21:14
  • 2
    The size (magnitude) of the numbers is not especially relevant. Look up [catastrophic cancellation](https://en.wikipedia.org/wiki/Loss_of_significance). – Cody Gray - on strike May 02 '20 at 23:20
-2

It is because every time you run through the loop, you are adding up some value to it(0.2) and after adding it up for a long time it gets bigger and bigger just like

0 +0.2+0.2+0.2....... and through the while loop you run it for so many times within seconds which is the reason to get a huge number

  • We're always adding `0.2` here and after some time the result is `301212.8000085571`. The question was not why we have a number like `301212.8`, but where the additional `.0000085571` comes from. – Matthias May 02 '20 at 18:43