我有两个函数sqrt(x)
和pow(x, y)
,在接收字符串形式的“ sqrt(pow(x,2))”时,我想传递给sympify的“ local”参数。此后,目标是使用简化将表达式从“ sqrt(pow(x,2))”简化为“ x”。
下面的代码输出'sqrt(x ** 2)',给了我一个暗示,pow(x, y)
函数已被使用,但由于未知原因而没有进一步简化。
import sympy as sp
# Function Definitions
def pow(x, y):
return x ** y
def sqrt(x):
return sp.sqrt(x)
sp.symbols('x', positive=True, real=True)
input_exp = 'sqrt(pow(x, 2))'
eqn = sp.sympify(input_exp, locals={'sqrt': sqrt, 'pow': pow})
print("Simplification: ", sp.simplify(eqn))
下面的代码正确地输出一个'x',但是有一个sympy表达式作为输入。对于我的用例,这需要是一个字符串。用对sp.sympify(input_exp, locals={'sqrt': sqrt, 'pow': pow})
的调用替换此sympy表达式也不起作用。
import sympy as sp
from sympy import Function
# Function definitions
class pow(Function):
@classmethod
def eval(cls, x, y):
return x ** y
class sqrt(Function):
@classmethod
def eval(cls, x):
return sp.sqrt(x)
# Simplify the expression.
x = sp.symbols('x', positive=True, real=True)
print("Simplification: ", sp.simplify(sqrt(pow(x, 2))))
欢迎任何建议或解决方案。 谢谢!
答案 0 :(得分:0)
您需要传递“ x”以及本地参考。 这是代码:
import sympy as sp
# Function Definitions
def pow(x, y):
return x ** y
def sqrt(x):
return sp.sqrt(x)
x = sp.symbols('x', positive=True, real=True)
input_exp = 'sqrt(pow(x, 2))'
eqn = sp.sympify(input_exp, locals={'sqrt': sqrt, 'pow': pow, 'x':x})
print("Simplification: ", sp.simplify(eqn))
和
import sympy as sp
from sympy import Function
# Function definitions
class pow(Function):
@classmethod
def eval(cls, x, y):
return x ** y
class sqrt(Function):
@classmethod
def eval(cls, x):
return sp.sqrt(x)
# Simplify the expression.
x = sp.symbols('x', positive=True, real=True)
input_exp = 'sqrt(pow(x, 2))'
eqn = sp.sympify(input_exp, locals={'sqrt': sqrt, 'pow': pow, 'x':x})
print("Simplification: ", sp.simplify(eqn))