0

Python does not seem to want to return the correct answer on this loop. I believe the code should stop after the evaluation of t=1.8 as the next value of t, 2.0, is equal to b, not less than.

a=0.0
b=2.0
h=0.2
t=a
print "t = ",t
while t<b:
    t+=h;
    print "t = ",t;

The output is

t =  0.0
t =  0.2
t =  0.4
t =  0.6
t =  0.8
t =  1.0
t =  1.2
t =  1.4
t =  1.6
t =  1.8
t =  2.0
t =  2.2

Any help or recognition of an error would be massively appreciated.

  • 3
    Since you are using floating point, you can't rely on the *equality* of two numbers, as there is always some floating point imprecision. [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Eugene Sh. Jan 13 '17 at 21:29
  • Hi @EugeneSh. i just uploaded the output as well. I agree, but this seems to be a quite significant error. Thanks for the link! – MeowBlingBling Jan 13 '17 at 21:31
  • The opposite is true, it is a very *small* error. You can see that eventually `2.0 < 2.0`. And it's because it could be evaluated as `1.9999999 < 2.0` or similar – Eugene Sh. Jan 13 '17 at 21:32
  • You can see this by changing your `print` statement to `print "t = {:.30f}".format(t)` – ThisSuitIsBlackNot Jan 13 '17 at 21:41
  • Very Helpful! Thanks for the insight @ThisSuitIsBlackNot – MeowBlingBling Jan 13 '17 at 21:44

0 Answers0