# [SciPy-user] accumulate with custom functions

Matt Knox mattknox_ca at hotmail.com
Tue Dec 26 20:28:11 CST 2006

```>
> On Sun, Dec 24, 2006 at 11:17:30AM -0500, Matt Knox wrote:
> >
> > I work quite a bit with another language called FAME, which is very vector
based. In FAME I calculate
> exponentially weighted moving averages (exp mave) in the following way:
> >
> > suppose X is a 1 dimensional array, then to Calculate an exp mave I would
do:
> >
> > myExpMave = X
> > Case firstvalue(X)+1 to lastvalue(X) #sets global operating range
> > set myExpMave[N] = myExpMave[N-1] + k *
> > (myExpMave[N]-myExpMave[N-1])  #where k is some constant smoothing
> > factor, N is an index placeholder recognized by FAME
>
> This can be done with standard indexing:
>
> y = x[:-1] + k * (x[1:] - x[:-1])
>
> or
>
> y = x[:-1] + k * numpy.diff(x)
>
> You may also be interested in
>
> numpy.vectorize
>
> Cheers
> Stéfan
>

Hi Stéfan,

that's not quite what I was looking for actually. My description was a bit too
ambiguous I think.

I'll just describe it by example.

Suppose x = numpy.arange(20)
let k = 0.2

if y is the result, then

y[0] = x[0] + 0.2*(x[1] - x[0]) == 0 + 0.2*(1 - 0) = 0.2
y[1] = y[0] + 0.2*(x[2] - y[0]) == 0.2 + 0.2*(2 - 0.2) = 0.56
y[2] = y[1] + 0.2*(x[3] - y[1]) == 0.56 + 0.2*(3 - 0.56) = 1.048
y[3] = y[2] + 0.2*(x[4] - y[2]) == 1.048 + 0.2*(4 - 1.048) = 1.6384

etc...

Is their any way to do this kind of cumulative function in numpy? I tried
defining a function "def myfunc(a, b): return a + k * (b - a)" and using
numpy.vectorize on that, but it doesn't seem to give me an accumulate method
when I do that. Is writing a ufunc in C the only thing I can do here and get
good speed?

Thanks,

- Matt

```