I'm solving a non-linear system with NDSolve. See my previous post

In the WhenEvent, which one is better for ODE solving

Mod[ϕ[t], 1] == 0


Sin[2 π*ϕ[t]] > 0

I thought the first one would be easier for the system to detect the event, but it does not give the correct answer.

  • $\begingroup$ Your question seems to contain the answer already: one of your two methods doesn't seem to work for you so, assuming that the other one does, which you did not mention, then the second one is obviously better. What are you really asking then? Why the first one does not work? Which one is faster? $\endgroup$
    – MarcoB
    Nov 28, 2023 at 14:13
  • 1
    $\begingroup$ In your first case, you're checking for equality with zero, in the other, simply that you exceed the threshold. One condition is easier to satisfy than the other. $\endgroup$
    – user87932
    Nov 28, 2023 at 21:15

1 Answer 1


Here is a toy example:

NDSolve[{f'[x] == 1, f[0] == 0, 
  WhenEvent[Mod[f[x], 1] == 0, Print[x]]}, f, {x, 0, 4}]


You see, MMA first calculates the next step and only then it checks the WhenEvent. There it starts with x=0 and makes the first step x+dx. Therefore 0. is not printed. Further, after the last step, the WhenEvent is not checked either, so that 4. is not printed.

  • 1
    $\begingroup$ That is a good explanation. But I'm curious on which one is more effecient in WhenEvent, Mod[f[x], 1] == 0 or Sin[2PI*f[x]]>0? $\endgroup$
    – metroidman
    Nov 28, 2023 at 12:19
  • $\begingroup$ My guess is that Mod is more efficient than Sin. $\endgroup$ Nov 28, 2023 at 16:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.