Evaluating a string with a numeric expression using sympy?

I encoded a function to calculate the numerical expression of the 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 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)  # take local objects in preference
  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?

+4
source share
1 answer

This is all about the expression ( stringso far) having the correct format:

My algorithm was out of order

And so it happened:

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 absent In the last member: *

If I do this:

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)

, , .

+1

Source: https://habr.com/ru/post/1531023/


All Articles