简体   繁体   English

使用apply R的递归循环

[英]recursive loop using apply R

I have got two loops I want to transform using some apply function in order to reduce the computation time. 我有两个循环,我想使用一些Apply函数进行转换,以减少计算时间。 First one seems easy to do, the problem arises with the second one because the S is updated with its own value in each iteration. 第一个似乎很容易做到,第二个问题就出现了,因为S在每次迭代中都用自己的值进行更新。

S0   = 100
a    = 0.00016
b    = 0.0126
sim    = 10000 
drifts = 1000
Si = rep(0,sim)

for(i in (1:sim))
{
 S =  S0
 for (j in (1:drifts))
  {
   z = rnorm(1, mean = 0, sd = 1)
   S = S * exp(a + b*z)
  }
  Si[i] =S 
}

Can anyone help? 有人可以帮忙吗?

calc_s <- function(S, i = 1) {
  S <- S * exp(a + b * rnorm(1, mean = 0, sd = 1))
  return (if (i < drifts) calc_s(S, i + 1) else S)}
S2 <- sapply(1:sim, function(x) {
  calc_s(S0)
})

It isn't faster though 虽然不快

How about something like the code below. 下面的代码怎么样? I have replaced the j-loop with a product, I think the math is correct. 我已经用产品替换了j循环,我认为数学是正确的。

sapply(1:sim,function(x) S0*prod(exp(a + b*rnorm(drifts))))

it is also significantly faster: 它也明显更快:

> system.time(for(i in (1:sim))
+ {
+   S =  S0
+   for (j in (1:drifts))
+   {
+     z = rnorm(1, mean = 0, sd = 1)
+     S = S * exp(a + b*z)
+   }
+   Si[i] =S 
+ }
+ )
   user  system elapsed 
  23.29    0.02   23.34 
> 
> system.time(Si<-sapply(1:sim,function(x) S0*prod(exp(a + b*rnorm(drifts)))))
   user  system elapsed 
   1.76    0.00    1.76 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM