<- function(c, z = complex(r = 0, i = 0), n = 0, lim = lim){
Mandelbrot_count <- n + 1
n <- z * z + c
z if( abs(z) > 2 | n > lim ){
return(n)
}# Recurse until return criteria are met
Mandelbrot_count(c = c, z = z, n = n, lim = lim)
}
Introduction
In this brief post, we will take a look at how we can visualise the Mandelbrot set using recursion in R
. The set looks like this (click the image to enlarge):
This post was inspired by this excellent Numberphile video featuring Dr. Holly Krieger. Below, we will go over the code, but skip the mathematics, as these are covered in the video.
Functions
Each pixel in the final image is a count, so we need to create a function, which computes the count for a given input c
, not how we are using recursion to solve the problem:
Next, we need to create a function, which can compute the pixels of the final visualisation:
<- function(res, lim){
Mandelbrot_matrix <- seq(-2, 0.5, len = res) # Values along the complex a-axis
A <- seq(-1.2, 1.2, len = res) # Values along the complex b-axis
B <- matrix(0, nrow = res, ncol = res) # Prebuild mandelbrot count matrix
mb
# Each pixel in the final picture is a count, generate counts
for( i in 1:res ){
for( j in 1:res ){
<- Mandelbrot_count(c = complex(r = A[i], i = B[j]), lim = lim)
mb[i,j]
}
}
# Done, return
return(mb)
}
Computation
Now, we can generate the count matrix of the mandelbrot set:
# - res [Pixel resolution res x res]
# - lim [Bail out limit for max number of iterations]
<- 2048
res <- 128
lim <- Mandelbrot_matrix(res = res, lim = lim) mb
Visualisation
Lastly, we can generate the visualisation of the mandelbrot set:
# Set colour palette
<- c("darkblue", "lightblue", "white", "yellow", "orange", "black")
palette <- colorRampPalette(palette)(n = lim)
colours
# Plot to png
<- paste0("mandelbrot_png_res_", res, "_lim_", lim, ".png")
png_file png(filename = png_file, width = res, height = res)
par(pty = "s")
image(mb, col = colours, xaxt = "n", yaxt = "n")
dev.off()
Done - That’s the code, which produces the image at the beginning of this post.
Until next time…