> For the complete documentation index, see [llms.txt](https://gitbook.testingwaters.in/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gitbook.testingwaters.in/patterns/mandelbrot-set.md).

# Mandelbrot Set

&#x20;Mathematically, the Mandelbrot set is defined on the plane of complex numbers

![](/files/-MkpLB9QIJ_VlMxyFJVu)

```d

//Function
def mandelbrot(wd,ht,mx)
{
	return [Imperative]
	{
		it = [];
		for (rw in 0..ht-1)
		{
		    for (cl in 0..wd-1)
		    {
		        rl = (cl - wd/2.0)*4.0/wd;
		        im = (rw - ht/2.0)*4.0/wd;
		        x = 0;
		        y = 0;
		        n = 0;
		        while (x*x+y*y <= 4 && n < mx)
		        {
		            x1 = x*x - y*y + rl;
		            y = 2*x*y + im;
		            x = x1;
		            n = n + 1;
		        }
		        it[cl][rw] = n;
		    }
		}
		return it;
	}
};
```

![](/files/-MRzni0nVhi-baaYTSPO)

```d
wd = 200;
hg = 200;
m = mandelbrot(wd,hg,50);

//Visualization
q = List.Reverse(List.Sort(List.UniqueItems(List.Flatten(m,-1))));
r = List.DropItems(Math.Round(Math.RemapRange(q,10,250)),-1);
d = Dictionary.ByKeysValues(q+"", List.Flatten([Color.ByARGB
(250,175,230,125),Color.ByARGB(List.Reverse(r),List.ShiftIndices
(r,100),List.ShiftIndices(r,-13),List.Reverse(r))],-1));
c = Image.FromPixels(List.Transpose(d.ValueAtKey(m+"")));

//Surface
pt1 = Point.ByCoordinates((-wd/2..wd/2..#wd)<1>,(-hg/2..hg/2..#hg)<2>);
el1 = List.Chop(Math.RemapRange(List.Flatten(m,-1),0,hg/10),hg);
sr1 = NurbsSurface.ByControlPoints(pt1.Translate(Vector.ZAxis(),el1));
sr2 = GeometryColor.BySurfaceColors(sr1,d.ValueAtKey(m+""));
```

![Maximum Iterations: 10](/files/-MRze8LaPE2HfUHHoAh4)

![Maximum Iterations: 30](/files/-MRzdSKTWvE7BRSwRAYx)

> Joni "Let’s draw the Mandelbrot set!", November 17, 2013 <[https://jonisalonen.com/2013/lets-draw-the-mandelbrot-set/>](https://jonisalonen.com/2013/lets-draw-the-mandelbrot-set/>)  January  26, 2021
