“'符号'对象不支持索引”错误

时间:2014-12-17 23:19:41

标签: python sympy

我有一个功能:

def s(x):
    t = lambda a: a*sp.sin(3.0/a)
    return t(x)

我正在尝试从0到2进行集成。当函数s(x)与我正在执行的操作位于同一文件中时,我得到了正确的答案。例如,当我有文件时:

def s(x):
    t = lambda a: a*sp.sin(3.0/a)
    return t(x)

x = sp.Symbol('x')

d_s = lambda a: sp.integrate(s(x), x)
print((d_s(x).subs(x,2) - sp.limit(d_s(x), x, 0)).evalf(25))

我得到了正确的值,即1.099并且有些变化。但是,如果我没有将它们全部放在同一个文件中,则会出现'Symbol' object does not support indexing错误。以下是导致问题的代码:

import HW8
# Finding exact values of integrals
x = sp.Symbol('x')
p_exact = sp.integrate(HW8.p(x), (x, 0, 2)).evalf(25)
q_exact = sp.integrate(HW8.q(x), (x, 0, 2)).evalf(25)

# Have to do something special for s(x) due to the discontinuity at x = 0
s_int = lambda x: sp.integrate(HW8.s(x), x)
s_exact = (s_int(x).sub(x,2) - sp.limit(s_int(x), x, 0)).evalf(25)
print(s_exact)

以下是包含函数的HW8代码:

import sympy as sp

def p(x):
    result = 0.5 + x * (2.0 - x)
    return result

def q(x):
    result = 2.0 + x * (-8.0 + x * (14.0 + x * (-7.0 + x)))
    return result

def s(x):
    t = lambda a: a*sp.sin(3.0/a)
    return t(x)

这是一个追溯:

s(x)
     12     t = lambda a: a*sp.sin(3.0/a)
     13     return t(x)

TypeError: 'Symbol' object does not support indexing 

<lambda>(x)
     11 
     12 # Have to do something special for s(x) due to the discontinuity at x = 0
---> 13 s_int = lambda x: sp.integrate(HW8.s(x), x)
     14 s_exact = (s_int(x).sub(x,2) - sp.limit(s_int(x), x, 0)).evalf(25)
     15 print(s_exact)

<module>()
     12 # Have to do something special for s(x) due to the discontinuity at x = 0
     13 s_int = lambda x: sp.integrate(HW8.s(x), x)
---> 14 s_exact = (s_int(x).sub(x,2) - sp.limit(s_int(x), x, 0)).evalf(25)
     15 print(s_exact)
     16 

execfile(fname, glob, loc)
    195             else:
    196                 filename = fname
--> 197             exec compile(scripttext, filename, 'exec') in glob, loc
    198     else:
    199         def execfile(fname, *where):

我已经在没有实现s(x)的情况下测试了这段代码,它没有给我任何错误并且执行完美。

我能否对为什么发生这种情况有所了解?

1 个答案:

答案 0 :(得分:0)

我在代码中的任何地方都看不到会导致这种情况。错误消息来自使用符号上的方括号语法,例如x[1] x = Symbol('x')