Exception parse error parity

0

I am trying to evaluate the derivative of a function with the parser function evaluator, the problem is that when sympy returns the exponents represented as "**" and my evaluator does not understand that it is power, he is waiting for a symbol ^ Then I throw that parity error. First I make the imports that I will need. Then sympy requires that you define variables, that's what I do with saying x = Symbol ('x') I define my function f and I draw its derivative with the SymPy diff method. I convert that result into a string because the evaluator receives strings, then I evaluate that result in the evaluator and it works with the function that is there, f = x ^ 2 derivative = 2 * x evaluated in 2 = 4. BUT if I try to evaluate let's say f = x ^ 3 derivative = 3 * x ^ 2 (this ^ returns it as two asterisks *) evaluated in 2 generates the error Exception: parse error [column 6]: parity So here what I need is some way for my evaluator to know that ** is to raise or that the result of the derivation of the diff method returns to me the powers so ^, I am thinking about some solution but until now I do not get anything please help .

from sympy import *
#from numpy import *
import numpy as np
from matplotlib import *
from py_expression_eval import *
import matplotlib.pyplot as plt

p = Parser()
p.ops2['^'] = np.power
p.ops1['sin'] = np.sin
p.ops1['tan'] = np.tan
p.ops1['cos'] = np.cos
p.ops1['log'] = np.log
p.consts['e'] = np.e

x = Symbol('x')
y = Symbol('y')
f = 'x^2'
derivada = diff(f, x)
derivadaStr = str(derivada)
print(derivada)

print(p.parse(derivadaStr).evaluate({'x': 2}))
    
asked by Daniel V 23.03.2017 в 19:52
source

1 answer

0

My own solution but I hope for better solutions and.y

from sympy import *
#from numpy import *
import numpy as np
from matplotlib import *
from py_expression_eval import *
import matplotlib.pyplot as plt

p = Parser()
p.ops2['^'] = np.power
p.ops1['sin'] = np.sin
p.ops1['tan'] = np.tan
p.ops1['cos'] = np.cos
p.ops1['log'] = np.log
p.consts['e'] = np.e

x = Symbol('x')
y = Symbol('y')
f = 'x^3'
derivada = diff(f, x)
derivadaStr = str(derivada)
derivadaStr2 = derivadaStr.replace("**", "^")
print(derivadaStr2)

print(p.parse(derivadaStr2).evaluate({'x': 2}))
    
answered by 23.03.2017 в 20:11