I encoded a function to calculate the numerical expression of the Lagrange interpolation polynomial:
from sympy import *
import json
def polinomioLagrange(Xs, Ys, t):
x = Symbol('x')
expresion = ''
for k in range(len(Xs)):
if k >0:
expresion = expresion + '+' + str(Ys[k]) + '*'
elif k==0:
expresion = expresion + str(Ys[k]) + '*'
expresion = expresion + '('
for i in range(len(Xs)):
if k==i:
continue
expresion = expresion + '(' + '3' + '-' + str(Xs[i]) + ')'
if k != len(Xs)-1 and i!= len(Xs)-1:
expresion=expresion+'*'
expresion = expresion + '/'
for i in range(len(Xs)):
if k==i:
continue
expresion = expresion + '(' + str(Xs[k]) + '-' + str(Xs[i]) + ')'
if i != len(Xs)-1 and k != len(Xs)-1:
expresion=expresion+'*'
print expresion
print k, i
ewa = raw_input('Prompt :')
expresion = expresion + ')'
print expresion
When I call function c lagrange([0,1,2,4],[-1,0,7,63],3), I get the 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 is actually normal, however, if I try sympify(expresion), I get the error output:
code, global_dict, local_dict)
File "<string>", line 1, in <module>
TypeError: 'NegativeOne' object is not callable
I understand what could be the reason there is -1 in the string, but ... How can I just get the expression being evaluated?
source
share