问题
I want to extend the Symbols class in SymPy so that I can add a Boolean attribute. I’m able to accomplish this for a single symbol (see my question here, and also someone else’s question here). And the code to accomplish this is repeated below:
from sympy.core.symbol import Symbol
class State(Symbol):
def __init__(self, name, boolean_attr):
self.boolean_attr = boolean_attr
super(State, self).__init__(name)
However, the problem with this solution is that when I am defining a polynomial, or some kind of expression involving more than one State, which is my extension of the Symbol class as you can see above, I need them all to be in the same domain when I evaluate it:
symbols defined separately cannot be evaluated numerically:
x=sympy.symbols('x')
y=sympy.symbols('y')
some_poly = Poly(x+y)
print some_poly.evalf(subs=dict(zip([sympy.symbols('x, y')],[1,4])))
>>> Poly(x + y, x, y, domain='ZZ')
symbols defined in the same domain can be evaluated numerically:
x, y = sympy.symbols('x, y')
some_poly = Poly(x+y)
print some_poly.evalf(subs=dict(zip(sympy.symbols('x,y'),[1,1])))
>>> 2.00000
Here is my question: How do I achieve this same behavior in my class State? Ideally it would work as follows:
x=State('x', boolean_attr=True)
y=State('y', boolean_attr=False)
states_poly = Poly(x+y)
print states_poly.evalf(subs=dict(zip(States('x,y'),[1,1])))
>>> 2.00000
But that doesn’t work because Sympy interprets x and y as being in different domains. How do I either:
- get
Sympyto interpretxandyas being in the same domain OR extend the
Stateclass to be able to define symbols in the same domain, e.g.:x, y =State('x, y', boolean_attr=[True, False])
How do I allow my polynomials defined using my extended class to be evaluated numerically?
回答1:
In your first example you put symbols in a list so you didn't zip x and y with the values 1, 4:
>>> Poly(x+y).evalf(subs=dict(zip(sympy.symbols('x, y'),[1,4])))
5.00000000000000
You will get the desired result if you use the same State symbols that you defined
>>> x=State('x', boolean_attr=True)
... y=State('y', boolean_attr=False)
... states_poly = Poly(x+y)
... states_poly.evalf(subs=dict(zip((x,y),[1,1])))
2.00000000000000
(In your proposed syntax you used States which was undefined. Even if it did work, such a routine wouldn't have put True for one boolean_attr and False for the other and since Symbols match on attributes, the substitution would have failed.)
来源:https://stackoverflow.com/questions/57333942/how-to-assign-properties-to-symbols-in-sympy-and-have-them-in-the-same-domain