#
#
#跑出一樣本數為n的布朗運動圖nIter張,512張太多了會當,改為3張
Brownian <- function(n = 11, pause = 0.05, nIter = 3, ...) {
    x = rnorm(n)
    y = rnorm(n)
    i = 1
    while (i <= nIter) {
        plot(x, y, ...)
        text(x, y, cex = 0.5)
        x = x + rnorm(n)
        y = y + rnorm(n)
##當作系統暫停Sys.sleep()的秒數,右大括號,表示迴圈結束
        Sys.sleep(pause)
        i = i + 1
    }
} 
###

## test it畫圖出來
Brownian(xlim = c(-20, 20), ylim = c(-20, 20), 
    pch = 21, cex = 2, col = "cyan", bg = "lavender") 

###
##不使用while迴圈的寫法,參考網路作法,原來是用repeat代替,如果拿掉i <= nIter的張數指令,剩下隨機rnorm(n)的話,指令會卡住而無法繼續跑,設定nIter = 3張,卻不知道為何最後只有出現2張,是因為if(i >= nIter) break...
Brownian <- function(n = 20, pause = 0.05, nIter = 3, ...) {
    x = rnorm(n)
    y = rnorm(n)
    i = 1
    repeat {
      plot(x, y, ...)
      text(x, y, cex = 0.5)
      x = x + rnorm(n)
      y = y + rnorm(n)
      Sys.sleep(pause)
      i = i + 1
      if(i >= nIter) break
    }
} 
Brownian(xlim = c(-20, 20), ylim = c(-20, 20), 
    pch = 21, cex = 2, col = "cyan", bg = "lavender")