While it is a bad idea to compare floating point numbers, in this case I think something simpler is going on: you have an off-by-1 problem in your loop. See what your code does:
test[t_, dt_] := Module[{},
For[ti = dt, ti <= t, ti = ti + dt, Print[ti];];
Print[MemberQ[{0.01, 0.02}, ti]];
Return[0];
]
then, after
test[0.01, .001];
look at ti:
ti
(*0.011*)
If you use < rather than <= in the condition, the final value will indeed be
what you expect it to be:
test2[t_, dt_] := Module[{},
For[ti = dt, ti < t, ti = ti + dt, Print[ti];];
Print[MemberQ[{0.01, 0.02}, ti]];
Return[0];
]
test2[0.01, .001]
ti
prints a list up to 0.009 and returns True.
In general, though, don't do things like that with floating-point numbers. Even if it works here, it will eventually fail. Observe:
(1 + $MaxMachineNumber) == $MaxMachineNumber
(*True*)
or, as JM points out,
1 + $MachineEpsilon == 1
(*True*)
For[]loop, really. Try0.008 + 0.001 // InputForm. Welcome to the fun of floating-point arithmetic! – J. M.'s missing motivation May 15 '12 at 12:41Module[{}, ...]with empty variable list? As far as I understand, it should not have any effect at all. – celtschk May 16 '12 at 13:22faqtag. I've typically been using it only when there are a minimum of eight duplicates. This question presently has only two. Maybe you can find others that should be marked as duplicates? (Possibly questions that have been deleted that should have been marked duplicate instead?) – Mr.Wizard Aug 04 '15 at 08:38