How to assign properties to symbols in SymPy and have them in the same domain?

為{幸葍}努か 提交于 2019-12-11 17:05:47

问题


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 Sympy to interpret x and y as being in the same domain OR
  • extend the State class 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!