I'm new to SymPy and python and I was faced with a problem. I'm trying to solve a system 'kunSys':
>>> kunSys
[-w0 + w1 - 8*x1 + 20,
-2*w0 + w2 - 8*x2 + 4,
w0*(-x1 - 2*x2 + 2),
w1*x1,
w2*x2,
w0 >= 0,
w1 >= 0,
w2 >= 0]
With a list of variables 'lagVars':
>>> lagVars
(x1, x2, w0, w1, w2)
As you can see, my system contains both eqations and inequalities.
Trying:
>>> solve(kunSys,lagVars)
Get:
NotImplementedError:
inequality has more than one symbol of interest
But it works fine when solving eqations and inequalities separately:
>>> kunSys[:5]
[-w0 + w1 - 8*x1 + 20,
-2*w0 + w2 - 8*x2 + 4,
w0*(-x1 - 2*x2 + 2),
w1*x1,
w2*x2]
>>> solve(kunSys[:5],lagVars)
[(0, 0, 0, -20, -4),
(0, 1/2, 0, -20, 0),
(0, 1, -2, -22, 0),
(2, 0, 4, 0, 4),
(11/5, -1/10, 12/5, 0, 0),
(5/2, 0, 0, 0, -4),
(5/2, 1/2, 0, 0, 0)]
>>> kunSys[5:]
[w0 >= 0, w1 >= 0, w2 >= 0]
>>> solve(kunSys[5:],lagVars)
(0 <= w0) & (0 <= w1) & (0 <= w2) & (w0 < oo) & (w1 < oo) & (w2 < oo)
But this is not a wanted result. I tried to use solveset() but it doesn't seem to work also. I googled a lot, but failed to find the answer.
Question:
How do I solve this system?
After the symbols and equations are defined, we can use SymPy's solve() function to compute the value of x and y. The first argument passed to the solve() function is a tuple of the two equations (eq1, eq2) . The second argument passed to the solve() function is a tuple of the variables we want to solve for (x, y) .
For example objects like sin or exp have _eval_derivative methods that are called as SymPy evaluates the derivative of a complex expression like sin(exp(x)). By capturing the inputs and outputs of all of these small methods we can collect a great quantity of information about the steps that SymPy takes.
SymPy presently doesn't know how to handle mixed inequalities and equalities, but since your inequalities are just variable >= 0
, you can work around this by just defining those symbols to be nonnegative. solve
will then filter the solutions based on that
>>> w0, w1, w2 = symbols('w0:3', nonnegative=True)
>>> x1, x2 = symbols("x1 x2")
>>> solve([-w0 + w1 - 8*x1 + 20,
... -2*w0 + w2 - 8*x2 + 4,
... w0*(-x1 - 2*x2 + 2),
... w1*x1,
... w2*x2], (w0, w1, w2, x1, x2))
[(0, 0, 0, 5/2, 1/2), (12/5, 0, 0, 11/5, -1/10), (4, 0, 4, 2, 0)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With