本文介绍了是否可以对每个元素都依赖于前一个元素的NumPy数组进行矢量化递归计算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

T(i) = Tm(i) + (T(i-1)-Tm(i))**(-tau(i))

Tmtau是先前已计算出的相同长度的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数组进行矢量化递归计算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-17 01:05