为什么 sympy 不接受我的符号? [英] Why won't sympy take my symbols?

查看:50
本文介绍了为什么 sympy 不接受我的符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的符号定义如下:

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)

(上面的代码是可运行的).现在,当我尝试将它们放入 sympy 矩阵时,它会引发错误,我不知道为什么:

(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.

推荐答案

错误消息中的 <__main__.construct 对象在 0x1088a5ad0> 是默认 结构返回的内容.__str__() 方法.我注意到,一旦该方法被一个返回 construct.value 的字符串表示的方法覆盖,那么任何使用 sympy.sympify()(包括 sympy.Matrix()) 接受它.我不知道 SymPy 打算如何转换现有的自​​定义对象——可能有更理想的方法.

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]])'

如果我只使用 SymPy 类来执行此操作,我将使用以下内容:

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]])'

这篇关于为什么 sympy 不接受我的符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆