|
From: David S. <dsc...@vi...> - 2002-01-08 15:08:56
|
> (Even looking back, I still don't see in the NumPy
> documentation just why this works. It looks to me from the
> documentation that only "ufuncs" operate on arrays
> element-by-element, not arbitrary user-defined functions.
> Yet the actual behavior is exactly what I want in this case.)
Python will of course allow you to call a function with parameters of
any type, including arrays. So the call
pulse.gcurve.pos[:,1] = yt(x, t)
to the function
def yt(x,t):
ytotal = 0.0
for k in arange(1.0, 4.0, 0.05):
ytotal = ytotal + sin(k * x - w(k) * t)
return ytotal
is just like writing
ytotal = 0.0
for k in arange(1.0, 4.0, 0.05):
ytotal = ytotal + sin(k * x - w(k) * t)
pulse.gcurve.pos[:,1] = ytotal
The only operations that operate on the array x in this code are
arithmetic operators and sin, which is a ufunc. So it works fine. If
yt() attempted to do something with x that isn't supported for arrays,
you would get a TypeError at that point.
Incidentally, if you wanted to eliminate the "for k" loop as well, you
can do it with more Numeric code:
def yt(x,t):
k = arange(1.0, 4.0, 0.05)[:,NewAxis]
return sum( sin(k * x - w(k) * t) )
and, of course, you could calculate k and w(k) just once. But since
readability was one of your goals, I didn't recommend it. (If you want
to use this code, you will have to change the first call yt(x,t) in the
plotting loop to yt(x,t)[0], since ytotal comes back a rank-1 array
instead of a scalar)
Dave
|