0

I'm trying to create a script to output a increasing and decreasing number. The script is this:

n = 0
r = 30
a = "ratios_forward["
s = "]: "
while r > 0:
    print(a,n,s,r)
    n = n + 1
    r = r - 0.1
    round(r, 1)

But my output looks like this.

ratios_forward[ 0 ]:  30
ratios_forward[ 1 ]:  29.9
ratios_forward[ 2 ]:  29.799999999999997
ratios_forward[ 3 ]:  29.699999999999996
ratios_forward[ 4 ]:  29.599999999999994
ratios_forward[ 5 ]:  29.499999999999993
ratios_forward[ 6 ]:  29.39999999999999
ratios_forward[ 7 ]:  29.29999999999999
ratios_forward[ 8 ]:  29.19999999999999
ratios_forward[ 9 ]:  29.099999999999987
ratios_forward[ 10 ]:  28.999999999999986
ratios_forward[ 11 ]:  28.899999999999984
ratios_forward[ 12 ]:  28.799999999999983

The same kind of output happens for 300 total lines. I tried to round it, which makes no difference. The first two lines make sense, but the next 298 seem to subtract a very small amount more than intended.

I've got Python 3.8.10. What am I doing wrong?

EDIT: I've tried the same kind of subtraction but with only 1 variable. No change.

i = 30
while i > 0:
    print(i)
    i = i - 0.1
  • 2
    Welcome to the floating point arithmetic imprecision. – davidbuzatto Jul 13 '21 at 17:36
  • Incidentally, you're rounding an expression, but you aren't storing it anywhere. `round(r, 1)` returns a rounded value, but you aren't storing it. Also, the way floating point numbers, as @davidbuzatto mentions, is not exact. It's probably easier to print the number out using formatting, like `print(f"ratios forward[{n}]: {r:.1f}")` – Ben Y Jul 13 '21 at 17:40
  • I suppose this idea is more complicated than I thought! Thank you! – AGreatUsernameChoice Jul 13 '21 at 17:40

0 Answers0