我正在寻找运行这个for循环,但是执行需要不可接受的长时间(~20s)。 x和y是长度为2000000的预定义矢量。
for(i in 1:2000000)
{
a <- runif(1)
b <- runif(1)
sqrtf <- sqrt(-log(b,10))
x[i] <- sqrtf*cos(a)
y[i] <- sqrtf*cos(b)
}
有什么技巧可以加快这一点吗?
编辑:修正了sqrtf
答案 0 :(得分:5)
n <- 2e6
set.seed(101)
a <- runif(n)
b <- runif(n)
sqrtf <- sqrt(-log10(b))
x <- sqrtf*cos(a)
y <- sqrtf*cos(b)
答案 1 :(得分:3)
# just so you don't have to write 2000000 over and over
n <- 2e6
# so the results are replicable
set.seed(0)
# the meat and potatoes... this is "vectorized" code that you'll hear lots about
# as you study R
a <- runif(n)
b <- runif(n)
sqrtf <- sqrt( -log10(b) )
x <- sqrtf * cos(a)
y <- sqrtf * cos(b)
答案 2 :(得分:1)
x <- sqrtexp*cos(runif(2e6))