4

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?

PeterE
  • 5,715
  • 5
  • 29
  • 51
Hatshepsut
  • 5,962
  • 8
  • 44
  • 80

1 Answers1

5

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.

PeterE
  • 5,715
  • 5
  • 29
  • 51
  • Cool. In the result of `diff(g,r,2).simplify()` it seems to be replacing x and y with $\xi_1$ and $\xi_2$ and then subbing them out with their values in terms of $r$ and $t$. Is there a way for it to keep them in terms of x and y? – Hatshepsut Jan 15 '16 at 08:20
  • @Hatshepsut if you want an explicit symbol named "x", use `symbols('x')`. If you just want the name "x" to refer to some other expression in the code use `x = r*cos(t)`. See also http://docs.sympy.org/latest/tutorial/gotchas.html. – asmeurer Jan 15 '16 at 19:25