Mandelbrot Set, evolved

September 30, 2010

(This article was first published on Revolutions, and kindly contributed to R-bloggers)

The Mandelbrot Set is perhaps the most famous fractal of all time. It's simple in its definition: iterate the complex equation zn+1 = zn2 + c (starting with z0 = 0) for various values of c, and if doesn't go to infinity then c is part of the Mandelbrot Set. The result, however, is amazingly complex. Thinking of c as defining a 2-dimensional area, the boundary of set (between where z does and does not zoom to infinity) is infinitely crenellated. And if you decorate the interior of the set with colors defined by the absolute value of z after N iterations, beautiful patterns emerge.

Because complex numbers are natural data types in the R language, it's easy to generate the Mandelbrot Set in just a few lines of code. And it's very quick, because each iteration is done over an entire grid of c values in a single statement. The code can be found in R's Wikipedia page (and reproduced after the jump). You've probably seen the Mandelbrot set before, but you may never have seen how it evolves from one iteration to the next. The R code below shows us by using the caTools package to creare an animated GIF.

Mandelbrot animation 


Wikipedia: R Programming Language, Example 2

library(caTools)  # external package providing write.gif function
jet.colors = colorRampPalette(c("#00007F", "blue", "#007FFF", "cyan", "#7FFF7F", 
        "yellow", "#FF7F00", "red", "#7F0000")) 
m = 600     # 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)

To leave a comment for the author, please follow the link and comment on their blog: Revolutions. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: ,

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)