I have a symbol a
appearing in my computations, which has a complicated definition in terms of other variables. However, I know that any derivative of a
has the form
da/dx = a^3 f(x)
for some known function f
, and I would like to teach Mathematica how to do it.
I thought setting up-values would be appropriate, but I just can't get it right. My first attempt was
D[a, x_] ^:= a^3*f[x]
It works if I try D[a, x5]
and gives a^3*f[x5]
, but already D[a^2, x5]
gives 0
. Then I thought it might help to actually define a
as a function, so that Mathematica knows it has to compute derivatives of it too, so I tried
D[a[x1, x2], x_] ^:= a[x1, x2] f[x]
Again, the basic test passed and calling D[a[x1, x2], x1]
gives what I want. However, calling D[a[x1, x2]^2, x1]
gives 2 a[x1,x2]^2 Derivative[1,0][a][x1,x2]]
, I don't fully understand why Mathematica does that and doesn't just use the definition of D
that is already there, but my last hope was to define this as an up-value too. However, setting this as an up-value for a
doesn't work because the nesting is too deep, and the only way is to really set it as an up-value for Derivative
, which already I think is not very good style. I was a bit surprised that Derivative
was not a protected symbol, so I could just write
Derivative /: Derivative[1, 0][a][x1_, x2_] := D[a[x1, x2], x1]
Derivative /: Derivative[0, 1][a][x1_, x2_] := D[a[x1, x2], x2]
This passed the few simple test that I did, but I'm not happy with it. The biggest problem is that I have to specify all the dependencies of a
explicitly and then make an individual definition of Derivative
for each of them. Also the solution above doesn't look very clean, and I'm afraid that there will be some cases which I haven't thought of, where this doesn't work again. I would love to not specify the arguments of a
and write something like a[_]
or a[__]
, but it doesn't seem to work. I'm a bit sad I wasn't able to solve this, given that what I want is so simple: to tell Mathematica, look, whenever you compute derivatives of an expression which contains a
s with respect to some x
, then derivative of each occurrence of a
is a^3 f(x)
.
Dt
instead. $\endgroup$ – swish May 12 '17 at 18:48b
that appears in the expression becomesDt[b,x]
, such that now I have to know which other symbols there will be beforehand and setDt[b,x]^:=0
for all possibleb
. Also in terms of performance, is there any difference betweenD
andDt
? $\endgroup$ – Stan May 12 '17 at 19:12