Hatshepsut
Hatshepsut

Reputation: 6652

Chain rule in sympy

I'm trying some basic practice with SymPy. I would like to take a second derivative symbolically of a function in rectangular coordinates with respect to the radius parameter in polar coordinates.

I'd like a nice chain rule symbolic expression where it calculates what it can and leaves unevaluated what can't be simplified further.

from sympy import *
init_session()
x, y, r, t = symbols('x y r t') # r (radius), t (angle theta)
f, g = symbols('f g', cls=Function)
g = f(x,y)
x = r * cos(t)
y = r* sin(t)
Derivative(g,r, 2).doit()

This code yields 0. Is there a way to get a symbolic representation of the answer, rather than 0?

Upvotes: 4

Views: 5681

Answers (1)

PeterE
PeterE

Reputation: 5855

Short answer: Your commands are out of order.

Long answer:

x, y, r, t = symbols('x y r t') # r (radius), t (angle theta)
f, g = symbols('f g', cls=Function)
g = f(x,y)

Now x,y are Symbols, f is a Function and g is an applied Function i.e. the symbols x,y applied to f as f(x,y).

x = r * cos(t)
y = r* sin(t)

Now you redefine x and y as expressions of r and t. This does not affect g in the slightest!

Derivative(g,r, 2).doit()

Now you derive g wrt r. As g is still defined via the initial symbols x,y it does not depend on r, thus the derivative is zero.

To achieve what you want use this:

from sympy import *
r, t = symbols('r t') # r (radius), t (angle theta)
f = symbols('f', cls=Function)
x = r* cos(t)
y = r* sin(t)
g = f(x,y)
Derivative(g,r, 2).doit()

I also dropped all unnecessary Symbol definitions.

Upvotes: 7

Related Questions