Reputation: 11690
Since I got the advice to make another question here it goes... I want to plot the sum, and I have a code:
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()
But I get the error
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'
So what seems to be the problem? It has got to do something with array, but I don't know what :\
EDIT: The picture, in Mathematica looks like this:
Upvotes: 0
Views: 637
Reputation: 64022
I don't understand what that generator expression is doing at the end of the return statement in f1
, but this:
a=4
t = linspace(0, 35, 1000)
y1 = numpy.array([f1(t_i) for t_i in t])
should get you somewhere. What it does is create a new numpy.array
by looping through t
, calling f1
on each value and building a list from the results. This way the t
inside f1
is a single number rather than the whole array at once, which means that your arithmetic can be properly applied to it.
Upvotes: 1
Reputation: 76985
You can't divide a numpy.ndarray
by a numpy.float64
. This is the problematic code:
return 0.5*(1 + sum( (a**(2*n)*cos(2*sqrt(1 + n)*t))/(e**a**2*factorial(n))
Upvotes: 1