是否可以矢量化 NumPy 数组的递归计算,其中每个元素都依赖于前一个元素? [英] Is it possible to vectorize recursive calculation of a NumPy array where each element depends on the previous one?
问题描述
T(i) = Tm(i) + (T(i-1)-Tm(i))**(-tau(i))
Tm
和 tau
是之前计算过的相同长度的 NumPy 向量,希望创建一个新的向量 T
.i
仅用于指示所需内容的元素索引.
Tm
and tau
are NumPy vectors of the same length that have been previously calculated, and the desire is to create a new vector T
. The i
is included only to indicate the element index for what is desired.
在这种情况下是否需要 for 循环?
Is a for loop necessary for this case?
推荐答案
你可能认为这行得通:
import numpy as np
n = len(Tm)
t = np.empty(n)
t[0] = 0 # or whatever the initial condition is
t[1:] = Tm[1:] + (t[0:n-1] - Tm[1:])**(-tau[1:])
但事实并非如此:您实际上不能以这种方式在 numpy 中进行递归(因为 numpy 计算整个 RHS,然后将其分配给 LHS).
but it doesn't: you can't actually do recursion in numpy this way (since numpy calculates the whole RHS and then assigns it to the LHS).
所以除非你能想出这个公式的非递归版本,否则你会陷入一个显式循环:
So unless you can come up with a non-recursive version of this formula, you're stuck with an explicit loop:
tt = np.empty(n)
tt[0] = 0.
for i in range(1,n):
tt[i] = Tm[i] + (tt[i-1] - Tm[i])**(-tau[i])
这篇关于是否可以矢量化 NumPy 数组的递归计算,其中每个元素都依赖于前一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!