Home > Software design >  Brownian Motion / loop in R
Brownian Motion / loop in R

Time:12-17

I want to implete the function of the Wiener representation in R (see https://en.wikipedia.org/wiki/Wiener_process#Wiener_representation). (I want to implement the first formulae) When plotting this function it should look more similar to the standard brownian motion the higher the dimension of the random vector is, and the lower it should look smoother. I have tried to implement it, but I think there is a mistake somewhere in the loop, because the graphs do not should look much more like a brownian motion when n is high, I even went as high as 10000 there isn't enough fluctation inside each graph

brownmotion <- function(n, time=1000){
W <- rep(0, time)

Wp1 <- rep(0, time)
Wp2 <- 0
X <- seq(0, 1, length.out = time)

xsi <- rnorm(n)
for ( i in 1:length(X)){
for (j in 1:n){
  Wp1[i] <- X[i]*xsi[1]
  Wp2 <- Wp2   xsi[j]*sin(j*X[i]*pi)/(j*pi)
  
  W[i] <- Wp1[i]   sqrt(2)*Wp2
}

}
return (W)
 }

CodePudding user response:

Since this is R, this is better done without loops:

brownmotion <- function(n, time=1000){
  X <- seq(0, 1, length.out = time)
  xsi <- rnorm(n   1)
  W <- xsi[1] * X   sqrt(2) * colSums(xsi[-1] * sin(pi * 1:n %*% t(X)) / (pi * 1:n))
  return (W)
}

When coding this, I noticed a small error in your original code in that you use xsi[1] twice. I avoided this by making xsi length n 1, so xsi[1] could be the initial value and there are still n values left.

  • Related