你好我想下面的遞歸僞高清轉換成一個功能編程結構中R:轉換簡單的遞歸關係,以功能性程序
a = [ random numbers between 0 and 10 ]
b = [ random numbers between -5 and 5 ]
c = [ random numbers between 0 and -10 ]
x0 = 200
index = 0
function f(x) {
index = index + 1
if(x is between 200 and 220) return f(x + a[index])
else if(x is between 220 and 250) return f(x + b[index])
else if(x is 250 and above) return f(x + c[index])
}
可執行R代碼裏面是:
a <- sample(1:10,size=50, replace=TRUE)
b <- sample(-5:5,size=50, replace=TRUE)
c <- sample(-1:-10,size=50, replace=TRUE)
index <- 0;
myfunc <- function(x){
index <<- index + 1;
if(index == 50) return(x)
if(x <= 220){ return(myfunc(x + a[index])) }
else if(x > 220 & x < 250){ return(myfunc(x + b[index])) }
else {return(myfunc(x + c[index]))}
}
print(myfunc(200));
想討論任何方法,包括Map/Filter/Reduce或Vectorisation。提前謝謝了。此外,我如何保留50個x元素的整個路徑(而不是隻看x的一個答案)。
iiuc,你提到的所有這些功能在這裏都沒有用...... – Arun 2013-03-19 17:51:13
說實話,你的代碼看起來有點奇怪,目前還不清楚你想實現什麼。你能用統計術語解釋你想要模擬的隨機變量(或向量)嗎? 「50個元素的整個路徑」是什麼意思? – 2013-03-19 18:06:04
大家好,感謝您的期待。它是一個以200開頭的路徑相關值。然後根據x的前一個值(因此遞歸定義),它將在200到300之間移動50次。通過50個元素的整個路徑意味着我想通過函數myfunc知道x的所有中間值。例如,如果我使用for循環重寫了這個,我會聲明一個50的結果向量,然後在我到達我的最終值x之前迭代地填充它。你想讓我寫一個for-loop版本嗎? – user1480926 2013-03-19 18:10:53