2012-02-26 23 views
3

私はこれをループで実行しようとしていますが、実行にはかなりの時間(〜20秒)かかります。 XおよびYは長さの事前に定義されたベクトル2000000forループの高速化R

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) 
} 

ビットこれをスピードアップするために利用可能な任意のトリックですか?

EDIT:あなたは 'X'と `y`に割り当てられていないのはなぜsqrtf

答えて

5
n <- 2e6 
set.seed(101) 
a <- runif(n) 
b <- runif(n) 
sqrtf <- sqrt(-log10(b)) 
x <- sqrtf*cos(a) 
y <- sqrtf*cos(b) 
+0

を固定しましたか?あなたは決してそれらを使用しません。私は急いでいたので –

+0

。固定、ありがとう。 –

1

x <- sqrtexp*cos(runif(2e6))

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)