2
$\begingroup$

I was wondering if anyone can explain the difference between the /; operator and Piecewise []. In what situation one should prefer one rather than the other? How the function associated with each of the defined conditions can be accessed?

$\endgroup$

1 Answer 1

3
$\begingroup$

Rather than ask general questions, I recommend that you experiment with these questions on your own. When you then encounter a problem that you cannot resolve, ask a specific question about that specific issue.

Clear["Global`*"]

f1[x_ /; x <= 1] := x^2;

f1[x_ /; x > 1] := x^3;

f2[x_] = Piecewise[{{x^2, x <= 1}, {x^3, x > 1}}];

The plots of the functions are the same

Plot[{f1[x], f2[x]}, {x, -2, 2},
 PlotStyle -> {Automatic, Dashed}]

enter image description here

However, the derivatives and exact integrals behave much differently.

f1'[x]

(* Derivative[1][f1][x] *)

f2'[x]

(* Piecewise[{{2*x, x < 1}, {3*x^2, x > 1}}, Indeterminate] *)

Integrate[f1[x], {x, -2, 2}]

(* Integrate[f1[x], {x, -2, 2}] *)

Integrate[f2[x], {x, -2, 2}]

(* 27/4 *)

Numerical integration is the same

NIntegrate[f1[x], {x, -2, 2}]

(* 6.75 *)

NIntegrate[f2[x], {x, -2, 2}]

(* 6.75 *)
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.