我编写了一个函数来评估拉格朗日插值多项式的数值表达式:
#!/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
当我用lagrange([0,1,2,4],[ – 1,0,7,63],3)调用函数时,我得到输出:
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))
这实际上没问题,但是,如果我尝试sympify(expresion),我会得到错误输出:
06002
我明白这可能是因为字符串中有一个-1但是……我怎么能简单地得到表达式?
解决方法:
这是关于具有正确格式的表达式(字符串到目前为止):
得到了:
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))
有些人遗失*在上学期:
如果我做:
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)
那只会起作用,我会得到我想要的东西.