Sympy’s solve
method doesn’t return all solutions on this relatively simple problem:
import sympy as sp
y1, y2, x = sp.symbols('y1 y2 x')
y1 = x**2
y2 = x
sp.solve(y1, y2, dict = True)
This returns [{x: 0}]
but there should be an x=1
solution as well.
Am I using this correctly?
1
You are trying to find the intersection between a parabola and a straight line. If you were to do it by hand, you would write:
step 1: x**2 = x
step 2: x**2 - x = 0
step 3: x * (x - 1) = 0
step 4: x = 0, x = 1
So, you have to inform sympy that the equation you are trying to solve is x**2 - x
:
import sympy as sp
x = sp.symbols('x')
y1 = x**2
y2 = x
eq = y1 - y2
sp.solve(eq, x, dict = True)
# [{x: 0}, {x: 1}]
There is a mistake in your code, sp.solve(y1, y2, dict=True) is incorrect because “solve” search equations and variables to solve. Thus you should pass equation to solve and not just expression.
Have a look at the below given code snippet:
Method:-01
import sympy as sp
x = sp.symbols('x')
y1 = x**2
y2 = x
eq1 = sp.Eq(y1, x**2)
eq2 = sp.Eq(y2, x)
solutions = sp.solve((eq1, eq2), (x, y2), dict=True)
print(solutions)
Method-02
import sympy as sp
x = sp.symbols('x')
y1 = x**2
y2 = x
solutions = sp.solve([y1 - x**2, y2 - x], x)
print(solutions)
Hope your queries are resolved.
1