[英]Why does it take so much time for R to compute m for loop with basic calculations?
Why does the computation of the following code in R take so much time?为什么在 R 中以下代码的计算需要这么长时间? It takes many minutes, so I have interruped the calculations.
这需要很多分钟,所以我中断了计算。
My aim is to adapt my simulated random numbers ( sumzv
, dim(sumzv) = 1000000 x 10) to my market model S_t
(geometric brownian motion).我的目标是使我的模拟随机数(
sumzv
, dim(sumzv) = 1000000 x 10)适应我的市场 model S_t
(几何布朗运动)。 The vectors m
and s
describe the drift and the deviation of the GBM and are vectors containing 10 numbers.向量
m
和s
描述了GBM的漂移和偏差,是包含10个数字的向量。 DEL
is the variable for the time steps. DEL
是时间步长的变量。 S_0
is a vector containing 10 stock prices at time 0. S_0
是一个包含 10 个股票在时间 0 的价格的向量。
n <- 1000000
k <- 10
S_t <- data.frame(matrix(0, nrow = n, ncol = k))
i <- 1
j <- 1
t <- 10
for (j in 1:k) {
for (i in 1:n) {
S_t[i, j] <- S_0[j] * exp(m[j] * t * DEL + s[j] * sqrt(DEL) * sumzv[i, j])
}
}
Thank you for your help.谢谢您的帮助。 Please keep in mind that I'm a beginner:)
请记住我是初学者:)
Unfortunately, I couldn't find any helpful information so far on the inte.net.不幸的是,到目前为止我在 inte.net 上找不到任何有用的信息。 Some pages said, vectorization is helpful to speed up an R Code, but this doesn't seem helpful to me.
有些页面说,矢量化有助于加速 R 代码,但这对我来说似乎没有帮助。 I tried to break down the data frames into vectors but this got very complex.
我试图将数据帧分解为向量,但这变得非常复杂。
The following code with vectorized inner loop is equivalent to the posted code.以下带有矢量化内循环的代码等同于发布的代码。
It also pre-computes some inner loop vectors, fac1
and fac2
.它还预先计算了一些内部循环向量
fac1
和fac2
。
S_t <- data.frame(matrix(0, nrow = n, ncol = m))
fac1 <- m * t * DEL
fac2 <- s * sqrt(DEL)
for (j in 1:k) {
S_t[, j] <- S_0[j] * exp(fac1[j] + fac2[j] * sumzv[, j])
}
The fully vectorized version of the loop on j
above is the one-liner below.上面
j
上循环的完全矢量化版本是下面的单行代码。 The transposes are needed because R is column major and we are multiplying by row vectors indexed on j = 1:k
.需要转置,因为 R 是主要列,我们乘以索引为
j = 1:k
的行向量。
S_t2 <- t(S_0 * exp(fac1 + fac2 * t(sumzv)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.