Reputation: 45
I'm new to python's SymPy and am trying to solve a simple system of equations. I can successfully evaluate the variable 'y', but when I attempt to substitute this value back into 'x', I cannot get it to simply evaluate the expression and output a value. My code is as follows:
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 attempt I've made so far only returns -5*y/2 + 3/2. I've tried casting it to a float, trying to use the solve expression in different ways, and casting it to a string and then using the simpify to turn it back into an expression to solve.
Nothing I've done works and I realize this should probably be an easy task but I can't figure it out. Any suggestion will help, thanks!
Upvotes: 3
Views: 3661
Reputation: 19145
Don't forget that you can solve both at once, too, with solve:
>>> 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
Upvotes: 2
Reputation: 47643
I'm not sure if you were 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 overwriting the Symbols x
and y
as you were going along.
Upvotes: 1