Question

I coded a function for evaluating the numeric expression of Lagrange Interpolation polynomial:

#!/usr/bin/env python
#coding: utf8 
from sympy import *
import json


def polinomioLagrange(Xs, Ys, t):

    x = Symbol('x')
    expresion = ''
    for 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 + '('

        for i 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 and i!= len(Xs)-1:
                expresion=expresion+'*'

            #expresion = expresion + '(' + str(a) + '-' + str(Xs[i]) +' )' + '/' + '(' + str(Xs[k]) + '-' + str(Xs[i]) + ')'

        expresion = expresion + '/'

        for i 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 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 the function with 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 OK, however, if I try sympify(expresion) I get the error output:

  code, global_dict, local_dict)  # take local objects in preference
  File "<string>", line 1, in <module>
TypeError: 'NegativeOne' object is not callable

I understand that might be cause there's a -1 there in the string but ... How could I simply get the expression evaluated?

Was it helpful?

Solution

It's all about the expression (string so far) having a right format:

My algorithm wasn't OK

And so was 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 some missing * At last term:

If I 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 would simply work and I will get what I want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top