# [Numpy-discussion] custom accumlators

Karol Langner karol.langner at kn.pl
Sat Jan 6 01:44:30 CST 2007

```On Friday 05 of January 2007 19:29, Matt Knox wrote:
> > On Friday 05 of January 2007 17:42, Matt Knox wrote:
> > > ---------------------------------------------
> > > Example 1 - exponential moving average:
> > >
> > > # naive brute force method...
> > > def expmave(x, k):
> > >     result = numpy.array(x, copy=True)
> > >     for i in range(1, result.size):
> > >        result[i] = result[i-1] + k * (result[i] - result[i-1])
> > >     return result
> > >
> > > # slicker method (if it worked, which it doesn't)...
> > > def expmave(x, k):
> > >     def expmave_sub(a, b):
> > >         return a + k * (b - a)
> > >     return numpy.vectorize(expmave_sub).accumulate(x)
> >
> > Why can't you simply use list comprehensions? Too slow?
> >
> > For example:
> > def expmave(x, k):
> > 	return [x[0]] + [x[i-1] + k*(x[i]-x[i-1]) for i in range(1,len(x))]
> >
> > Karol
>
> That's not the same calculation. There is no cumulative effect in your
> function.
>
> Each iteration depends on the previous iteration, like a cumulative sum,
> etc.
>
> And as for the speed, I'm basically trying to determine what is the most
> efficient way to do it, outside of writing it in C. And I don't really want
> to create intermediate lists, ideally things would be kept as numpy arrays.
> I can't think of a loop free way to do it with numpy.
>
> Good try though. No harm in trying! That's the only way we learn things.

You're right, I didn't think that throught. Sorry.

--
written by Karol Langner
Sat Jan  6 08:43:50 CET 2007
```