mathsympysymbolic-math

Sympy parametric plot in polar coordinates


I want to plot the parametrization r2=4 cos(t). From 0 to 2π for t this should give me two lobes, symmetrically placed around the y-axis, but I can only get one in sympy due to the square root.

import sympy as sp
r, t = sp.symbols('r t')

r = sp.sqrt(4 * sp.cos(t))

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

sp.plot_parametric((x,y), (t, - sp.pi/2, sp.pi/2), aspect_ratio = (1,1),size=(4,4),axis_center = (0,0))

enter image description here

How do I get its mirror lobe?


Solution

  • If you start with r2=4 cos(t), then you have two solutions for r:

    You want to plot them both:

    import sympy as sp
    r, t = sp.symbols('r t')
    
    r1 = sp.sqrt(4 * sp.cos(t))
    r2 = -sp.sqrt(4 * sp.cos(t))
    
    def to_polar(r):
        x = r * sp.cos(t)
        y = r * sp.sin(t)
        return x, y
    
    sp.plot_parametric(
        to_polar(r1),
        to_polar(r2),
        (t, - sp.pi/2, sp.pi/2), aspect_ratio = (1,1),size=(4,4),axis_center = (0,0))
    

    enter image description here

    EDIT to satisfy comment: SymPy doesn't have a plus/minus object. Hence, if you don't want to manually code the expressions, you could write your original equation in r, solve it for r, and loop over the solution to convert them to polar:

    r = sp.symbols("r")
    eq = sp.Eq(r**2, 4 * sp.cos(t))
    sol = sp.solve(eq, r)
    polar_sol = [to_polar(s) for s in sol]
    sp.plot_parametric(*polar_sol, (t, - sp.pi/2, sp.pi/2), aspect_ratio = (1,1),size=(4,4),axis_center = (0,0))