# Inefficient NIntegrate and Which

In version 10 a simple numerical integraton of piecewise function is highly inefficient:

f[x_] := Which[-1 <= x <= 0, x, 0 <= x, x^2, True, 0]
ϕ[x_] := NIntegrate[f[t], {t, -1, x}] whereas in the version 5 it was much faster: How can I speed up the plotting (what options in Plot or in NIntegrate)?

@Micheal E2

partially you were right - there is difference in a number of points, however not so large like the diference in timing  The Plot command was used to see difference in timing, however, for the same number of points older version is still better:  • How many points are plotted in each version? – Michael E2 Feb 9 '15 at 11:34

NIntegrate[f[t], {t, -1, x}] integrates the same thing over and over again, when a point is needed by Plot.

Integrate what you need one time only:

f[x_] = Which[-1 <= x <= 0, x, 0 <= x, x^2, True, 0];
ϕ[x_] = NDSolve[{Derivative[g][t] == f[t], g[-1] == 0},
g, {t, -1.5, 1}][[1, 1, 2]][x];
Plot[ϕ[x], {x, -1.5, 1}]

• thanks for the answer, but I was just interested in the NIntegrate efficiency, maybe, I did not say it clearly. – sebqas Feb 10 '15 at 11:09

I agree NDSolve is the way to go, but I think I know why there has been a slow down since V5.

I believe sometime since V5 symbolic preprocessing was introduced, which can cause overhead. We can turn this off in V10 and see a drastic speed up:

f[x_] := Which[-1 <= x <= 0, x, 0 <= x, x^2, True, 0]
ϕ[x_] := NIntegrate[f[t], {t, -1, x}]

Plot[ϕ[x], {x, -1.5, 1}] // AbsoluteTiming ψ[x_] := NIntegrate[f[t], {t, -1, x}, Method -> {Automatic, "SymbolicProcessing" -> False}]

Plot[ψ[x], {x, -1.5, 1}] // Quiet // AbsoluteTiming # Edit

I have verified that this is the reason for the slowdown. My copy of V5 does not know about the "SymbolicProcessing" submethod: • +1. I don't know when the symbolicprocessing option was introduced but its in v9 (same results). – george2079 Feb 10 '15 at 22:45
• +1, thanks, that is what I asked! I suspected that Math is doing something other than pure numerics. – sebqas Feb 11 '15 at 8:35
• @george2079 it looks like it was introduced in version 6. It appears in the v6 legacy documentation for NIntegrate: reference.wolfram.com/legacy/v6/ref/NIntegrate.html. – Chip Hurst Feb 11 '15 at 15:46
f[x_] = Piecewise[{
{x, -1 <= x <= 0},
{x^2, x > 0}}];

\[Phi][x_] = Assuming[Element[x, Reals],
Integrate[f[t], {t, -1, x}]] Plot[\[Phi][x], {x, -1.5, 1}] // Timing 