Skip to main content
 首页 » 编程设计

python之Sympy expr_parse() 导致函数求值失败

2024年10月24日8myhome

我一直在研究 sympy 库,在尝试评估已解析的函数时遇到了一个问题。如果我手动输入函数,如 function(2z),它会按预期进行计算。但是,我需要能够使用此类来获取字符串,但无法获得预期的输出。

from sympy import I, re, im, Abs, arg, conjugate, Symbol, symbols, lambdify 
from sympy.parsing.sympy_parser import parse_expr 
from sympy.abc import z 
import numpy 
 
class function(object): 
    def __init__(self, expre): 
        self.z=symbols('z',complex=True) 
        if isinstance(expre,str): 
            self.expre = parse_expr(expre) 
        else: 
            self.expre=expre 
        self.f_z=lambdify(self.z, self.expre, "numpy") #taking advantage of the reuse of the function object. Lamdba numby operations greatly speed up operations on large amounts of data with inital overhead 
 
    def evaluateAt(self,w): 
        return self.f_z(w) #return the result! 
 
z=symbols('z',complex=True) 
funct=function(z**2) 
print(funct.evaluateAt(complex(1+1j))) 
 
funct=function("z**2") 
print(funct.evaluateAt(complex(1+1j))) 

输出为:

2j 
z**2 

我也试过使用“sympify”也无济于事。我很确定我只是在做一些非常离谱的事情,但不知道从这里到哪里去。

请您参考如下方法:

与其从 object 继承子类,不如从 sympy.core.function.Function 类继承。

from sympy import Function 
 
 
class some_func(Function): 
 
    @classmethod 
    def eval(cls, expr, sym): 
        # automatic evaluation should be done here 
        # return None if not required 
        return None 
 
 
    def evaluateAt(self, pt): 
        return self.args[0].subs(self.args[1], pt) 
 
>>> s = some_func("z**2", "z") 
>>> s.evaluateAt(complex(1 + 1j)) 
(1.0 + 1.0*I)**2 
>>> s.evaluateAt(complex(1 + 1j)).expand() 
2.0*I