尝试绘制总和时python中的TypeError

时间:2011-05-23 19:24:22

标签: python plot sum

因为我在这里得到了另一个问题的建议,所以...我想绘制总和,我有一个代码:

from scitools.std import *
from math import factorial, cos, e, sqrt
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()

但是我收到了错误

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'

那么似乎是什么问题?它必须对数组做些什么,但我不知道是什么:\

编辑:Mathematica中的图片如下所示: image

2 个答案:

答案 0 :(得分:1)

您无法将numpy.ndarray除以numpy.float64。这是有问题的代码:

return 0.5*(1 + sum( (a**(2*n)*cos(2*sqrt(1 + n)*t))/(e**a**2*factorial(n))

答案 1 :(得分:1)

我不明白生成器表达式在f1的return语句结尾处做了什么,但是这个:

a=4
t = linspace(0, 35, 1000)
y1 = numpy.array([f1(t_i) for t_i in t])

应该让你到处找个地方。它的作用是通过循环numpy.array创建一个新的t,在每个值上调用f1并根据结果构建一个列表。这样t内的f1是一个数字,而不是整个数组,这意味着您的算术可以正确应用于它。