Solving a system of algebraic equations with SymPy

I am new to python SymPy and am trying to solve a simple system of equations. I can successfully evaluate the variable "y", but when I try to replace that value with "x", I cannot get it to just evaluate the expression and output the value. My code looks like this:

x = Symbol('x')
y = Symbol('y')
A = 1
B = 3
C = 6

x = solve(A*(1-x-y) + B*x + C*y - 4, x)
x = x[0]
y = solve(A*(1-x-y) + B*x - (8-C)*y, y)
y = y[0]

print x
print x.subs(y,0.5)

      

Every try I've made so far only returns -5 * y / 2 + 3/2. I've tried using it for float, trying to use the solution expression in different ways and casting it to a string, and then using simpify to cast it back into the expressible.

Nothing I have done is working and I understand that this will probably be an easy task, but I cannot figure it out. Any suggestion would help, thanks!

+3


source to share


2 answers


I'm not sure if you are going for something like:

from sympy import *

x = Symbol('x')
y = Symbol('y')
A = 1
B = 3
C = 6

xeq = solve(A*(1-x-y) + B*x + C*y - 4,x)[0]
print ('x = %s' % xeq)
yeq = solve(A*(1-x-y) + B*x - (8-C)*y,y)[0]
print ('y = %s' % yeq)

ysolve = 0.5
xval = xeq.subs(y, ysolve)
print ('If y = %f, x = %f' % (ysolve, xval))
yval = yeq.subs(x, xval)
print ('If x = %f, y = %f' % (xval, yval))

      

The output would be:



x = -5*y/2 + 3/2
y = 2*x/3 + 1/3
If y = 0.500000, x = 0.250000
If x = 0.250000, y = 0.500000

      

I believe the main problem with your code is that you are rewriting symbols x

and y

as you go along.

+1


source


Don't forget that you can solve both at the same time with:



>>> x,y=symbols('x y')
>>> A = 1
>>> B = 3
>>> C = 6
>>> sol = solve((
...     A*(1-x-y) + B*x + C*y - 4,
...     A*(1-x-y) + B*x - (8-C)*y, ))
>>> sol
{x: 1/4, y: 1/2}
>>> print "x = {x} and y = {y}".format(x=sol[x],y=sol[y])
x = 1/4 and y = 1/2

      

+2


source







All Articles