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! $\endgroup$Module[{}, ...]
with empty variable list? As far as I understand, it should not have any effect at all. $\endgroup$