How do I access the variable x and y in an equation

46 Views Asked by At
from sympy import symbols, Eq, solve, Circle, Point, latex, simplify, sympify
x, y = symbols('x y')
m = Circle(Point(0, 0), Point(1, 0), Point(0, 2))
dt = m.equation()
dt = dt.subs(x,2)
print(dt)

The answer should be like be

k=(x - 1/2)**2 + (y - 1)**2 - 5/4
k = k.subs(x, 2)
print(k)

I tried to copy the whole block inside sympy lib but it got confused of the "_symbol". The type of dt is <class 'sympy.core.add.Add'> but when open lib, I couldn't find sympy.core.add.Add.

I hope to change to value of x and y inside the equation so it would give the answer like the second line.

1

There are 1 best solutions below

0
ti7 On

The issue is that the x an y from a naive Circle.equation() are not the same Symbols as you created (despite appearances), and you should either pass in the symbols as arguments or use the defaults and get them from the equation (How can I get a list of the symbols in a sympy expression? )

>>> dt.free_symbols
{y, x}
>>> [sym is x for sym in dt.free_symbols]
[False, False]

Passing in the symbols

>>> f = m.equation(x,y)  # quick access to docs via help(m.equation)
>>> f
(x - 1/2)**2 + (y - 1)**2 - 5/4
>>> f.subs({x:2, y:3})
5
>>> [sym is x for sym in f.free_symbols]
[False, True]

extracting them from it into a dict (ugly)

>>> f = m.equation()
>>> f.free_symbols
{y, x}
>>> smb = {str(sym): sym for sym in f.free_symbols}
>>> smb
{'y': y, 'x': x}
>>> f.subs({smb["x"]:2, smb["y"]:3})
5

Finally, you could use lambdify it

>>> from sympy import lambdify
>>> f = m.equation()
>>> fn = lambdify(sorted(f.free_symbols, key=str), f)
>>> fn(x=1, y=3)
3.0
>>> fn(x=2, y=3)
5.0