Reputation: 2804
I have defined some constraints using relational GreaterThan -
x = sympy.Symbol('x')
constraint1 = (x >= 0)
I want to now check if the constraint holds for an arbitrary value of 'x'. I tried using sympy.checksol
, but get an attribute error, so I'm guessing that's not the way to go -
In [7]: sympy.checksol(constraint1, {x: 3})
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-7-cc41bd5986e3> in <module>()
----> 1 sympy.checksol(constraint1, {x: 3})
/Library/Python/2.7/site-packages/sympy/solvers/solvers.pyc in checksol(f, symbol, sol, **flags)
200 if attempt == 0:
201 val = f.subs(sol)
--> 202 if val.atoms() & illegal:
203 return False
204 elif attempt == 1:
AttributeError: 'bool' object has no attribute 'atoms'
I even tried constraint1.evalf
but it always returns itself -
In [10]: constraint1.evalf(subs={x: 3})
Out[10]: x >= 0
In [11]: constraint1.evalf(subs={x: -3})
Out[11]: x >= 0
So how do I evaluate the relational constraint for given values of its symbols?
Upvotes: 1
Views: 437
Reputation: 91470
evalf
is for numerical evaluation of expressions, which is not what you want here. Just use subs
, as you discovered
>>> constraint1.subs(x, -3)
False
And be aware that if you plug something in that it can't figure out, it will remain unevaluated:
>>> contraint1.subs(x, y)
y >= 0
Also, subs only does basic checking. If you want more advanced checking, you should use ask
(ask
currently doesn't translate inequalities, so you'll need to convert them to Q.positive
or Q.nonnegative
manually).
Upvotes: 5