I often need to integrate extremely piecewised functions, like the following one (not extreme, but gives an idea):
q[time_?NumericQ] :=
Module[{q1 = 0.7, d1 = 600, p1 = 2700, ph1 = 0, q2 = 0.37, d2 = 870.,
p2 = 5000, ph2 = 0},
If[Mod[time, p1] > ph1 && Mod[time, p1] < ph1 + d1, q1, 0] +
If[Mod[time, p2] > ph2 && Mod[time, p2] < ph2 + d2, q2, 0]]
I know that I can list all the mandatory points in the NIntegrate interval List
. But most of the time I don't know them.
Running NIntegrate
generally returns singularity, accuracy, etc, type of errors.
NIntegrate[q[t], {t, 0, 7*24*3600}]
I can play around with WorkingPrecision
, MaximumRecursion
, etc, but it is not that easy to arrive at something that returns no errors, or that runs in a reasonable time.
I generally end up running something like:
NIntegrateBis[funct_, list_] :=
Module[{step = 0.1, time = list[[1]], int = 0},
While[time < list[[2]], int = int + funct[time]*step;
time = time + step]; int]
NIntegrateBis[q, {0, 10000}]
Simple and with no messages... but no error control, no variable step, etc (it can even overpass the boundaries, although it is easy to correct that part...)
What is the best strategy to integrate my functions? Use NIntegrate
with a specific set of options (that I don't know of)? Build a personal NIntegrate
?
PS - I'm running optimization simulations with those functions, and so, I need it to run pretty fast.
Interpolation
. And they are all joined up at the end. That's why I would prefer a solution on the integration end, not looking at the function itself. $\endgroup$MachinePrecision
) if the points can be found where the pieces change (e.g. use the interpolation grid). Is that possible for your functions? $\endgroup$NIntegrate
could master it with a specific set of options. The simplest numerical method of integration that we first learn is the one I've recreated with my basic functions. Can'tNIntegrate
be degraded to that level? If not, how can I make a real fast basic one? $\endgroup$