[英]How to write a double recursive function in R
I want tot write a program in R to compute a value, the program is below . 我想在R中编写一个程序来计算值,该程序如下。
options( expressions = 5e5 )
P_n_m=function(r,n,m) {
if(r >0 & n==1 & m==0 | r >=0 & n==0 & m==1) return(1)
else if(r >= 0 & n >= 0 | r >= 0 & m >= 0){
return(n/(n+m)*P_n_m(r-n-m,n-1,m)+m/(n+m)*P_n_m(r,n,m-1))
}
else return(0)
}
But it always give me error. 但这总是给我错误。 I also try to adjust system setting, but it still didn't work.
我也尝试调整系统设置,但仍然无法正常工作。 I want to compute P_n_m(49,7,7), and I don't know which part in program is wrong.
我想计算P_n_m(49,7,7),但我不知道程序中哪一部分是错误的。 Can any one help me to solve this problem?
谁能帮我解决这个问题?
Your function has an infinite recursion in it. 您的函数具有无限递归。
When you compute P_n_m(r,n,m)
, you must compute both P_n_m(rnm,n-1,m)
and P_n_m(r,n,m-1)
. 计算
P_n_m(r,n,m)
,必须同时计算P_n_m(rnm,n-1,m)
和P_n_m(r,n,m-1)
。 Notice that the second term only reduces m but leaves r and n unchanged. 注意,第二项仅减少m,而使r和n不变。 That causes the infinite recursion.
这导致无限递归。
Let's track your example, P_n_m(49,7,7). 让我们跟踪您的示例P_n_m(49,7,7)。 It will have to compute (among other things)
它将必须计算(除其他事项外)
P_n_m(49,7,6) which has to compute P_n_m(49,7,6)必须计算
P_n_m(49,7,5) which has to compute P_n_m(49,7,5)必须计算
P_n_m(49,7,4) which has to compute P_n_m(49,7,4)必须计算
P_n_m(49,7,3) which has to compute P_n_m(49,7,3)必须计算
P_n_m(49,7,2) which has to compute P_n_m(49,7,2)必须计算
P_n_m(49,7,1) we have m==1 but not n==0, both r & n > 0 so we need P_n_m(49,7,1)我们有m == 1但没有n == 0,r&n> 0,所以我们需要
P_n_m(49,7,0) we have m==0 but not n==1, both r & n > 0 so we need P_n_m(49,7,0)我们有m == 0但没有n == 1,r&n> 0,所以我们需要
P_n_m(49,7,-1) and now we need P_n_m(49,7,-1)现在我们需要
P_n_m(49,7,m) down to negative infinity. P_n_m(49,7,m)降至负无穷大。
You need to rethink the definition of your function. 您需要重新考虑函数的定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.