1

我最近开始用 R 编写代码,偶然发现了这段代码,它绘制了一个 Mandelbrot 分形:

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

4

1 回答 1

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"  
)
于 2013-02-16T13:42:05.050 回答