1
$\begingroup$

I need to solve a differential equation numerically wherein two "events" must trigger independently and one of the WhenEvent[] "actions" changes it's own "event" condition. Here is a simplified example:

solution =
   NDSolve[{x'[t] + x[t] == 1, x[0] == 0, ttemp[0] == 0.002,
    WhenEvent[t == ttemp[t],
     {
      ttemp[t] ->(*t*)ttemp[t] + 0.002 (*changes the condition to be checked*)
      }
     ], 
    WhenEvent[Mod[t, 0.05], Print[t]](*works independently*)
    },
   {x, ttemp}, {t, 0, 10}, DiscreteVariables -> {ttemp}];

Suddenly I see that message was not printed at t=2.1, t=9.65, t=9.7, t=9.9 and, maybe, some other instants!

If I remove first WhenEvent[], it works properly:

solution =
   NDSolve[{x'[t] + x[t] == 1, x[0] == 0, ttemp[0] == 0.002,
    WhenEvent[Mod[t, 0.05], Print[t]]
    },
   {x, ttemp}, {t, 0, 10}, DiscreteVariables -> {ttemp}];

Moreover, the second "event" condition reformulation helps (but it's unacceptable for me):

solution =
   NDSolve[{x'[t] + x[t] == 1, x[0] == 0, ttemp[0] == 0.002,
    WhenEvent[
     Mod[t, 0.002], {ttemp[t] ->(*t*)
       ttemp[t] + 0.002} ],
    WhenEvent[
     Mod[t, 0.05], Print[t]]
    },
   {x, ttemp}, {t, 0, 10}, DiscreteVariables -> {ttemp}];

So, the problem doesn't seem to occur because the events are close enough since they are close every time when second event triggers. Problem instants are repeatable and do not change from one execution to another. Common workarounds (e.g. to Evaluate the condition, vary "DetectionMethod", etc) do not work here as far as I explored. Does anyone have any ideas?

$\endgroup$
0

1 Answer 1

4
$\begingroup$

Increasing WorkingPrecision solves the issue. Adding N@ to t prevents overly long prints. Rationalizing the constants is usually a good idea, but not doing so will give a warning now.

NDSolve[{x'[t] + x[t] == 1, x[0] == 0, ttemp[0] == 2/1000, 
   WhenEvent[t == ttemp[t], {ttemp[t] -> ttemp[t] + 2/1000}], 
   WhenEvent[Mod[t, 1/20], Print[N@t]]}, {x, ttemp}, {t, 0, 10}, 
  DiscreteVariables -> {ttemp}, WorkingPrecision -> 10];
$\endgroup$

Your Answer

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

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