1

I am implementing a variation of eulers method and my iterations last 1 too long because my while loop returns true for 1.00000 < 1.

t = 0.1;
for N = 1:9
   t = t + 0.1;
end

>> t

t =

    1.0000

>> t < 1

ans =

     1

>> 1 < 1

ans =

     0

I tried converting the 1 to a double but it does not work. (e.g. t < double(1) ). I cannot turn t into an integer because the end of my domain shouldn't be confined to be a integer.

user2316667
  • 5,444
  • 13
  • 49
  • 71
  • 2
    You're encountering the joy that is [floating point arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). You could try something like `abs(t-1) < tol`, where `tol` is some small tolerance value (e.g. something like `1e-6`). – MrAzzaman Oct 11 '14 at 23:22
  • http://matlabgeeks.com/tips-tutorials/floating-point-comparisons-in-matlab/ – Michael Petch Oct 11 '14 at 23:24
  • @MrAzzaman Thanks for the suggestion but it won't work. If my domain is t0 to t1, t1 > t0, and I am at tn, what I do is check `tn < t1`. t1 = 1 but tn = 1.000 (giving me the error). So I tried: `abs(tn - t1) < 0.001` but when tn = 0, I get 1 < 0.0001 which is false and thus I don't get even a single iteration. I'm trying to see how it can be adapted. I don't see it though. The fundamental flaw is I'm checking strictly less than, not proximity. – user2316667 Oct 11 '14 at 23:33
  • Whoops, sorry. For some reason I had it in my head that you were checking that `t==1`. You would instead want something like `t1-tn > tol`. – MrAzzaman Oct 11 '14 at 23:37
  • Ahh, clever. Please post that answer. It worked. – user2316667 Oct 11 '14 at 23:39
  • @user2316667 I suggest you try `format long g` to see what the `1.0000` number really is. I would hope it turns out to indeed be very slightly less than `1` – Dan Oct 11 '14 at 23:41
  • @Dan Yes, it is less than order of 10^-10. [EDITTED] Rather, I mean to say the difference between 1 and t was in that order. So I assigned to1 to be 0.0001 – user2316667 Oct 11 '14 at 23:43
  • This is probably the 20th question I have seen regarding floating point arithmetic with that post being referred to as a duplicate. – rayryeng Oct 12 '14 at 06:34

0 Answers0