1
$\begingroup$

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

Thanks in advance.

$\endgroup$
6
  • $\begingroup$ Where is the conditional pattern? $\endgroup$
    – Syed
    Commented Jan 12, 2023 at 15:01
  • 1
    $\begingroup$ Something like f[x_] := Piecewise[{{x^2, -2 < x < 2}, {Undefined, True}}] is probably what you're looking for. $\endgroup$ Commented Jan 12, 2023 at 15:10
  • $\begingroup$ Yeah, sorry i forgot the /; in the definition of my function. Sorry for the typo. $\endgroup$
    – coussin
    Commented Jan 12, 2023 at 15:41
  • $\begingroup$ Defining my function using Piecewise works, that's true. But it runs much more slower than defining using a conditional pattern. $\endgroup$
    – coussin
    Commented Jan 12, 2023 at 15:42
  • $\begingroup$ 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. $\endgroup$ Commented Jan 12, 2023 at 15:47

2 Answers 2

2
$\begingroup$

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.

$\endgroup$
0
$\begingroup$

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] *)
$\endgroup$
3
  • 2
    $\begingroup$ 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. $\endgroup$ Commented Jan 12, 2023 at 15:48
  • $\begingroup$ Once again, sorry for the typo. My function should read f[x_/;-2<x<2]=x² $\endgroup$
    – coussin
    Commented Jan 12, 2023 at 15:51
  • $\begingroup$ I have edited my first message... $\endgroup$
    – coussin
    Commented Jan 12, 2023 at 15:52

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.