# Integrating a Simple Piecewise Function

If I define

f[x_]:=If[x<0,-1,1]


and then integrate,say

Integrate[f[x],{x,-3,7}]


I get what I expect, namely 4.

But if I do the same thing with a different function

f[x_] := If[x < -1, 1/(2x^2), If[x > 1, 1/(2x^2), 0]]


and if I then integrate

Integrate[f[x], {x, -3, 7}]


I do not, as expected, get 16/21; instead I just get an expression consisting of an integral sign with -3 and 7 at the limits, followed by the definition of f just as I typed it above (with all the If statements, etc) and then a dx.

I can of course break the integral into two parts, either of which Mathematica handles perfectly well. But how do I get it to evaluate this expression without my manual intervention?

-
Instead of using If, construct the function using Piecewise. – Szabolcs Mar 5 '14 at 1:52
Using Piecewise is better, but an alternative is Integrate[PiecewiseExpand@f[x], {x, -3, 7}], which converts the function to Piecewise. – Michael E2 Mar 5 '14 at 1:58
@Szabolcs: I hadn't known about Piecewise, and apparently the very old version of Mathematica that I use (4.1.0.0) doesn't know about it either. Of course I shouldn't expect that others will tailor their answers to my ancient software, so I do thank you for the suggestion, though it doesn't seem to work for me. – WillO Mar 5 '14 at 3:09

In Mathematica 9.0 the second integral evaluates to 16/21...

-
Thanks for this info. Maybe it's time to upgrade. – WillO Mar 5 '14 at 6:54

You can use Piecewise to define your piecewise functions. For example your second example could be defined as follows:

f[x_] := Piecewise[{{1/(2 x^2), Abs[x] > 1}, {0, True}}]


Integration:

Integrate[f[x], {x, -3, 7}]


yields 16/21

-