2016-04-05 9 views
2

私はsympyライブラリを掘り下げているので、特に解析された関数を評価しようとするときに問題に遭遇しました。関数(2z)のように手動で関数を入力すると、期待どおりに評価されます。しかし、私は文字列を取るためにこのクラスを使用できるようにする必要がありますが、私は期待される出力を得ることができません。出力された状態でsympy expr_parse()関数の評価が失敗する

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" を使用して試してみました。私はちょうど本当にオフベースの何かをやっていると確信していますが、ここからどこに行くのか分かりません。

+0

[この質問](http://stackoverflow.com/questions/7820771/python-number-like-class-that-remembers-arithmetic-operations)への私の答えはあなたを助けるかもしれません。 – PaulMcG

答えて

2

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