我很好奇,是否有一种快速的方法可以计算Python中给定数组的累加乘积。我了解numpy同时具有cumsum
和cumprod
函数,但似乎都不适合我的情况。我的迭代序列如下,其中 t 是时间索引:
X_ {t + 1} = X_ {t} *(B_ {t + 1}-B_ {t})+ X_t
任何建议将不胜感激。
答案 0 :(得分:3)
在这种解决方案中,我将假定向量B是已知的。 X的方程可以简化如下
X_(t+1) = (B_(t+1) - B_t) X_t + X_t
X_(t+1) = ((B_(t+1) - B_t) + 1) X_t
let C = B[1:] - B[:-1] + 1.
现在动态方程是
X_(t+1) = C_t X_t
观察方程的行为
X_1 = C_0 X_0
X_2 = C_1 C_0 X_0
X_3 = C_2 C_1 C_0 X_0
从上面的模式中,我们得到
X_n = C_(n-1) ... C_0 X_0
这意味着,如果您只是在特定状态之后,则无需显式计算每个先前状态。
要获得numpy数组中元素的乘积,只需使用numpy.prod
。以下代码段显示了如何计算给定点的X以及如何计算t
import numpy as np
# provide for B and X_0 yourself.
C = B[1:] - B[:-1] + 1
X = np.cumprod(C) * X_0 # compute the entire X vector at once.
X_5 = np.prod(C[:5]) * X_0 # compute X_5 only
就是这样!没有明确的循环或递归。
答案 1 :(得分:0)
尝试一下。由于每次都要计算X_2,X_3,....,因此应该使用循环,但是B_diff([B_2-B_1,B_3-B_2,...])会被预先有效地计算。
def make_X(initial_X, B):
B_diff = B[1:] - B[:-1] + 1
X = [initial_X]
for t in range(len(B_diff)):
next_X = B_diff[t] * X[-1]
X.append(next_X)
return X
# Test
make_X(1, np.array([1, 2, 3, 4]))
答案 2 :(得分:0)
最终决定使用numpy apply自定义函数,因为我需要在矩阵中使用它:
# for calculating the series
def myFunc(arr:np.array, initial:int, size:int):
temp = initial
new_arr = [0]*size
for i in range(size):
new_arr[i] = temp + (temp * arr[i])
temp += temp * arr[i]
return np.array(new_arr)
# for implementing it across my matrix
np.apply_along_axis(myFunc, 0, arr, initial, size)