我是python的新手,我正在努力编写一个递归函数。我在Matlab中有以下几行动态编程函数的代码,这些代码是一位教授举的例子:
function [policy,fstar] =StochasticInventoryControl(N,K,c,h,M,g,Dmax,p)
fstar=zeros(M+1,N+1);
for n=N:-1:1
for s=0:M
for x=0:M-s
temp=0;
for d=0:Dmax
temp=temp+p(d+1)*(g*min(s+x,d)+fstar(1+max(s+x-d,0),n+1));
end
f(1+s,1+x)=-K*(x>0)-c*x-h*(s+x)+temp;
end
[fstar(1+s,n),policy(1+s,n)]=max(f(1+s,1:M-s+1));
end
end
policy=policy-1;
end我正在尝试用python重写相同的函数,我想出了下面的代码:
def StochasticInventoryControl(N, K, c, h, M, g, Dmax, p):
fstar = zeros(M + 1, N + 1)
for n in range (N, 1, -1):
for s in range (0, M):
for x in range (0, M - s):
temp = 0
for d in range (0, Dmax):
temp = temp + p(d + 1)*(g*min(s + x, d) + fstar(1 + max(s + x - d,0), n + 1))
f(1 + s, 1 + x).lvalue = -K * (x > 0) - c * x - h * (s + x) + temp
[fstar(1 + s, n), policy(1 + s, n)] = max(f(1 + s, n in range (1, M - s + 1))最后一行是错误的,我知道我不能在python中以这种方式定义函数的递归关系。我应该如何写python中的最后一行?
发布于 2017-05-03 05:46:24
首先,你的索引和范围是关闭的。与大多数编程语言一样,python索引和范围从0开始,并且范围是半开放的(它们排除了最后一个值),因此您需要在范围中考虑到这一点。
其次,f(s,x)使用方括号进行索引,所以它应该是f[s,x]而不是numpy。
第三,您可以像在MATLAB中一样在numpy数组中进行切片,但您需要考虑索引的差异,以及x:y:z索引的最后一个元素是Python中的步长,而MATLAB中的中间元素是。
第四,缩进在Python中很重要,因此内部循环需要再缩进一层才能像在MATLAB中一样工作。
至于你关于最后一行最后一行的问题,numpy中没有一个函数可以同时处理最大值和最大索引。您需要使用np.max作为值,使用np.argmax作为索引,如下所示:
fstar[s, n-1] = np.max(f[s, :M-s+1])
policy[s, n-1] = np.argmax(f[s, :M-s+1])+1或者更好地使用numpy方法:
fstar[s, n-1] = f[s, :M-s+1].max()
policy[s, n-1] = f[s, :M-s+1].argmax()+1https://stackoverflow.com/questions/43728734
复制相似问题