Although there are similar posts here Negative integral of a positive function , Positive integrand giving negative answer ,
my case is even more surprising. I have a very simple function
Clear[y]
y[q_, w_] := Module[{res},
res = If[w > q (2 - q), 0, w];
If[w > Abs[q (2 - q)] && w < q (2 + q), res = 1 - 1/4 (q - w/q)^2];
If[w < 0, res = 0];
res
]
It looks like this
g1 = Plot[y[0.25, w], {w, 0, 4}, PlotRange -> All]
Numerical and analytical integrals are equal
Integrate[y[0.25, w], {w, 0, 4}]
NIntegrate[y[0.25, w], {w, 0, 4}]
(*0.0957031*)
Now let us shift the function
g2 = Plot[y[0.25, w-2], {w, 0, 4}, PlotRange -> All]
and integrate again in the same limits
Integrate[y[0.25, w - 2], {w, 0, 4}]
NIntegrate[y[0.25, w - 2], {w, 0, 4}]
(*-1.9043*)
The result is now negative and not equal to the previous value! What's up?
In this particular case i am not so much interested in the origin of such peculiar result, but rather in the practical prescription on how to deal with it.






0.0957031is also wrong. Redefine your function asClear[y];y[q_?NumericQ, w_?NumericQ] := ...and run bothNIntegrate[y[0.25, w], {w, 0, 4}]andNIntegrate[y[0.25, w - 2], {w, 0, 4}]. – march Jun 04 '16 at 20:04wandw-2cases by forcing the arguments to be numeric, the question is why does that work? – Jack LaVigne Jun 05 '16 at 00:50y[a,b]. It's strange to be using a module for this. Less strange, but more troublesome, is usingIfinstead ofPiecewise. – John Doty Jun 05 '16 at 02:16Integrateis not going to work correctly, becauseydoesn't evaluate correctly symbolically, andIntegratemanipulates symbolic expressions.NIntegrateis also failing probably because it does symbolic pre-processing before it does the numerical integration, and so the function doesn't evaluate correctly as an integrand. – march Jun 05 '16 at 05:35