4
$\begingroup$

I have noticed a weird behavior of the "Derivative" operator, and I would like to know to why is this happening and if it is intended, as I'm using this function quite a bit in my code and I would like for it to work. Here is a code snippet that reproduces de problem :

f1[λ_, v_] := f2[λ, vectrans[v]]
f2[λ_, v_] :=λ (v[[1]] + v[[2]])
vectrans[v_] := ( {
    {0, 2},
    {2, 0}
   } ) . v
f1[λ, {a, b}]
Derivative[1, 0][f1][λ, {a, b}]
D[f1[λ, {a, b}], λ]

Now if you look at the output of this code, I coded the function f1 to get a scalar and a vector as input, and spit out $λ(2a+2b)$, if the inputs are $λ$ and $v=\{a,b\}$. Then, in the first attempt I use the operator Derivative[1,0] to do the partial derivative w.r.t. $\lambda$, but I get the following output with mathematica 13 :

{{{a, b}, {2 + a, 2 + b}}, {{2 + a, 2 + b}, {a, b}}}

Which honestly I have no idea how it comes about.

If we use instead the operator D, we get the expect result $2a+2b$.

Why is that ?

$\endgroup$
3
  • 2
    $\begingroup$ Derivative, in effect, differentiates f1[\[Lambda], x] and then replaces x by {a, b}. D differentiates the result of f1[\[Lambda], {a, b}]. $\endgroup$
    – Michael E2
    Jun 14, 2022 at 15:36
  • $\begingroup$ I see. I will try to include conditions on the parameters of f1 to see if it changes anything. $\endgroup$
    – Frotaur
    Jun 14, 2022 at 15:37
  • $\begingroup$ Indeed, adding a ListQ to the v parameter just prevents Derivative from computing the derivative altogether, as f1 just doesn't evaluate... Apparently using "Derivative[1,{0,0}]" works, as it then knows that the second parameter is a vector. $\endgroup$
    – Frotaur
    Jun 14, 2022 at 15:40

1 Answer 1

7
$\begingroup$

So the problem as pointed in the comments was that Derivative will assume all parameters of the function to be differentiated are scalars, in other words it differentiates f[λ,x] and then replaces x by {a,b}, which gives the unexpected result.

One way around this, while still using Derivative is as follows :

Derivative[1,{0,0}][f1][λ,{a,b}]

This was indeed written in the Documentation, but I had missed it :

Derivative[{n1,n2,…}][f] represents the derivative of f[{x1,x2,…}] taken $n_i$ times with respect to $x_i$. In general, arguments given in lists in f can be handled by using a corresponding list structure in Derivative.

$\endgroup$

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.