尝试绘图时python中的语法无效

时间:2011-05-23 17:40:42

标签: python syntax plot

在我使用无穷阶乘和XD的错误后,我重新编写了代码,但我一直收到语法错误:\

from scitools.std import *
from math import factorial, cos, e
from scipy import *
import numpy as np


def f1(t):
    return 0.5*(1 + sum( (a**(2*n)*cos(2*sqrt(1 + n)*t))/(e**a**2*factorial(n)) for n in range(0,100)))

a=4
t = linspace(0, 35, 1000)
y1 = f1(t)

plot(t, y1)

xlabel(r'$\tau$')
ylabel(r'P($\tau$)')
legend(r'P($\tau$)')
axis([0.0, 35.0, 0.0, 1.0])
grid(True)
show()

它说我的程序有错误:语法无效,a为红色:\

现在怎么了? :(

编辑:

我已经添加了另一个)在总和的末尾,但现在我不断收到巨大的错误:

Traceback (most recent call last):
  File "D:\faxstuff\3.godina\kvantna\vježbe\qm2\v8\plot.py", line 12, in <module>
    y1 = f1(t)
  File "D:\faxstuff\3.godina\kvantna\vježbe\qm2\v8\plot.py", line 8, in f1
    return 0.5*(1 + sum( (a**(2*n)*cos(2*sqrt(1 + n)*t))/(e**a**2*factorial(n)) for n in range(0,100)))
  File "C:\Python26\lib\site-packages\numpy\core\fromnumeric.py", line 1415, in sum
    res = _sum_(a)
  File "D:\faxstuff\3.godina\kvantna\vježbe\qm2\v8\plot.py", line 8, in <genexpr>
    return 0.5*(1 + sum( (a**(2*n)*cos(2*sqrt(1 + n)*t))/(e**a**2*factorial(n)) for n in range(0,100)))
TypeError: unsupported operand type(s) for /: 'numpy.ndarray' and 'numpy.float64'

我是否应该使sum表达式返回一个我可以绘制的数组或?

1 个答案:

答案 0 :(得分:4)

return 0.5*(1 + sum(...中的括号不均衡。

作为一种风格问题,我建议避免使用from <module> import *式导入。在您的特定示例中,您最终会导入一个导入全局命名空间的单字母变量名称(e),然后您可以继续使用该名称。这可能会导致混淆,更糟糕的是,难以诊断错误。