Kalcifer
Kalcifer

Reputation: 1600

How do I rearrange an equation to be in terms of a specified variable with Sympy?

I can write, for example,

Line(Point(3,-4), Point(-2,2)).equation()

to generate an equation of a line that passes through those points, but the output is given as

-6x - 5y - 2

presumably being equivalent to -6x - 5y - 2 = 0. How can I instead set the output to be

y = (-6/5)x - (2/5)

I thought it might have to do with some formatting settings in the equation() method, so I checked the documention, but it didn't say anything about it.

EDIT 1: It appears that if I input

solve(Eq(Line(Point(3,-4), Point(-2,2)).equation()))

I will get the (albeit ugly) output

⎡⎧     5⋅y   1⎫⎤
⎢⎨x: - ─── - ─⎬⎥
⎣⎩      6    3⎭⎦

This does give a rearranged solution, but the issue is that this is only in the form of x=f(y). I'm not sure how I would get it to instead be in terms of y=f(x).

EDIT 2: I think this might actually be a bug with solve(), or Eq(). If I instead manually type

solve(-6*x-5*y-2,y)

or

solve(Eq(-6*x-5*y-2),y)

I will get the (somewhat ugly, but correct) output of

⎡  6⋅x   2⎤
⎢- ─── - ─⎥
⎣   5    5⎦

Now if I were to instead type

solve(Eq(Line(Point(3,-4), Point(-2,2)).equation()),y)

or

solve(Eq(Line(Point(3,-4), Point(-2,2)).equation()),x)

I get the output of

[]

This is rather strange, though, because

Eq(-6*x-5*y-2)

and

Eq(Line(Point(3,-4),Point(-2,2)).equation())

both output

-6⋅x - 5⋅y - 2 = 0

so I'm really not sure what Is going on here.

Upvotes: 0

Views: 507

Answers (2)

smichr
smichr

Reputation: 18939

The symbols used in the equation have assumptions on them and that makes them different from the plain symbols you might create with Symbol('x'). So that's why it has the option to pass in the symbols you want to use for x and y.

>>> var('x y')
(x, y)
>>> Line(Point(3,-4), Point(-2,2)).equation(x,y)
-6*x - 5*y - 2
>>> Eq(y, solve(_, y)[0])
Eq(y, -6*x/5 - 2/5)

That's also why you didn't get a solution in one of your examples -- the variable you were solving for wasn't in the equation. It looked the same but it wasn't since it had different assumptions on it.

Upvotes: 0

Nebiyou Yismaw
Nebiyou Yismaw

Reputation: 790

Since you need to pass the symbol you want to solve for, you can do something like this (Although the equation function expects strings )

x, y = symbols('x, y')
eq = (Line(Point(3,-4), Point(-2,2)).equation(x,y))

print(solve(eq, y))# prints [-6*x/5 - 2/5]

or you can get the symbol from the expression and pass it to solve like

eq = (Line(Point(3,-4), Point(-2,2)).equation())

print(solve((eq), list(eq.atoms(Symbol))[1])) # prints [-6*x/5 - 2/5]

Upvotes: 1

Related Questions