Reputation: 25
I have two functions, sqrt(x)
and pow(x, y)
, that I want to pass to the "local" argument of sympify upon receiving "sqrt(pow(x,2))" as a string. After this, the goal is to simplify the expression from "sqrt(pow(x,2))" to "x" using simplify.
The code below outputs 'sqrt(x**2)', giving me a hint that the pow(x, y)
function is picked up, but not further simplified for an unknown reason.
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))
The code below correctly outputs an 'x', but has a sympy expression as input. For my usecase, this needs to be a string. Replacing this sympy expression with a call to sp.sympify(input_exp, locals={'sqrt': sqrt, 'pow': pow})
does not work either.
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))))
Any suggestion or solutions are more then welcome. Thank you!
Upvotes: 2
Views: 642
Reputation: 121
You need to pass 'x' as well as a local reference. Here is the code :
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))
and
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))
Upvotes: 2