2013-02-16 294 views
1

我最近開始R中的編碼和偶然發現這個代碼,它繪製曼德爾布羅分形:如何在使用R繪圖時更改分辨率?

library(caTools)   # external package providing write.gif function 
jet.colors <- colorRampPalette(c("#00007F", "blue", "#007FFF", "cyan", "#7FFF7F", 
           "yellow", "#FF7F00", "red", "#7F0000")) 
m <- 1200    # define size 
C <- complex(real=rep(seq(-1.8,0.6, length.out=m), each=m), 
       imag=rep(seq(-1.2,1.2, length.out=m), m)) 
C <- matrix(C,m,m)  # reshape as square matrix of complex numbers 
Z <- 0     # initialize Z to zero 
X <- array(0, c(m,m,20)) # initialize output 3D array 
for (k in 1:20) {  # loop with 20 iterations 
    Z <- Z^2+C    # the central difference equation 
    X[,,k] <- exp(-abs(Z)) # capture results 
} 
write.gif(X, "Mandelbrot.gif", col=jet.colors, delay=100) 

我做了一些測試,看結果。我發現這些圖像的分辨率太低,所以我嘗試使用這些代碼來提高分辨率:本質上,它計算兩倍的功能(即f(1),f(1.5),f(2),f(2.5)而不是f(1),f(2)),我想。

library(caTools)   # external package providing write.gif function 
jet.colors <- colorRampPalette(c("#00007F", "blue", "#007FFF", "cyan", "#7FFF7F", 
           "yellow", "#FF7F00", "red", "#7F0000")) 
m <- 1200    # define size 
C <- complex(real=rep(seq(-1.8,0.6, length.out=m), each=m), 
       imag=rep(seq(-1.2,1.2, length.out=m), m)) 
C <- matrix(C,m,m)  # reshape as square matrix of complex numbers 
Z <- 0     # initialize Z to zero 
X <- array(0, c(m,m,20*2)) # initialize output 3D array 
for (n in 1:20) {  # loop with 20 iterations 
    for (m in 1:2) { # Loop twice 
    k <- n+m/2 # Does the trick of adding .5 
    Z <- Z^2+C    # the central difference equation 
    X[,,k] <- exp(-abs(Z)) # capture results 
    } 
} 
write.gif(X, "Mandelbrot.gif", col=jet.colors, delay=100) 

雖然它計算數字量的兩倍,的Mandelbrot.gif分辨率似乎是相同的,以及尺寸(爲1200x1200)。

+0

我沒有嘗試m的更多值,因爲它導致了一個太大的變量。 – 2013-02-16 12:39:49

回答

1

的分辨率提高了簡單地增加的m值。然而,在X元素的數目爲m^2 * 20,其可以很容易地變得大於2^31-1,其是向量長度的電流限制(一個陣列是具有附加屬性的向量)在R.要麼你找到一個不同的函數來創建GIF動畫,這並不需要保存的所有信息在一個陣列,或者您等待R的下一個重大更新,這將增加AFAIK對象大小限制。

下面的代碼允許更高的分辨率,但要注意,它需要大量的CPU時間,你會很快耗盡內存。你還需要ImageMagick。

library(animation)   # external package providing saveGIF function 
jet.colors <- colorRampPalette(c("#00007F", "blue", "#007FFF", "cyan", "#7FFF7F", 
           "yellow", "#FF7F00", "red", "#7F0000")) 
m <- 200    # define size 
C <- complex(real=rep(seq(-1.8,0.6, length.out=m), each=m), 
       imag=rep(seq(-1.2,1.2, length.out=m), m)) 
C <- matrix(C,m,m)  # reshape as square matrix of complex numbers 
Z <- 0     # initialize Z to zero 
saveGIF(
    for (k in 1:20) {  # loop with 20 iterations 
    Z <- Z^2+C    # the central difference equation 
    image(exp(-abs(Z)),col=jet.colors(255)) # plot results 
    },"Mandelbrot2.gif" 
)