sympy solve one equation in 2 unknowns and symbols

47 views Asked by At
import sympy
from sympy.abc import x, y, z, a, b

I want to find the roots in x and y for the following equation: f(x,y) = 2(x - a) + (y - b), whose roots are x=a, y=b. Using sympy I get instead

sym.solve((x - a)*2 + (y - b), [x, y])

$\left[ \left( a + \frac{b}{2} - \frac{y}{2}, y\right)\right]$

In other words, sympy treats y as a symbol (or scalar) instead of variable even if I ask it to solve for y as well. How can I overcome this issue?

2

There are 2 answers

2
Lajos Arpad On BEST ANSWER

The roots you have there are not the only possible roots. Looking at your

2(x - a) + (y - b)

formula, if we equate it to 0 to find the roots:

2(x - a) + (y - b) = 0

then it's clear that

x = (2a + b - y) / 2

and

y = b - 2(x - a)

so there are infinitely many possible roots. besides the roots you have given (x=a, y=b) we could define other roots, like (x = b/2 and y = 2a), having

2(b/2 - a) + 2a - b = 0

b - 2a + 2a - b = 0

0 = 0

as the result and infinitely many possible cases, you take an arbitrary x and compute its corresponding y or take an arbitrary y and compute its corresponding x to generate as many possible root pairs as you like. This is why finding the roots will not lead you to a single tuple, but infinitely many ones.

1
Raky On

SymPy is treating y as a constant instead of a variable in the equation. To overcome this issue and find the roots for both x and y, you can use one of the following approaches:

Solve for x in terms of y and then substitute it back into the original equation to solve for y:

from sympy import Eq, solve

x = solve(2*(x - a) + (y - b) == 0, x)[0]
f_substituted = f.subs(x, x)
y = solve(Eq(f_substituted, 0), y)[0]

print("x =", x, ", y =", y)

Use sympy's linsolve function to directly solve the system of linear equations derived from the original equation:

from sympy import Eq, linsolve

# Convert the equation to a system of linear equations
equations = [Eq(2*(x - a) + (y - b), 0)]

# Solve the system for x and y
solution = linsolve(equations, [x, y])

print("x =", solution[x], ", y =", solution[y])

Either of these approaches should give you the correct solution: x = a, y = b.

Remember to ensure your equation is in the form of Eq(f(x, y), 0) before using linsolve, and use solve cautiously, especially with multiple variables.

I hope this helps.