[英]Evaluating a string with a numerical expression with sympy?
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: 当我用lagrange([0,1,2,4],[-1,0,7,63],3)
调用函数时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))
Which is actually OK, however, if I try sympify(expresion)
I get the error output: 这实际上没问题,但是,如果我尝试sympify(expresion)
我会得到错误输出:
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? 我明白这可能是因为字符串中有一个-1但是......我怎么能简单地得到表达式?
It's all about the expression ( string
so far) having a right format: 这是关于具有正确格式的表达式( string
到目前为止):
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. 那只会起作用,我会得到我想要的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.