使用带有sympy的数字表达式来评估字符串?

时间:2014-03-10 18:21:28

标签: python sympy

我编写了一个用于评估拉格朗日插值多项式的数值表达式的函数:

#!/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),我会得到错误输出:

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

我明白这可能是因为字符串中有一个-1但是......我怎么能简单地得到表达式?

1 个答案:

答案 0 :(得分:1)

所有关于表达式(string到目前为止)都具有正确的格式:

我的algorithm wasn't OK

所以得到了:

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)

那只会有效,我会得到我想要的东西。