# Benefits/pitfalls of defining function that is discontinuous at a point "explicitly" vs using piecewise?

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

f=5;
f[x_]:=x


or

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


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

• 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. Nov 12, 2020 at 0:23
• @Somos Sorry for not mentioning. Nov 12, 2020 at 0:59
• Another way: f[x_]:=Which[x==1,5,True,x^2] Nov 12, 2020 at 4:19

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

Clear["Global*"]

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

f1'[x]

(* 2 x *)

f1'

(* 2 *)

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

f2'[x]

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

f2'

(* 0 *)

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

f3'[x]

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

f3'

(* Indeterminate *)

• Oof. Thanks. Wouldn't the second technically be better if we cared about derivatives then? Nov 12, 2020 at 0:57
• I would think that the third is better. Nov 12, 2020 at 1:11

When you write

f = 5;
f[x_] := x


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

f[y]
(* 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]
g[y]
(* 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.

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