I'd like to implement an operator f
that commutes with differentiation D
.
Unprotect[D];
D[f[y___], x] := f[D[y, x]];
Protect[D];
D[f[Sin[x]], x]
D[f[Sin[x]] + 1, x]
Unfortunately this code produces two different results
f[Cos[x]] (* as expected *)
Cos[x] f´[Sin[x]] (* cannot explain *)
I'd like to know, what's going on, and how to fix the replacement rule such that the second expression evaluates to f[Cos[x]]
as well.
Update. Solution 1 The following solution seems to do the job of redefining the D
operator (although I'm nowhere near understanding completely my own code).
PartialDerivative[x_, x_] := 1;
PartialDerivative[c_, x_] := 0 /; FreeQ[c, x];
PartialDerivative[f_ConditionalExpectation, x_] :=
ConditionalExpectation[PartialDerivative[f, x]];
PartialDerivative[(f_)[g__], x_] := Module[{i, n, p},
n = Length[SequenceHold[g]];
Sum[
p = ConstantArray[0, n]; p[[i]] = 1;
((Derivative[##1][f] & ) @@ p)[g]*
PartialDerivative[SequenceHold[g][[i]], x], {i, 1, n}]];
I would appreciate if someone more experienced could take a look at the code and tell me whether this approach is alright.