Python parser error with expressions evaluator

0

Hello, I have been implementing several numerical methods in python for a long time, in this case I am implementing the bisection method and it works perfectly but the problem is in the expression evaluator that is giving me an error that I do not understand, here is the code as well this works perfectly evaluates the function and gives me the graph, but if I try to evaluate the function x^4 + 3x^3 - 2 gives me the error:

  

Traceback (most recent call last):
  File "F: \ bisection3.py", line 19, in
  fa = f ('x ^ 4 + 3x ^ 3 - 2', 'x', a)
  File "F: \ bisection3.py", line 11, in f
  result = p.parse (exp) .evaluate ({var: x0})
  File "C: \ Users \ DanielPortatil \ AppData \ Local \ Programs \ Python \ Python36-32 \ lib \ site-packages \ py_expression_eval__init __. Py", line 610, in parse
  self.error_parsing (self.pos, 'unexpected variable')
  File "C: \ Users \ DanielPortatil \ AppData \ Local \ Programs \ Python \ Python36-32 \ lib \ site-packages \ py_expression_eval__init __. Py", line 639, in error_parsing
  raise Exception (self.errormsg)
  Exception: parse error [column 8]: unexpected variable

and I do not understand why unexpected variable ... in the following code works well does not give the error, but if I change the function to evaluate by x^4 + 3x^3 - 2 will give me that error. If someone can help me I appreciate it a lot, try the function x^4 + 3 - 2 and it works that he is not being able to read a second x is what I get to understand.

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


def f(exp, var, x0):
    p = Parser()    
    p.ops2['^'] = np.power    
    p.ops1['sin'] = np.sin    
    p.ops1['tan'] = np.tan   
    p.consts['e'] = np.e    
    result = p.parse(exp).evaluate({var:x0})    
    return result

a = 0   
b = 100   
error = 10   
i = 0

while(error>1e-8 and i!=100):   
    c = (a + b) / 2    
    fa = f('x^2 + tan(x^3) - 5', 'x', a)    
    fc = f('x^2 + tan(x^3) - 5', 'x', c)    
    if(fc == 0):    
        raiz = c    
        break

    elif(fa * fc < 0):    
        b = c    
    else:    
        a = c    
    raiz = c    
    i += 1    
    error = abs(fc)    
    print("Iteracion",i,". Raiz aproximada:",raiz)    
print(raiz)    
print(i)    
print(f('x^2 + tan(x^3) - 5', 'x',raiz))    

x = np.linspace(0, 15, 101)  
#plt.plot(x, f('x^3 -2 * x^2 - 1','x',x))    
plt.plot(x, f('x^2 + tan(x^3) - 5','x',x))    
#plt.plot(a, f('x^2 + tan(x^3) - 5','x',a), 'or')   
plt.grid()   
plt.show()

I just tried in the following way: x^4 + 3*x^3 - 2 and so does not give the error and evaluates it, but that is not the idea of an expression evaluator, it should work without adding the 3*x^3 . If someone knows how to do to recognize 3x^3 as 3*x^3 I appreciate it a lot

    
asked by Daniel V 21.03.2017 в 15:55
source

0 answers