我最近开始用 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)。