Generate Mandelbrot images using TikZ?

There's a Mandelbrot set shading in the shadings library:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{shadings}
\begin{document}
\tikz\shade[shading=Mandelbrot set] (0,0) rectangle (4,4);
\end{document}

Mandelbrot set

Displayed with the Acrobat Reader, as the TeXworks PDF previewer did not show high resolution.

The Mandelbrot set is computed and generated by the PDF renderer. The algorithm is written using PostScript commands, PDF supports a subset of Postscript operators, that's why it should be much faster than computing using higher level pgf or TikZ operators.


Here is a rather crude solution using luatex. Note that the calculations are done without any optimization, no use of symmetry or any other properties of the Mandelbrot set. Warning: the code takes a while to process even on a fairly fast computer.

\documentclass{standalone}
\usepackage{tikz}
\usepackage{luacode}

\def\escapetime#1#2{\directlua{tex.print(escape_time(#1,#2))}}
\def\mandcolor#1#2{\directlua{mand_color(#1,#2)}}

\begin{document}
\begin{luacode}
local NUMITER=100

point_iter = function (a,b) 
   local n = 1
   local x = a
   local y = b
   return function ()
      if n > NUMITER then return nil end
      n = n+1
      x,y = x*x - y*y + a, 2*x*y + b
      return n, x*x + y*y
   end
end

escape_time = function (a,b)
   local esc_time
   for n, d in point_iter(a,b) do
      esc_time = n
      if d > 4 then break end
   end
   return esc_time
end

mand_color = function (a,b)
   local etime = escape_time(a,b)
   if etime == NUMITER+1 then tex.print("black") else tex.print("red!"..etime) end
end
\end{luacode}
\begin{tikzpicture}[scale=2]
   \foreach \x in {-2,-1.99,...,.5}{
      \foreach \y in {-1.3,-1.29,...,1.3}{
      \draw[\mandcolor{\x}{\y},fill] (\x,\y) +(-.005,-.005) rectangle +(.005,.005);}}
\end{tikzpicture}
\end{document}

This is the resulting image:

mandelbrot set generated with lualatex

The next step would be to use mplib directly from lua to render the picture.


For those who are interested in another approach, i.e., using PSTricks:

\documentclass[border=12pt]{standalone}
\usepackage{pst-fractal}

\begin{document}
\psfractal[type=Mandel,baseColor=red,maxRadius=30,dIter=30,cx=-1.3,xWidth=4cm,yWidth=4cm](-3,-2)(2,2)
\end{document}

enter image description here

Compile the code snippet above with xelatex or latex-dvips-ps2pdf sequence.