I am learning to vectorize my code, which is currently suffering from severe time issues. My goal is to get rid of all the loops that slow down the process. This has worked fine whenever I did not need to know the result of step i to calculate step i+1.
At one point, this does not hold true anymore. I tried to break down the problem to this simplified snippet:
x2 = np.arange(10)
f1, sumint = 0.0, 0.0
for i in x2:
f2 = np.exp(x2[i]) + f1
sumint += f2
f1 = f2
The term np.exp(x2[i])
can of course be calculated for the whole matrix. But f1 is a term which carries the result of i-1 which I do not know in advance (or, do I?)
I am looking for a numpy-solution to this problem, because the real code involves more complex calculations and more of the variables like f1. I am aware of numpy.vectorize
but the docs say that this does not speed up the code, but rather assists readibility.
Edit: Maybe this example is more suitable to show my actual case...
x2 = np.random.rand(10)
y2 = np.random.rand(10)
f2 = np.random.rand(10)
sumint, f1, x1, y1 = 0, 0, 0, 0
for i in range(10):
sumint += (f2[i] - f1) * (x2[i] - x1) / (y2[i] - y1)
x1 = x2[i]
y1 = y2[i]
f1 = f2[i]
Edit 2: Sorry for that, I found the solution. By breaking down the problem to its core I found that what I thought of a recursion was just a SHIFT. Solution to the problem was:
f1 = np.zeros(10)
x1 = np.zeros(10)
y1 = np.zeros(10)
x1[1:] = x2[:-1]
y1[1:] = y2[:-1]
f1[1:] = f2[:-1]
sumint = (f2 - f1) * (x2 - x1) / (y2 - y1)
which I can now apply to the real case.