I have got two loops I want to transform using some apply function in order to reduce the computation time. 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.
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.