sympy 中的占位符函数
placeholder functions in sympy
# python 2.7.10
# sympy 0.7.6
import sympy as sym
a, b, c, x = sym.symbols('a b c x')
F = sym.symbols('F', cls=sym.Function)
假设我们有一个表达式:
expr = F(a - b) - F(b**2 - c)
有没有办法用已知函数F(x) = x**0.5 + 1
替换未知函数F
?例如:
result = expr.subs(F(_), _**0.5 + 1)
这将导致:
(a - b)**0.5 - (b**2 - c)**0.5
这可以通过继承 Function
并定义适当的 eval
方法来完成 (http://docs.sympy.org/dev/modules/core.html#id50)
In [1]: from sympy import Function, sqrt
In [2]: from sympy.abc import x, y, z, a, b, c
In [4]: f = Function('f')
In [5]: expr = f(a-b)+f(b**2-c)
In [6]: expr
Out[6]: f(a - b) + f(b**2 - c)
In [11]: class F(Function):
....:
....: @classmethod
....: def eval(cls, x):
....: return sqrt(x)+1
....:
In [12]: expr.subs(f, F)
Out[12]: sqrt(a - b) + sqrt(b**2 - c) + 2
Python的type
函数可以用来缩短F
的定义
In [13]: G = type('G', (Function, ),
{'eval' : classmethod(lambda self, x : sqrt(x)+1)})
In [14]: expr.subs(f, G)
Out[14]: sqrt(a - b) + sqrt(b**2 - c) + 2
In [15]:
In [1]: import sympy as sm
In [2]: a, b, c, x = sm.symbols('a b c x')
In [3]: F = sm.symbols('F', cls=sm.Function)
In [4]: expr = F(a - b) - F(b**2 - c)
您可以使用 SymPy 的 Lambda 函数来定义自定义函数。
In [5]: G = sm.Lambda(x, sqrt(x) + 1)
In [6]: expr.subs(F, G)
Out[6]: sqrt(a - b) - sqrt(b**2 - c)
replace
是为此目的制作的:
>>> import sympy as sym
>>> a, b, c, x = sym.symbols('a b c x')
>>> F = sym.symbols('F', cls=sym.Function)
>>> expr = F(a - b) - F(b**2 - c)
>>> arg=Wild('arg')
>>> expr.replace(F(arg), sqrt(arg) + 1)
sqrt(a - b) - sqrt(b**2 - c)
# python 2.7.10
# sympy 0.7.6
import sympy as sym
a, b, c, x = sym.symbols('a b c x')
F = sym.symbols('F', cls=sym.Function)
假设我们有一个表达式:
expr = F(a - b) - F(b**2 - c)
有没有办法用已知函数F(x) = x**0.5 + 1
替换未知函数F
?例如:
result = expr.subs(F(_), _**0.5 + 1)
这将导致:
(a - b)**0.5 - (b**2 - c)**0.5
这可以通过继承 Function
并定义适当的 eval
方法来完成 (http://docs.sympy.org/dev/modules/core.html#id50)
In [1]: from sympy import Function, sqrt
In [2]: from sympy.abc import x, y, z, a, b, c
In [4]: f = Function('f')
In [5]: expr = f(a-b)+f(b**2-c)
In [6]: expr
Out[6]: f(a - b) + f(b**2 - c)
In [11]: class F(Function):
....:
....: @classmethod
....: def eval(cls, x):
....: return sqrt(x)+1
....:
In [12]: expr.subs(f, F)
Out[12]: sqrt(a - b) + sqrt(b**2 - c) + 2
Python的type
函数可以用来缩短F
In [13]: G = type('G', (Function, ),
{'eval' : classmethod(lambda self, x : sqrt(x)+1)})
In [14]: expr.subs(f, G)
Out[14]: sqrt(a - b) + sqrt(b**2 - c) + 2
In [15]:
In [1]: import sympy as sm
In [2]: a, b, c, x = sm.symbols('a b c x')
In [3]: F = sm.symbols('F', cls=sm.Function)
In [4]: expr = F(a - b) - F(b**2 - c)
您可以使用 SymPy 的 Lambda 函数来定义自定义函数。
In [5]: G = sm.Lambda(x, sqrt(x) + 1)
In [6]: expr.subs(F, G)
Out[6]: sqrt(a - b) - sqrt(b**2 - c)
replace
是为此目的制作的:
>>> import sympy as sym
>>> a, b, c, x = sym.symbols('a b c x')
>>> F = sym.symbols('F', cls=sym.Function)
>>> expr = F(a - b) - F(b**2 - c)
>>> arg=Wild('arg')
>>> expr.replace(F(arg), sqrt(arg) + 1)
sqrt(a - b) - sqrt(b**2 - c)