# Function defined through conditional pattern and derivative

If I define a function through a conditional pattern, its derivative is not defined in the whole domain of the original function...

Minimal code to reproduce : for instance, I define

f[x_/;-2<x<2]=x^2


and f'[x] is only defined for -1.5<x<1.5 (it's not exactly 1.5...)

How can this be solved ? I use MMA v13 on Windows 10

• Where is the conditional pattern?
– Syed
Commented Jan 12, 2023 at 15:01
• Something like f[x_] := Piecewise[{{x^2, -2 < x < 2}, {Undefined, True}}] is probably what you're looking for. Commented Jan 12, 2023 at 15:10
• Yeah, sorry i forgot the /; in the definition of my function. Sorry for the typo. Commented Jan 12, 2023 at 15:41
• Defining my function using Piecewise works, that's true. But it runs much more slower than defining using a conditional pattern. Commented Jan 12, 2023 at 15:42
• So what exactly are you using it for? If you want to apply it to large amounts of data, it's much better to just filter the data beforehand for values that are in the domain of f rather than relying on the function to handle the exceptions. Commented Jan 12, 2023 at 15:47

I think this comes closest to what you're looking for:

Clear[f, x, poly]
poly[x_] := x^2;
f[x_ /; -2 < x < 2] = poly[x]
f'[x_ /; -1.5 < x < 1.5] = poly'[x]


Note the use of = instead of := to make sure poly'[x] is computed only once. Also note that x has to be cleared of values for this to work correctly.

You got something wrong. You confuse ":" and "/;". What you wrote is a default value.

Clear["Global*"]
f[x_ : -2 < x < 2] = x^2;


If you now call f without an argument, you will get:

f[]
(* (-2 < x < 2)^2 *)


What you want is a conditional pattern:

Clear["Global*"]
f[x_ /; -2 < x < 2] := x^2;


with this:

f[1.5]
(* 2.25 *)
f[2.5]
(* f[2.5] *)

• I think the problem the OP is pointing out, is that f' does not work when there's a condition on the l.h.s. of the definition. Commented Jan 12, 2023 at 15:48
• Once again, sorry for the typo. My function should read f[x_/;-2<x<2]=x² Commented Jan 12, 2023 at 15:51
• I have edited my first message... Commented Jan 12, 2023 at 15:52