-1

couldn't fine answer here. my code:

t = 0
i = 0
arrival = 7.2
while t < 3600:
    time_passed = 0.1
    if t % arrival == 0:
         i+=1
    t+= time_passed
print (i)

===> I get 1 for some reason. can't understand how to fix it (it should be 500) edit: I want to know how to change my code in order to fix the issue, not the theory behind..

Or Levi
  • 3
  • 2

1 Answers1

2

Its because of floating point rounding issues. You can read this post on why it happens.

If you want a quick fix, just use pythons decimal library.

from decimal import Decimal
t = 0
i = 0
arrival = Decimal('7.2')
while t < 3600:
    time_passed = Decimal('0.1')
    if t % arrival == 0:
         i+=1
    t+= time_passed
print (i)
Stevo Mitric
  • 1,570
  • 18
  • 19