When using NDSolve
, I often have parameters that, in most of their domain, have a constant or null variation, but that suffer from abrupt variations on a very small interval.
Mathematica variable step algorithm is unable to detect these singularities. On the following example, it misses the 15.0 to 15.1 abrupt rise:
variation[x_?NumericQ] := Which[
x < 10, 1,
x < 15, 0,
x < 15.1, 10,
x < 20, 0,
x < 30, 1,
True, 0]
points = {};
ans = accumulation /.
Flatten[NDSolve[{accumulation'[x] == variation[x],
accumulation[0] == 0}, accumulation, {x, 0, 40},
StepMonitor :> AppendTo[points, {x, accumulation[x]}]]];
What I do to guarantee a correct integration, is to define a MaxStepSize
. In the following example MaxStepSize -> 0.01
:
But as you can see, this can cost me a lot of computation time.
Since I know where exactly are the abrupt variations of my parameters, is there another way to guarantee the correct integration, without raising so high the number of steps? Something like listing to Mathematica points in the integration domain that have to be "seen"?
Answer
There is an (undocumented?) feature of NDSolve which is handy for exactly this purpose: You can add more than just the start and end of the integration interval and enforce that these points will be met. The result is like you would run NDSolve on each of the corresponding intervals with the starting conditions given by the end point of the previous interval. This would do what you want for your example:
variation[x_?NumericQ] := Which[
x < 10, 1, x < 15, 0, x < 15.1, 10, x < 20, 0, x < 30, 1, True,0
];
points = {};
ans = accumulation /.
Flatten[NDSolve[{accumulation'[x] == variation[x],
accumulation[0] == 0},
accumulation, {x, 0, 10, 15, 15.1, 20, 30, 40},
StepMonitor :> AppendTo[points, {x, accumulation[x]}]]];
Show[
Plot[ans[x], {x, 0, 40}],
ListPlot[points, PlotStyle -> Red]
]
Comments
Post a Comment