f[x_] := x /; x<0
f[x_] := x^2 /; x>=0
Integrate[f[x],{x,-1,1}]
The above does not work (Mathematica returns it unevaluated), but the below does.
g[x_] = Piecewise[{ {x,x<0}, {x^2,x>=0}}]
Integrate[g[x],{x,-1,1}]
Why? More importantly, I've written a lot of code using the /;
form:
is there any way I can make it work and/or automagically convert it to
Piecewise form without having to rewrite my code?
In real life, I'm doing something like
Integrate[Cos[n x] f[x], {x, -1, 1}]
for arbitrary n, and want a symbolic result, so NIntegrate won't solve my problem.
NIntegrate[f[x], {x, -1, 1}]
will work and can be used with eitherRationalize
orRootApproximant
to return-1/6
. $\endgroup$/;
a programming construct, whilePiecewise
is meant for representing a mathematical concept.Piecewise
was designed with symbolic manipulation in mind./;
is for controlling evaluation. These are two entirely different uses, and many constructs have two versions in Mathematica for this reason. Some others don't and the line between 'math' and 'programming' can be blurry (e.g. I'd also considerIf
a programming construct but it does work inIntegrate
) ... which can cause problems and confusion. $\endgroup$