Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

python - Why won't sympy take my symbols?

I have symbols defined as follows:

import sympy

class construct(object):   
    def __init__(self, value):
        self.value = value

    def __add__(self, symbol):    
        return construct(self.value+symbol.value)

    def __mul__(self,symbol):
        return construct(self.value*symbol.value)

a = construct(2)
b = construct(10)

(the above code is runnable). Now, when I try to put them in a sympy matrix, it raises an error and I can't figure out why:

import sympy
A= sympy.Matrix([[a],[b]])


....SympifyError: Sympify of expression 'could not parse u'<__main__.construct object at 0x1088a5ad0>'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)

I'm not even using strings here at all, so I'm not sure why it's complaining about a parse error.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The <__main__.construct object at 0x1088a5ad0> in the error message is what is returned by the default construct.__str__() method. I notice that once that method is overridden with one returning the string representation of construct.value then anything that uses sympy.sympify() (including sympy.Matrix()) accepts it. I don't know that this is how existing custom objects are intended to be converted by SymPy--there might be a more ideal way.

import sympy

class construct(object):

    def __init__(self, value):
        self.value = value

    def __add__(self, symbol): 
        return construct(self.value+symbol.value)

    def __mul__(self,symbol):
        return construct(self.value*symbol.value)

    def __str__(self):
        return str(self.value)

a = construct(2)
b = construct(10)
print(sympy.Matrix([[a],[b]])) # will output 'Matrix([[2], [10]])'

Were I to do this only with SymPy classes, I would use the following:

import sympy
a,b = sympy.symbols('a b')
a = 2
b = 10
print(sympy.Matrix([[a],[b]])) # will output 'Matrix([[2], [10]])'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...