1
$\begingroup$

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}]
$\endgroup$
0

2 Answers 2

1
$\begingroup$

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}]

Mathematica graphics

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}]

Mathematica graphics

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

$\endgroup$
4
  • $\begingroup$ 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. $\endgroup$
    – user11311
    Commented Dec 24, 2013 at 16:32
  • $\begingroup$ I'm using Mma v9.0.1 on Win. $\endgroup$ Commented Dec 24, 2013 at 16:36
  • $\begingroup$ @user11311 The third example works for me (Mma 9.0.1, Mac OS X 10.8.5). $\endgroup$
    – Michael E2
    Commented Dec 24, 2013 at 16:47
  • $\begingroup$ Thanks! Then it is an issue with 9.0.0.0. $\endgroup$
    – user11311
    Commented Dec 24, 2013 at 16:52
0
$\begingroup$

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}];
$\endgroup$

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.