我想优化一个涉及递归公式的计算:

#a, b, c are arrays of shape (N, )

a[0] = c[0]

for i in range(1, N):
    a[i] = a[i-1]*b[i] + c[i]

有没有一种方法可以通过优化的NumPy方法组合返回结果a?比如cumprodcumsumdot

推荐答案

No, this sort of algorithms are hard to vectorize (using just ). I recommend to look at . Example:

import numba
import numpy as np


@numba.njit
def compute(a, b, c):
    a[0] = c[0]

    for i in range(1, len(a)):
        a[i] = a[i - 1] * b[i] + c[i]


N = 10
a = np.empty(N, dtype="int64")
b = np.arange(1, N + 1, dtype="int64")
c = np.arange(10, N + 10, dtype="int64")

# note - when run for first time, numba compiles the function (this takes some time).
# Next runs numba uses already compiled function which is fast
compute(a, b, c)
print(a)

打印:

[      10       31      105      433     2179    13089    91639   733129
  6598179 65981809]

Python相关问答推荐

如何使用SubProcess/Shell从Python脚本中调用具有几个带有html标签的参数的Perl脚本?

比较两个二元组列表,NP.isin

Python 3.12中的通用[T]类方法隐式类型检索

我在使用fill_between()将最大和最小带应用到我的图表中时遇到问题

Django管理面板显示字段最大长度而不是字段名称

如何在Python中将returns.context. DeliverresContext与Deliverc函数一起使用?

非常奇怪:tzLocal.get_Localzone()基于python3别名的不同输出?

. str.替换pandas.series的方法未按预期工作

scikit-learn导入无法导入名称METRIC_MAPPING64'

pandas滚动和窗口中有效观察的最大数量

在线条上绘制表面

django禁止直接分配到多对多集合的前端.使用user.set()

如何在Raspberry Pi上检测USB并使用Python访问它?

在np数组上实现无重叠的二维滑动窗口

不允许访问非IPM文件夹

Maya Python脚本将纹理应用于所有对象,而不是选定对象

pandas:在操作pandora之后将pandora列转换为int

mdates定位器在图表中显示不存在的时间间隔

如何在信号的FFT中获得正确的频率幅值

一维不匹配两个数组上的广义ufunc