1

I'm trying to inc the var t and when t == 3.14, I want to restart this loop setting t = 0.

The print(t) thing is an attempt to debug my code.

Can someone, please, explain me what's happening here? Thanks!

Here's the code:

import time

t = 0
while 1:
    t += 0.10
    print(t)
    time.sleep(0.5)
    if t == 3.14:
        t = 0

Here's what's happening:

> 0.1
> 
> 0.2
> 
> 0.30000000000000004
> 
> 0.4
> 
> 0.5
> 
> 0.6
> 
> 0.7
> 
> 0.7999999999999999
> 
> 0.8999999999999999
> 
> 0.9999999999999999
> 
> 1.0999999999999999
> 
> 1.2
> 
> 1.3
> 
> 1.4000000000000001
> 
> 1.5000000000000002
> 
> 1.6000000000000003
> 
> 1.7000000000000004
> 
> 1.8000000000000005
> 
> 1.9000000000000006
> 
> 2.0000000000000004
> 
> 2.1000000000000005
> 
> 2.2000000000000006
> 
> 2.3000000000000007
> 
> 2.400000000000001
> 
> 2.500000000000001
> 
> 2.600000000000001
> 
> 2.700000000000001
> 
> 2.800000000000001
> 
> 2.9000000000000012
> 
> 3.0000000000000013
> 
> 3.1000000000000014
> 
> 3.2000000000000015
> 
> 3.3000000000000016
gdlmx
  • 6,479
  • 1
  • 21
  • 39
  • 2
    Never compare floating point numbers like that, they are imprecise – Andrew Li Nov 05 '16 at 02:40
  • Thank you very much for the help! And I'm sorry for the duplicated question. I didn't found anything about it before. – Matheus Martins Jerônimo Nov 05 '16 at 03:21
  • 1
    Also, if you always increment `t` by `0.10`, it will _never_ equal `3.14` --- it will jump from (approximately) `3.10` to `3.20`. Did you mean to type `t += 0.01` instead of `t += 0.10`? – Kevin J. Chase Nov 05 '16 at 04:45
  • @KevinJ.Chase you are right. It was what a wanted, but the error still remain – Matheus Martins Jerônimo Sep 19 '17 at 16:47
  • @MatheusMartinsJerônimo: One of the linked duplicates should solve your problem. (Also, you never mentioned an error message before now. Normally, I would ask you to [edit] your question to provide the new information, but this is almost a year old _and_ closed as a duplicate, so don't bother.) – Kevin J. Chase Sep 19 '17 at 22:36
  • @KevinJ.Chase sorry for the misunderstaning. By error i mean not behaving like i expected. Again, sorry for my bad approch to this problem. – Matheus Martins Jerônimo Sep 19 '17 at 23:48

0 Answers0