7

I am using SymPy lib for Python. I have two sympy symbols and expression that binds them:

x = Symbol('x')
y = Symbol('y')
expr = 2 * x - 7 * y

How can i express 'y' in terms of 'x', i.e get the equality:

y = (2/7) * x

Thanks.

eupp
  • 415
  • 3
  • 13

2 Answers2

11

This is how you can express this equation in terms of x:

In [1]: from sympy import *

In [2]: x, y = symbols('x, y')

In [3]: expr = 2*x - 7*y

In [4]: solve(expr, y)
Out[4]: [2*x/7]

This works because if the solve() function is presented with something that is not a full equation, it assumes that the provided expression is equal to zero. In other words, writing

expr = 2*x - 7*y

above is equivalent to writing

expr = Eq(2*x - 7*y, 0)

which would tell SymPy that

2x - 7y = 0.
qwerty_so
  • 31,206
  • 7
  • 53
  • 81
Sudhanshu Mishra
  • 1,721
  • 1
  • 18
  • 37
1

Since this is the first result that shows up in Google search, I'll provide an alternative approach, even though it's not a direct answer to the question.

As the other answer pointed out, if you have two independent symbols and an equation relating them, you can use expr.solve to express one of them in terms of the other:

x, y = symbols('x y')
expr = 2*x - 7*y

y = solve(expr, y)[0]
y # outputs 2*x/7

But sometimes it occurs that you only have only one independent symbol x and the other symbol y is expressed in terms of x, and you want to reverse the dependence – make y the independent symbol.

# what we have
y = symbols('y')
x = 7*y/2

# what we want
x = symbols('x')
y = ???

That's where this simple utility function comes in handy. It lets you express a in terms of b.

def express(a, b, name):
    sym = symbols(name)
    sol = solve(a-sym, b)
    assert len(sol) == 1
    return (sym, sol[0])

The first argument a is the dependent variable that we want to express in terms of the free variable b. The third argument name is the name we will give to a (it was just an unnamed expression until now).

Example usage:

y = symbols('y')
x = 7*y/2

x, y = express(x, y, 'x')
y # outputs 2*x/7
m93a
  • 7,128
  • 6
  • 29
  • 45