How can I simplify this integral?
Integrate[Piecewise[{{c[x], 0 <= x <= 1/2}, {0, True}}], {x, 0, 1}]
I think it should be the same as
Integrate[c[x], {x, 0, 1/2}]
Thanks
I can't think of an easy way to just Simplify
a Piecewise
integral. But here's something that might achieve what you're looking for (in a hopefully more general setting).
Define a "piecewise integral" function:
pIntegrate[p_, {var_, min_, max_}] :=
Module[{funranges =
SortBy[{#[[1]], Sort@Cases[#[[2]], _?NumberQ]} & /@ p[var][[1]], Mean[#[[2]]] &]},
(* Turn "x < a" into "-Infinity < x < a" *)
If[Length[funranges[[1, 2]]] == 1, funranges[[1, 2]] = {-Infinity, funranges[[1, 2, 1]]}];
If[Length[funranges[[-1, 2]]] == 1, funranges[[-1, 2]] = {funranges[[-1, 2, 1]], Infinity}];
(* Only want the pieces of the function that are defined between the
limits of integration *)
funranges = Select[funranges, Or @@ IntervalMemberQ[Interval[{min, max}], #[[2]]] &];
funranges[[;; , 2]] = Sort[Join[{min, max}, #[[2]]], Less][[{2, 3}]] & /@ funranges;
(* Integrate the pieces and return their sum *)
Total[Integrate[#[[1]], Flatten[{var, #[[2]]}]] & /@ funranges]
]
Then applying it to your example:
f[x_] := Piecewise[{{c[x], 0 <= x <= 1/2}, {0, True}}]
pIntegrate[f, {x, 0, 1}]
But it can also do more complicated things. Suppose f
has many pieces, which overhang the limits of integration in odd ways (and that the pieces aren't even presented in the right order):
f[x_] := Piecewise[{{a[x], 0 <= x < 1/2}, {c[x], x >= 1}, {b[x], 1/2 <= x < 1},
{d[x], x < 0}, {0, True}}]
pIntegrate[f, {x, -5, 0.75}]
(Sadly, the output is reordered according to Mathematica's whim -- function names? -- and not according to the integration limits of the pieces. But I think there's little that can be done about that.)
I'm sure there must be a cleaner, more concise way of doing this. Also, it would be nice to be able to set the options for Integrate
through pIntegrate
. But it works, and perhaps it will inspire someone to do it improve on it.
Internal`FromPiecewise[]
.
$\endgroup$
Commented
Aug 17, 2017 at 2:30
Reverse@Transpose[f[x][[1]]]
(but includes the default case). I suspect my way would fall apart fairly quickly for two or more variables.
$\endgroup$
Commented
Aug 17, 2017 at 2:39