7
$\begingroup$

Is it possible to differentiate symbolically w.r.t. some squared quantity in Mathematica? Evaluating something like

D[x^4 + 2 x^2 + 6, x^2]

gives the error message

General::ivar: x^2 is not a valid variable.

Is there some way around this without defining a new variable $y = x^2$?

$\endgroup$
5
  • $\begingroup$ What would be the derivative of $x^3$ wrt $x^2$? $\endgroup$
    – anderstood
    Commented Jan 18, 2017 at 16:36
  • 2
    $\begingroup$ @anderstood $\frac{3}{2} x$. $\endgroup$
    – Janosh
    Commented Jan 18, 2017 at 16:40
  • 7
    $\begingroup$ So, just D[x^4 + 2 x^2 + 6, x] / D[x^2,x]? $\endgroup$
    – swish
    Commented Jan 18, 2017 at 16:47
  • $\begingroup$ @swish I guess this should be an (if not the) answer. $\endgroup$
    – anderstood
    Commented Jan 18, 2017 at 17:16
  • 4
    $\begingroup$ By the chain rule, using implicit differentiation, Df/Dx^2 = (Df/Dx) / (Dx^2/Dx), so this method would also work in general. $\endgroup$
    – JKreft
    Commented Jan 18, 2017 at 18:17

2 Answers 2

7
$\begingroup$

From @swish's comment (but using Dt):

myD[f_,x_]:=FullSimplify[Dt[f]/Dt[x]]

myD[x^3, x^2]
(* (3 x)/2 *)

myD[x^4 + 2 x^2 + 6, x^2]
(* 2 (1 + x^2) *)

If you need to specify constants, I would recommend the following:

myD[f_, x_, cons : OptionsPattern[Dt]] := 
 FullSimplify[Dt[f, cons]/Dt[x, cons] ]

myD[1/Sqrt[x^2 y^4 + m^4], y^3, Constants -> {x, m}]
(* -((2 x^2 y)/(3 (m^4 + x^2 y^4)^(3/2))) *)
$\endgroup$
1
  • $\begingroup$ Thanks for the inspiration. Since I will apply myD to terms containing multiple independent variables for which Dt gives lots of extra terms containing differentials of variables that should really be treated as constant, I ended up going with the implementation myD[f_,x_^n_]:=FullSimplify[D[f,x]/D[x^n,x]]. For instance, for f[y] = 1/Sqrt[x^2 y^4 + m^4], myDt, i.e. your implementation gives myDt[f[y],y^3] = (-2 m^3 Dt[m] - x y^3 (y Dt[x] + 2 x Dt[y]))/(3 y^2 (m^4 + x^2 y^4)^( 3/2) Dt[y]) whereas myD yields myD[f[y],y^3] = -((2 x^2 y)/(3 (m^4 + x^2 y^4)^(3/2))). $\endgroup$
    – Janosh
    Commented Jan 19, 2017 at 13:49
10
$\begingroup$

Temporarily replace x^2 by y and then revert the change:

D[x^4 + 2 x^2 + 6 /. x -> Sqrt[y], y] /. y -> x^2
(* 2 + 2 x^2 *)

For the general case, furthermore use Simplify to replace Sqrt[x^2] in the final result by x:

Simplify[D[x^3 /. x -> Sqrt[y], y] /. y -> x^2, Assumptions -> x > 0]
(* (3 x)/2 *)
$\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.