How do I vecture this calculation in numpy
Nothing, there is a trick ufunc
that works if you are doing any algebra. In this case, it ufunc
is multiply
a trick accumulate
.
c = np.r_[np.multiply.accumulate(b[0:-1][::-1])[::-1], 1]
total2 = np.sum(a * c)
What it is: Algebraically, you sum a[i]
multiply times b[i:]
by for i in range(a.size)
. To do this, turn over b
and get the launched product of everything but the last number (assuming a
both b
are the same length), and then put it back. The last value should be 1 because the final value is a
just added.
Testing
a = np.random.randint(1, 10, 40) b = 1 + np.random.rand(40) total = a[0] for ix in range(1, len(a)): total = total*b[ix-1] + a[ix] total 278443993.10494208 total2 278443993.10494208
source to share