Is there a way to convert a Cartesian expression in SymPy to a polar one? I have the following expression:
1/sqrt(x^2+y^2)
However, I can't seem to get SymPy to acknowledge that this is 1/r in polar coordinates. I tried using the 'subs' command, both of the following options (I imported sympy as asp, and defined all of the symbols earlier):
expr = 1/sp.sqrt(x**2+y**2)
expr.subs((x,y),(r*cos(theta),r*sin(theta))
expr.subs((sp.sqrt(x**2+y**2),sp.atan(y/x)),(r,theta))
but in both cases, I simply receive the original expr again.
Is there a way to convert a Cartesian expression to a polar one in SymPy?
subs((x,y),(r*cos(theta),r*sin(theta))
is not a correct syntax for subs
. When multiple symbols are to be replaced, one has to provide either a dictionary
subs({x: r*sp.cos(theta), y: r*sp.sin(theta)})
or an iterable with pairs (old, new) in it:
subs(((x, r*sp.cos(theta)), (y, r*sp.sin(theta))))
The former is more readable; the latter is needed when substitutions must be carried out in a particular order (not the case here).
Either way, to achieve 1/r you also need to declare r
as nonnegative
r = sp.symbols('r', nonnegative=True)
and simplify the result of substitution:
expr.subs({x: r*sp.cos(theta), y: r*sp.sin(theta)}).simplify()