pythonsympy

Find the equation of a line with sympy (y=mx+b)


So I'm brushing up on my algebra and trying to learn sympy at the same time. Following an algebra tutorial on youtube, I'm at this point: finding the equation of a line

I can't quite figure out how to isolate y

What I've tried:

p1 = sym.Point(-1, 1)
m = -2
eq = sym.Line(p1, slope=m).equation()
eq

returns: 2x + y + 1

eq1 = sym.Eq(eq, 0)
eq1

Gives me: 2x + y + 1 = 0

and..

eq2 = sym.simplify(eq1)
eq2

Returns: 2x + y = -1

..but that's as close as I can get to isolating y (y = -2x - 1). I'm sure it's a simple answer but I've been searching on the intertubes for 2 days now without success. I've tried solve() and subs(), solve just returns an empty set and subs gives the original equation back. What am I doing wrong?


Solution

  • I believe that the code below gives what you want. I believe solve wasn't working for you because you needed to define x, y as symbols. Then you can use the solution to create your equation using Eq. Note that the solution is a list. Hope this helps.

    import sympy as sym
    from sympy.solvers import solve
    
    p1 = sym.Point(-1, 1)
    m = -2
    eq = sym.Line(p1, slope=m).equation()
    print(eq)
    
    eq1 = sym.Eq(eq, 0)
    print(eq1)
    
    x, y = sym.symbols('x y', real = True)
    
    sol = solve(eq, y)
    print(sol)
    
    eq1 = sym.Eq(y, sol[0])
    print(eq1)
    

    Output:

    2*x + y + 1
    Eq(2*x + y + 1, 0)
    [-2*x - 1]
    Eq(y, -2*x - 1)