您好我正在尝试将以下递归伪代码定义转换为R中的函数式编程构造:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
return View();
}
}
我不知道如何在方程式中实现随机数?我可以使用循环吗?
答案 0 :(得分:0)
如果我正确地理解了你的问题,那么这样的事情应该有效(你也需要在你的递归关系中使用a[n], b[n]
等等,因为它们是向量):
set.seed(1)
W = 50
Z = 100
a <- sample(2:5,Z/2,replace=TRUE)
b <- 1/sample(8:32,Z,replace=TRUE)
c <- sample(1:8,W/2,replace=TRUE)/4
d <- 1/sample(40:48,W,replace=TRUE)
# The recurrence relations
#Z[n] = Z[n-1] + a*Z[n-1] - b*Z[n-1]-18*W[n-1]
#W[n] = W[n-1] + c*W[n-1]- d*W[n-1]
n <- 50
W <- rep(0, n)
Z <- rep(0, n)
# base values
W[1] = 1
Z[1] = 1
# generate Z[2:n]
sapply(2:n, function(i) {Z[i] <<- Z[i-1] + a[i-1]*Z[i-1] - b[i-1]*Z[i-1]-18*W[i-1]; Z[i]})
# [1] -1.405263e+01 -5.572595e+01 -2.755339e+02 -1.633522e+03 -4.719064e+03 -2.784248e+04 -1.651987e+05 -8.177336e+05 -4.054596e+06 -1.193853e+07
#[11] -3.541765e+07 -1.038918e+08 -5.139908e+08 -2.023839e+09 -1.205871e+10 -4.737349e+10 -2.343741e+11 -1.397564e+12 -5.450500e+12 -3.251505e+13
#[21] -1.930581e+14 -5.722794e+14 -2.825630e+15 -8.300287e+15 -3.276429e+16 -1.299650e+17 -3.854135e+17 -1.518983e+18 -9.057638e+18 -3.594750e+19
#[31] -1.417929e+20 -7.032929e+20 -2.771801e+21 -8.142166e+21 -4.853984e+22 -2.389653e+23 -1.424233e+24 -4.143225e+24 -2.042018e+25 -7.982434e+25
#[41] -4.728057e+26 -2.311494e+27 -1.377265e+28 -6.838835e+28 -3.394089e+29 -2.023882e+30 -5.965127e+30 -2.352911e+31 -1.168052e+32