# Problems with WhenEvent

Any help/explanations will be highly appreciated:

This works:

sol = NDSolve[{x''[t] + x[t] == Sin[t], x[0] == 0, x'[0] == 1,
WhenEvent[Abs[t x[t]] > 1, {x'[t] -> -x'[t]}]},
x, {t, 0, 8}][[1]];

xt = x /. sol;

Plot[xt[t], {t, 0, 8}];


This does not:

TT = t;

sol = NDSolve[{x''[t] + x[t] == Sin[t], x[0] == 0, x'[0] == 1,
WhenEvent[Abs[TT x[t]] > 1, {x'[t] -> -x'[t]}]},
x, {t, 0, 8}][[1]];

xt = x /. sol;

Plot[xt[t], {t, 0, 8}]


This crashes the Kernel:

sol = NDSolve[{x''[t] + x[t] == Sin[t], x[0] == 0, x'[0] == 1,
WhenEvent[(Abs[x[t]] > 1) && (x[t] > 5), {x'[t] -> -x'[t]}]},
x, {t, 0, 8}][[1]];

xt = x /. sol;

Plot[xt[t], {t, 0, 8}]


## 2 Answers

Your second example doesn't work because the t in TT = t; is another t, outside the scope of the DSolve[].

Your third example doesn't kill the kernel here :

sol = NDSolve[{x''[t] + x[t] == Sin[t], x[0] == 0, x'[0] == 1,
WhenEvent[(Abs[x[t]] > 1) && (x[t] > 5), {x'[t] -> -x'[t]}]},
x, {t, 0, 8}][[1]];

xt = x /. sol;

Plot[xt[t], {t, 0, 8}]


but the WhenEvent[] clause isn't working. I guess that what is happening is that the first part of the ÀND clause rises an "exception" each time it occurs and then the second part is checked, but it's false.
So, simply reversing the AND clauses works:

sol = NDSolve[{x''[t] + x[t] == Sin[t], x[0] == 0, x'[0] == 1,
WhenEvent[(x[t] > 1.5) && (Abs[x[t]] > 1), {x'[t] -> -x'[t]}]},
x, {t, 0, 8}][[1]];

xt = x /. sol;

Plot[xt[t], {t, 0, 8}]


Please note that I've changed the x[t] value where the event is met only to make the effect more visible.

• Thank you for your comments. The third example still crashes the kernel. I am using Mathematica 9 on a Mac running OS X 10.9, maybe it is just the version. Commented Dec 24, 2013 at 16:32
• I'm using Mma v9.0.1 on Win. Commented Dec 24, 2013 at 16:36
• @user11311 The third example works for me (Mma 9.0.1, Mac OS X 10.8.5). Commented Dec 24, 2013 at 16:47
• Thanks! Then it is an issue with 9.0.0.0. Commented Dec 24, 2013 at 16:52

Indeed, it was a scope issue. I solved the second example, this works:

TT[t_] := t;
sol = NDSolve[{x''[t] + x[t] == Sin[t], x[0] == 0, x'[0] == 1,
WhenEvent[Abs[TT[t] x[t]] > 1, {x'[t] -> -x'[t]}]},
x, {t, 0, 8}][[1]];
xt = x /. sol;
Plot[xt[t], {t, 0, 8}];