Closed
Description
Following on from discussion in #11534, this uses a list comprehension in the following function:
def function(amplitudes):
def f(t):
x1 = amplitudes[0]
result = x1 / sqrt(2.0)
harmonic = 1.0
for x_even, x_odd in zip(amplitudes[1::2], amplitudes[2::2]):
result += (x_even * np.sin(harmonic * t) +
x_odd * np.cos(harmonic * t))
harmonic += 1.0
if len(amplitudes) % 2 != 0:
result += amplitudes[-1] * np.sin(harmonic * t)
return result
return f
As both amplitudes
and t
are numpy ndarrays
, there is probably some performance gain to be had from vectorising the loop.
My numpy
knowledge and available time aren't sufficient to make this entirely trivial. I came across the following issues in particular:
- Basic slices of
numpy ndarrays
return views rather than copies, which then can't be subject to manynumpy
operations (i.e.np.resize
). - Addressing
amplitudes
in the inner scope assigns the name in the inner scope (see here for details). This causes anamplitudes is not defined
exception.