How to guarantee that NDSolve correctly detects abrupt changes in parameters?

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"?

-
Are the locations of the discontinuities in your actual function known or unknown? – J. M. Jan 21 '12 at 16:35
"Since I know where exactly are the brusk variations ..." – P. Fonseca Jan 21 '12 at 16:40
Just break up your integration interval at the discontinuities, and apply NDSolve[] to each interval. Use Piecewise[] to assemble your final function. If you don't know where the discontinuities are, you will want to look at Method -> "EventLocator". – J. M. Jan 21 '12 at 17:12

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


-
I don't think I've seen that before. +1 – Mr.Wizard Jan 23 '12 at 14:12