python - Numpy:根据前一个元素计算?

标签 python numpy

假设我有数组 xy:

x = numpy.array([1,2,3,4,5,6,7,8,9,10])  # actual content is the a result of another calculation step

y有一个公式,每个元素都基于前一个元素,让i表示y的索引,每个元素是:

y[i] = y[i-1] * 2 + x[i]

计算第一个元素时,令y[i-1] = 50。换句话说,y 应该是:

[101, 204, 411, 826, 1657, 3320, 6647, 13302, 26613, 53236]

如何使用 numpy 计算 y

最佳答案

让我们在您的序列中构建一些项目:

y[0] = 2*y[-1] + x[0]
y[1] = 2*y[0] + x[1] = 4*y[-1] + 2*x[0] + x[1]
y[2] = 2*y[1] + x[2] = 8*y[-1] + 4*x[0] + 2*x[1] + x[2]
...
y[n] = 2**(n+1)*y[-1] + 2**n*x[0] + 2**(n-1)*x[1] + ... + x[n]

可能不是很明显,但您可以使用 numpy 构建上述序列,执行如下操作:

n = len(x)
y_1 = 50
pot = 2**np.arange(n-1, -1, -1)
y = np.cumsum(pot * x) / pot + y_1 * 2**np.arange(1, n+1)
>>> y
array([  101,   204,   411,   826,  1657,  3320,  6647, 13302, 26613, 53236])

这类解决方案的缺点是它们不是很通用:问题中的一个小改动可能会使整个方法变得无用。但是,只要你能用一点代数解决问题,它几乎肯定会远远超过任何算法方法。

关于python - Numpy:根据前一个元素计算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30068020/

相关文章:

python - 单线程的 ZeroMQ 进程间通信丢失消息

python - 沿 numpy 数组中的范围应用函数

python - 逆笛卡尔积 - 给定乘积,找到索引

python - 多维 numpy 矩阵的旋转和翻转

python - 绘制非对称误差线 Matplotlib

python - 从两个一维向量 a、b 创建 bool 数组 A,如果 a[i]==b[j],则 A[i,j] 为 True

Python pandas date_range 采样分别分配给每一天

python - jupyter 笔记本上找不到 PhantomJS

python - 如何在 Anaconda python 发行版上安装 AWSCLI

python - pip 安装 Flask-Ask 引发 ModuleNotFound pip.req