Reputation: 3
I want tot write a program in R to compute a value, the program is below .
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. Can any one help me to solve this problem?
Upvotes: 0
Views: 114
Reputation: 37641
Your function has an infinite recursion in it.
When you compute P_n_m(r,n,m)
, you must compute both
P_n_m(r-n-m,n-1,m)
and P_n_m(r,n,m-1)
. Notice that
the second term only reduces m but leaves r and n unchanged.
That causes the infinite recursion.
Let's track your example, 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,5) which has to compute
P_n_m(49,7,4) which has to compute
P_n_m(49,7,3) which has to compute
P_n_m(49,7,2) which has to compute
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,0) we have m==0 but not n==1, both r & n > 0 so we need
P_n_m(49,7,-1) and now we need
P_n_m(49,7,m) down to negative infinity.
You need to rethink the definition of your function.
Upvotes: 2