Drawing a colorful Mandelbrot Set in SQL Server

In this post I’m explaining a Transact-SQL script to draw a Mandelbrot set. Sometimes being creative is a rewarding experience.

Consider the equation, Zn+1 = Zn2+ C. Mandelbrot set is a set of values of C in which the Z in the formula bounded to certain range over many iterations. Both Z and C are complex numbers. In order to implement this in SQL, we need to convert the complex number to real and imaginary part in the form x + yi.

Starting from 0, i.e, Z0 = 0, apply the value Z of each previous iterations to current Z till the boundary exceeds a value or the end of iteration (say a 1000 iterations).

The above formula can be written as below.

Zreal = Zprev_real * Zprev_real – Zprev_im * Zprev_im + Creal

Zim = 2 * Zprev_real * Zprev_im + Cim

We select a plot area in a computer screen and for each pixel co-ordinates, map Creal and Cim and apply that to above formula in a loop until the value Zreal * Zreal + Zim * Zim <= 4 or till the iteration completes. Why the number 4? This is the diameter of the bounded circle. Store the number of iterations done for each screen co-ordinates. Draw a color based on the iteration number. You will get a magnificent image of Mandelbrot set. You can find a good explanation of the equation and how it is derived as above in this article.

There are many algorithms and language examples online to draw Mandelbrot set, plotting ASCII characters instead of color. Few years back I also tried this and come up with an SQL statement that plots the set in ASCII. But now I decided to give it some color. Using WKT (Well Known Text) and GEOMETRY data type in SQL Server, I generated a set of polygon co-ordinates and the result image from the Spatial result tab for the Mandelbrot set is below.

But the image rendering is not that much interesting. You can find many examples on drawing in SQL Server using GEOMETRY data type here, here, and here.

The research for a much better image rendering ended up in choosing a PPM Image Format. Using the same data, the iteration numbers were converted to RGB values and saved the file with .ppm extension. The ppm file can be read using most of the image editing softwares like Photoshop, GIMP etc. and also there are online PPM file viewers as well. The result is a much colorful Mandelbrot set plotting.

I have shared the entire script in Rosetta Code and you will get that from here.

In next post I will discuss the versatile Julia set.

Happy coding…

Leave a comment

Filed under Fun, T-SQL

Leave a comment