Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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}]
share|improve this question
add comment

2 Answers 2

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.

share|improve this answer
    
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. –  user11311 Dec 24 '13 at 16:32
    
I'm using Mma v9.0.1 on Win. –  belisarius Dec 24 '13 at 16:36
    
@user11311 The third example works for me (Mma 9.0.1, Mac OS X 10.8.5). –  Michael E2 Dec 24 '13 at 16:47
    
Thanks! Then it is an issue with 9.0.0.0. –  user11311 Dec 24 '13 at 16:52
add comment

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}];
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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