For example, suppose I wanted to define a function, f that is $f(x)=x^2$ except at $x=1$, where $f(x)=5$

Two ways I can define this are



g[x_]:= Piecewise[{{5,x==1}},x^2]

What are the benefits/downsides of one approach vs the other? Or are they the same?

  • 1
    $\begingroup$ You didn't mention using If[] statement or Which[] They are different. The first method uses two patterns. There are several benefits/pitfalls, but that requires much explaining. $\endgroup$
    – Somos
    Nov 12, 2020 at 0:23
  • $\begingroup$ @Somos Sorry for not mentioning. $\endgroup$
    – user106860
    Nov 12, 2020 at 0:59
  • $\begingroup$ Another way: f[x_]:=Which[x==1,5,True,x^2] $\endgroup$ Nov 12, 2020 at 4:19

2 Answers 2


They differ in how they handle the function's derivative.


f1[1] = 5;
f1[x_] := x^2


(* 2 x *)


(* 2 *)

f2[x_] := Piecewise[{{5, x == 1}}, x^2]


(* Piecewise[{{0, x == 1}}, 2*x] *)


(* 0 *)

f3[x_] := Piecewise[{{x^2, x < 1 || x > 1}}, 5]


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


(* Indeterminate *)
  • $\begingroup$ Oof. Thanks. Wouldn't the second technically be better if we cared about derivatives then? $\endgroup$
    – user106860
    Nov 12, 2020 at 0:57
  • 4
    $\begingroup$ I would think that the third is better. $\endgroup$
    – Bob Hanlon
    Nov 12, 2020 at 1:11

When you write

f[1] = 5;
f[x_] := x

you are specifying how expressions will be rewritten during evaluation. f[1] is just a pattern: any expression that matches that pattern will be rewritten as 5. The 'Blank' pattern represents anything else, so:

(* y *)

The possibility that y might take the value 1 at some later stage of the computation isn't taken into account.

One the other hand:

g[x_] := Piecewise[{{5, x == 1}}, x^2]
(* Piecewise[{{5, y == 1}}, y^2] *)

This treats y properly as a variable.

Note that symbolic mathematics in Mathamatica can "reason" about Piecewise expressions, but cannot do so with collections of rewriting rules, so f is not a suitable function to feed to symbolic methods.

  • $\begingroup$ Thanks for the response. Quick clarifying question on one sentence in your answer: you say f[1] is just a pattern, any expression that matches that pattern will be rewritten as 5". Isn't f[1] the only expression that matches that pattern? $\endgroup$
    – user106860
    Nov 12, 2020 at 1:31
  • 1
    $\begingroup$ @user106860 Yes. Of course, it could be a subexpression of some more complicated expression. $\endgroup$
    – John Doty
    Nov 12, 2020 at 1:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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