1

I've noticed a peculiar result with some while loops that I haven't been able to account for. I've tried varying many different conditions and have found some patterns, but I'll provide just one simple comparison here for reference. I feel pretty confident in my understanding of while loops, but I can't resolve this behavior. Here is an example with 2 different results

Example 1:

t = 0
dt = 0.1
while (t<4):
    t = t + dt
    print(t)

The results from Example 1 end with

...
3.8
3.9
4.0

As I would expect, the while loop is broken once t=4.

However, when I execute the same code with a slightly different conditional (t<5)...

Example 2:

t = 0
dt = 0.1
while (t<5):
    t = t + dt
    print(t)

The last few results from Example 2 are...

...
4.9
5.0
5.1

It would appear that the while loop has acknowledged that t=5, but not broken the loop until t=5.1. This is not consistent with my understanding of the operation of a while loop. I have tried this with and without decimals and I continue to encounter cases where the while loop appears to complete one extra loop.

Could anyone please shed some light on this? I am certainly a novice with programming. Most of my experience is with Python and LaTeX, but I love to learn. And this is driving me crazy!

  • The answer is obvious if one changes `print(t)` to `print(repr(t))`. The value displayed, rounded, as `5.0` is then displayed as `4.999999999999998`. This is less than 5 and does not stop the loop. – Terry Jan Reedy Oct 20 '18 at 18:20

0 Answers0