When modeling systems with WhenEvent
and NDSolve
I found that the default extrapolation settings used in the returned InterpolatingFunction
often cause weird artifacts when plotting the solution. As an example take the following image. It shows the solution of a bouncing ball problem where WhenEvent
is used both to let the ball rebound and to stop integration after five bounces.
The code that generated the image is:
bouncingBall[e_] := Module[{i = 0},
NDSolve[{y''[t] == -9.81, x''[t] == 0, x'[0] == 1, y'[0] == 1, x[0] == 0, y[0] == 1,
WhenEvent[y[t] == 0, {y'[t] -> - e y'[t], i++ , If[i == 5, "StopIntegration"]}]},
{x, y}, {t, 0, 5}]]
ParametricPlot[{x[t], y[t]} /. bouncingBall[0.79] // Evaluate, {t, 0, 5},
PlotRange -> {{0, 3}, {-1, 1.5}}]
From Michael E2' answer I know that the undocumented but well known option "ExtrapolationHandler" -> {Indeterminate &, "WarningMessage" -> False}
solves the issue.
For the sake of demoing code to people not familiar with Mathematica I would like to temporarily override the standard extrapolation settings so that I don't have to explain to the audience what this arcane code snipped does.
I tried using SetOptions
on both NDSolve
and InterpolatingFunction
but in both cases one gets an error message that this is not a known option.
SetOptions[#,"ExtrapolationHandler" -> {Indeterminate &,
"WarningMessage" -> False}] & /@ {NDSolve, InterpolatingFunction}
SetOptions::optnf: "!(\"ExtrapolationHandler\") is not a known option for NDSolve." SetOptions::optnf: "!(\"ExtrapolationHandler\") is not a known option for InterpolatingFunction."