# 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
替换未知函数F(x) = x**0.5 + 1
?例如:
result = expr.subs(F(_), _**0.5 + 1)
哪会导致:
(a - b)**0.5 - (b**2 - c)**0.5
答案 0 :(得分:2)
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)
答案 1 :(得分:1)
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)
答案 2 :(得分:0)
这可以通过继承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]: