python - Evaluating a string with a numerical expression with sympy? -


i coded function evaluating numeric expression of lagrange interpolation polynomial:

#!/usr/bin/env python #coding: utf8  sympy import * import json   def polinomiolagrange(xs, ys, t):      x = symbol('x')     expresion = ''     k in range(len(xs)):          if k >0: #si no es el primero ni el último término de la sumatoria             expresion = expresion + '+' + str(ys[k]) + '*'         elif k==0:             expresion = expresion + str(ys[k]) + '*'          expresion = expresion + '('          in range(len(xs)):             if k==i:                 continue # si i==k saltamos esta iteración para eliminar división sobre cero              expresion = expresion + '(' + '3' + '-' + str(xs[i]) + ')'              if k != len(xs)-1 , i!= len(xs)-1:                 expresion=expresion+'*'              #expresion = expresion + '(' + str(a) + '-' + str(xs[i]) +' )' + '/' + '(' + str(xs[k]) + '-' + str(xs[i]) + ')'          expresion = expresion + '/'          in range(len(xs)):             if k==i:                 continue # si i==k saltamos esta iteración para eliminar división sobre cero                     expresion = expresion + '(' + str(xs[k]) + '-' + str(xs[i]) + ')'              if != len(xs)-1 , k != len(xs)-1:                 expresion=expresion+'*'                          print expresion             print k,             ewa = raw_input('prompt :')         expresion = expresion + ')'      print expresion 

when call function lagrange([0,1,2,4],[-1,0,7,63],3) output:

7*((3-1)*(3-2)*(3-4)/(0-1)*(0-2)*(0-4))+0*((3-0)*(3-2)*(3-4)/(1-0)*(1-2)*(1-4))+-1*((3-0)*(3-1)*(3-4)/(2-0)*(2-1)*(2-4))+63*((3-0)(3-1)(3-2)/(4-0)(4-1)(4-2)) 

which ok, however, if try sympify(expresion) error output:

  code, global_dict, local_dict)  # take local objects in preference   file "<string>", line 1, in <module> typeerror: 'negativeone' object not callable 

i understand might cause there's -1 there in string ... how expression evaluated?

it's expression (string far) having right format:

my algorithm wasn't ok

and getting:

7*((3-1)*(3-2)*(3-4)/(0-1)*(0-2)*(0-4))+0*((3-0)*(3-2)*(3-4)/(1-0)*(1-2)*(1-4))+-1*((3-0)*(3-1)*(3-4)/(2-0)*(2-1)*(2-4))+63*((3-0)(3-1)(3-2)/(4-0)(4-1)(4-2)) 

with missing * @ last term:

if do:

from sympy import *  expression = '7*((3-1)*(3-2)*(3-4)/(0-1)*(0-2)*(0-4))+0*((3-0)*(3-2)*(3-4)/(1-0)*(1-2)*(1-4))+-1*((3-0)*(3-1)*(3-4)/(2-0)*(2-1)*(2-4))+63*((3-0)*(3-1)*(3-2)/(4-0)*(4-1)*(4-2))' y = s(expression) siympify(y) 

that work , want.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -