<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Centre of the Universe &#187; Fractals</title>
	<atom:link href="http://www.sergemeunier.com/blog/category/fractals/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.sergemeunier.com/blog</link>
	<description>The musings of a mad software developer</description>
	<lastBuildDate>Tue, 01 Jun 2010 20:26:26 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Fractals in C#: The Lorentz attractor</title>
		<link>http://www.sergemeunier.com/blog/the-lorentz-attractor/</link>
		<comments>http://www.sergemeunier.com/blog/the-lorentz-attractor/#comments</comments>
		<pubDate>Tue, 06 Oct 2009 05:42:22 +0000</pubDate>
		<dc:creator>Serge Meunier</dc:creator>
				<category><![CDATA[Fractals]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.sergemeunier.com/blog/?p=829</guid>
		<description><![CDATA[The Lorenz attractor is a fractal based on the Lorenz oscillator, which is a 3-dimensional chaotic system.
For a full explanation on the Lorentz attractor, you can read the wikipedia article here.
The central equations needed for the Lorenz oscillator are:
dx/dt = σ(y &#8211; x)
dy/dt = x(ρ &#8211; z) &#8211; y
dz/dt = xy &#8211; βz
σ is the [...]


Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/t-square-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: T-Square fractals'>Fractals in C#: T-Square fractals</a> <small>A T-Square fractal is a relatively simple affair. The procedure...</small></li>
<li><a href='http://www.sergemeunier.com/blog/newton-rhapson-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: Newton-Rhapson fractals'>Fractals in C#: Newton-Rhapson fractals</a> <small>For anyone who has studied calculus, the Newton-Rhapson method should...</small></li>
<li><a href='http://www.sergemeunier.com/blog/brownian-motion/' rel='bookmark' title='Permanent Link: Fractals in C#: Brownian motion'>Fractals in C#: Brownian motion</a> <small>Brownian motion is described by an essentially random motion, which,...</small></li>
</ol>

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>The Lorenz attractor is a fractal based on the Lorenz oscillator, which is a 3-dimensional chaotic system.<br />
<div id="attachment_837" class="wp-caption aligncenter" style="width: 310px"><img src="http://www.sergemeunier.com/blog/wp-content/uploads/2009/10/lorentz-300x166.jpg" alt="Lorentz Attractor" title="Lorentz Attractor" width="300" height="166" class="size-medium wp-image-837" /><p class="wp-caption-text">Lorentz Attractor</p></div><br />
For a full explanation on the Lorentz attractor, you can read the wikipedia article <a href="http://en.wikipedia.org/wiki/Lorenz_attractor">here</a>.</p>
<p>The central equations needed for the Lorenz oscillator are:<br />
<em>dx/dt = σ(y &#8211; x)</em><br />
<em>dy/dt = x(ρ &#8211; z) &#8211; y</em><br />
<em>dz/dt = xy &#8211; βz</em></p>
<p><em>σ</em> is the Prandtl number, and is usually set to 10.<br />
<em>ρ</em> is the Rayleigh number and can be varied.<br />
<em>β</em> is set to 8/3.</p>
<p>Now, drawing the Lorenz attractor in C#, we are going to iterate a fixed number of times through these equations. In the code below, <em>ρ</em> is set to 28, and the number of iterations to 8000.</p>
<p>The code is able to draw the attractor in two dimensions or three dimensions, and the first part of the code calculates the transformations we will use later to transform the coordinates of attractor (which are in three dimensions) to screen coordinates.</p>
<p>We then iterate through each iteration, taking the x, y and z from the previous iteration, and running them through the Lorens oscillator equations to get our first set of derivatives.</p>
<p>We then add these to the previous x,y and z values, and then run them through the equations again, getting our second set of derivatives, and then add these to the x,y and z values as before. We repeat this until we get four sets of derivatives.</p>
<p>Once we have that we then add them together multiply by a scaling factor, and and them to x, y and z respectively.</p>
<p>Now that we have the new coordinates, we can plot a point at that position, applying our transformations to convert the three dimensional coordinates to screen coordinates.</p>
<p>You can get the full source code <a href="http://www.sergemeunier.com/downloads/FractalizeSource.zip">here</a>.<br />
<span id="more-829"></span></p>
<pre name="code" class="c-sharp">
		public void Generate(Graphics g, int iWidth, int iHeight, int iDim)
		{
      double rho, sigma, beta;
      double iterations;
      double x,y,z,d0_x,d0_y,d0_z,d1_x,d1_y,d1_z,d2_x,d2_y,d2_z;
			double d3_x,d3_y,d3_z,xt,yt,zt,dt,dt2,x_angle,y_angle,z_angle;
			double sx,sy,sz,cx,cy,cz,temp_x,temp_y,old_y;
			int i, row,col, old_row, old_col;
			int color = 0;

      iterations = 8000;
      rho = 28;
      sigma = 10;
      beta = 8.0 / 3.0;

			x_angle = 45;
			y_angle = 0;
			z_angle = 90;
			x_angle = DegToRad(x_angle);
			sx = Math.Sin(x_angle);
			cx = Math.Cos(x_angle);
			y_angle = DegToRad(y_angle);
			sy = Math.Sin(y_angle);
			cy = Math.Cos(y_angle);
			z_angle = DegToRad(z_angle);
			sz = Math.Sin(z_angle);
			cz = Math.Cos(z_angle);

			x = 0;
			y = 1;
			z = 0;

			if (iDim == 3)
			{
				old_col = (int)Math.Round(y*9.0);
				old_row = (int)Math.Round(350.0 - 6.56*z);
				g.DrawLine(new Pen(oColor[0]),0,348,638,348);
				g.DrawLine(new Pen(oColor[0]),320,2,320,348);
				g.DrawLine(new Pen(oColor[0]),320,348,648,140);
			}
			else
			{
				old_col = (int)Math.Round(y*9.0+320.0);
				old_row = (int)Math.Round(350.0 - 6.56*z);
				g.DrawLine(new Pen(oColor[0]),0,348,639,348);
				g.DrawLine(new Pen(oColor[0]),320,2,320,348);
			}
				dt = 0.01;
			dt2 = dt / 2.0;
			for (i = 0; i <= iterations; i++)
			{
				d0_x = sigma*(y-x)*dt2;
				d0_y = (-x*z + rho*x - y)*dt2;
				d0_z = (x*y - beta*z)*dt2;
				xt = x + d0_x;
				yt = y + d0_y;
				zt = z + d0_z;
				d1_x = (sigma*(yt-xt))*dt2;
				d1_y = (-xt*zt + rho*xt - yt)*dt2;
				d1_z =(xt*yt - beta*zt)*dt2;
				xt = x + d1_x;
				yt = y + d1_y;
				zt = z + d1_z;
				d2_x = (sigma*(yt-xt))*dt;
				d2_y = (-xt*zt + rho*xt - yt)*dt;
				d2_z =(xt*yt - beta*zt)*dt;
				xt = x + d2_x;
				yt = y + d2_y;
				zt = z + d2_z;
				d3_x = (sigma*(yt - xt))*dt2;
				d3_y = (-xt*zt + rho*xt - yt)*dt2;
				d3_z = (xt*yt - beta*zt/3)*dt2;
				old_y = y;
				x = x + (d0_x + d1_x + d1_x + d2_x + d3_x) * 0.33333333;
				y = y + (d0_y + d1_y + d1_y + d2_y + d3_y) * 0.33333333;
				z = z +  (d0_z + d1_z + d1_z + d2_z + d3_z) * 0.33333333;

				if (iDim == 3)
				{
					temp_x = x*cx + y*cy + z*cz;
					temp_y = x*sx + y*sy + z*sz;
					col = (int)Math.Round(temp_x*8.0 + 320.0);
					row = (int)Math.Round(350.0 - temp_y*5.0);
				}
				else
				{
					col = (int)Math.Round(y*9.0+320.0);
					row = (int)Math.Round(350 - 6.56*z);
				}
				if (col < 320)
				{
					if (old_col >= 320)
					{
						color++;
						color = color % 16;
					}
				}
				if (col > 320)
				{
					if (old_col <= 320)
					{
						color++;
						color=color % 16;
					}
				}
				g.DrawLine(new Pen(oColor[color]),old_col,old_row,col,row);
				old_row = row;
				old_col = col;
			}
		}
</pre>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.sergemeunier.com%2Fblog%2Fthe-lorentz-attractor%2F&amp;linkname=Fractals%20in%20C%23%3A%20The%20Lorentz%20attractor"><img src="http://www.sergemeunier.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>

<p>Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/t-square-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: T-Square fractals'>Fractals in C#: T-Square fractals</a> <small>A T-Square fractal is a relatively simple affair. The procedure...</small></li>
<li><a href='http://www.sergemeunier.com/blog/newton-rhapson-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: Newton-Rhapson fractals'>Fractals in C#: Newton-Rhapson fractals</a> <small>For anyone who has studied calculus, the Newton-Rhapson method should...</small></li>
<li><a href='http://www.sergemeunier.com/blog/brownian-motion/' rel='bookmark' title='Permanent Link: Fractals in C#: Brownian motion'>Fractals in C#: Brownian motion</a> <small>Brownian motion is described by an essentially random motion, which,...</small></li>
</ol></p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.sergemeunier.com/blog/the-lorentz-attractor/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fractals in C#: Newton-Rhapson fractals</title>
		<link>http://www.sergemeunier.com/blog/newton-rhapson-fractals/</link>
		<comments>http://www.sergemeunier.com/blog/newton-rhapson-fractals/#comments</comments>
		<pubDate>Mon, 05 Oct 2009 06:17:53 +0000</pubDate>
		<dc:creator>Serge Meunier</dc:creator>
				<category><![CDATA[Fractals]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.sergemeunier.com/blog/?p=809</guid>
		<description><![CDATA[For anyone who has studied calculus, the Newton-Rhapson method should be familiar. To those who have not, I do apologize if I lose you, but will try to make it easy.
The Newton-Rhapson method is a way to find the roots of a function using approximations. 
So, for the non-maths people out there, a function is [...]


Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/mandelbrot-set/' rel='bookmark' title='Permanent Link: Fractals in C#: The Mandelbrot set'>Fractals in C#: The Mandelbrot set</a> <small>Of all the fractals around, the Mandelbrot set is one...</small></li>
<li><a href='http://www.sergemeunier.com/blog/t-square-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: T-Square fractals'>Fractals in C#: T-Square fractals</a> <small>A T-Square fractal is a relatively simple affair. The procedure...</small></li>
<li><a href='http://www.sergemeunier.com/blog/julia-set/' rel='bookmark' title='Permanent Link: Fractals in C#: Julia sets'>Fractals in C#: Julia sets</a> <small>Julia sets are very similar to Mandelbrot sets, and if...</small></li>
</ol>

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>For anyone who has studied calculus, the Newton-Rhapson method should be familiar. To those who have not, I do apologize if I lose you, but will try to make it easy.</p>
<p>The Newton-Rhapson method is a way to find the roots of a function using approximations. </p>
<p>So, for the non-maths people out there, a function is denoted by f(x) and can be any equation, for example f(x) = x^2 + 3, or f(x) = sin(x). Now, the roots of a function are defined by f(x) = 0, so it is wherever the function equals zero.</p>
<p>Another important concept here is the derivative f&#8217;(x). This is the rate of change of the function f(x), but by going any deeper, I know I will lose the non-maths guys, and I am sure any of you who know some maths already know about derivatives.</p>
<p>The Newton-Rhapson method tries to find the values of the root by approximating the root, and then iterating using the procedure <em>a&#8217; = a &#8211; f(a)/f&#8217;(a)</em> where <em>a</em> is the approximated root, and <em>a&#8217;</em> is the closer approximation. The procedure is then repeated replacing <em>a</em> with the new <em>a&#8217;</em> value, as many times as is needed to achieve the required accuracy.<br />
<div id="attachment_811" class="wp-caption aligncenter" style="width: 287px"><img src="http://www.sergemeunier.com/blog/wp-content/uploads/2009/10/newtonrhapson-277x299.jpg" alt="Newton Rhapson" title="Newton Rhapson" width="277" height="299" class="size-medium wp-image-811" /><p class="wp-caption-text">Newton Rhapson</p></div><br />
So how the function that generates the fractal works, first we take our canvas, and iterating through each pixel in the canvas, we get <strong>x</strong> and <strong>y</strong> values, which are made up of the minimum values &#8211; which are passed as a parameter, so that we can view any part of the Cartesian space &#8211; and then add to that the column (or row) we are on multiplied by the scaling factor. </p>
<p>Now that we have our values we are going to pass into our function, and have set up a few values before we iterate, we start the iteration.</p>
<p>We keep on iterating, using the Newton-Rhapson method to find new values for <strong>x</strong> and <strong>y</strong>, and finally finished iteration when either we have reached a point where the values are as accurate as they are ever going to be, or else we have reached the amount of iterations we are going to allow.</p>
<p>Now that we have done that, we can select the color to draw at that particular point.  We have created an array of 16 colours, and then depending on values of <strong>x</strong> and <strong>y</strong>, we use certain colours, based on the iteration in which we reached our value.</p>
<p>If <strong>x</strong> is larger than 0, then the first 5 colours are used. If <strong>y</strong> > 0 and <strong>x</strong> is less than -0.3 then the next 5 colours are used, and for everything else the last 6 colours are used.<br />
<span id="more-809"></span><br />
The full source code is available <a href="http://www.sergemeunier.com/downloads/FractalizeSource.zip">here</a></p>
<pre name="code" class="c-sharp">
		Color[] oColor = new Color[16];

               //I put this code to set the colours into the class constructor. It is here purely to show which colours I have used.
		oColor[0] = Color.Black;
		oColor[1] = Color.Blue;
		oColor[2] = Color.Brown;
		oColor[3] = Color.Green;
		oColor[4] = Color.Magenta;
		oColor[5] = Color.Orange;
		oColor[6] = Color.Red;
		oColor[7] = Color.DarkGray;
		oColor[8] = Color.LightBlue;
		oColor[9] = Color.LightGreen;
		oColor[10] = Color.LightYellow;
		oColor[11] = Color.PaleVioletRed;
		oColor[12] = Color.Ivory;
		oColor[13] = Color.Yellow;
		oColor[14] = Color.Cyan;
		oColor[15] = Color.Lime;
		}

		public void Generate(Graphics g, int iIterations, int iSize, double XMax, double XMin, double YMax, double YMin, int iWidth, int iHeight)
		{
			int flag, iColor, col, row, i;
			double deltaX, deltaY, X, Y, Xsquare,Xold,Yold;
			double Ysquare,denom;

			deltaX = (XMax - XMin)/(iWidth);
			deltaY = (YMax - YMin)/(iHeight);
			for (col = 0; col < iWidth; col++)
			{
				for (row = 0; row < iHeight; row++)
				{
					X = XMin + col * deltaX;
					Y = YMax - row * deltaY;
					Xsquare = 0;
					Ysquare = 0;
					Xold = 42;
					Yold = 42;
					i = 0;
					flag = 0;
					while ((i <= iIterations) &#038;&#038; (flag == 0))
					{

						Xsquare = X*X;
						Ysquare = Y*Y;
						denom = 3.0*((Xsquare - Ysquare)*(Xsquare - Ysquare) + 4.0*Xsquare*Ysquare);
						if (denom == 0)
						{
							denom = 0.00000001;
						}
						X = 0.6666667*X + (Xsquare - Ysquare)/denom;

						Y = 0.6666667*Y - 2.0*X*Y/denom;
						if ((Xold == X) &#038;&#038; (Yold == Y))
						{
							flag = 1;
						}
						Xold = X;
						Yold = Y;
						i++;
					}
					if (X > 0)
					{
						iColor = i % 5;
					}
					else
					{
						if ((X < -0.3) &#038;&#038; (Y > 0))
						{
							iColor = (i % 5) + 5;
						}
						else
						{
							iColor = (i % 6) + 10;
						}
					}
					g.FillRectangle(new SolidBrush(oColor[iColor]),col, row, 1, 1);
				}
			}

		}
</pre>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.sergemeunier.com%2Fblog%2Fnewton-rhapson-fractals%2F&amp;linkname=Fractals%20in%20C%23%3A%20Newton-Rhapson%20fractals"><img src="http://www.sergemeunier.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>

<p>Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/mandelbrot-set/' rel='bookmark' title='Permanent Link: Fractals in C#: The Mandelbrot set'>Fractals in C#: The Mandelbrot set</a> <small>Of all the fractals around, the Mandelbrot set is one...</small></li>
<li><a href='http://www.sergemeunier.com/blog/t-square-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: T-Square fractals'>Fractals in C#: T-Square fractals</a> <small>A T-Square fractal is a relatively simple affair. The procedure...</small></li>
<li><a href='http://www.sergemeunier.com/blog/julia-set/' rel='bookmark' title='Permanent Link: Fractals in C#: Julia sets'>Fractals in C#: Julia sets</a> <small>Julia sets are very similar to Mandelbrot sets, and if...</small></li>
</ol></p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.sergemeunier.com/blog/newton-rhapson-fractals/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fractals in C#: Julia sets</title>
		<link>http://www.sergemeunier.com/blog/julia-set/</link>
		<comments>http://www.sergemeunier.com/blog/julia-set/#comments</comments>
		<pubDate>Fri, 02 Oct 2009 11:42:49 +0000</pubDate>
		<dc:creator>Serge Meunier</dc:creator>
				<category><![CDATA[Fractals]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.sergemeunier.com/blog/?p=777</guid>
		<description><![CDATA[Julia sets are very similar to Mandelbrot sets, and if you have not yet looked at my post on generating Mandelbrot sets, then I suggest you take a look. Most of the background is the same.
The only major difference is between Julia sets and the Mandelbrot set is that the Mandelbrot iteration is based on [...]


Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/mandelbrot-set/' rel='bookmark' title='Permanent Link: Fractals in C#: The Mandelbrot set'>Fractals in C#: The Mandelbrot set</a> <small>Of all the fractals around, the Mandelbrot set is one...</small></li>
<li><a href='http://www.sergemeunier.com/blog/newton-rhapson-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: Newton-Rhapson fractals'>Fractals in C#: Newton-Rhapson fractals</a> <small>For anyone who has studied calculus, the Newton-Rhapson method should...</small></li>
<li><a href='http://www.sergemeunier.com/blog/t-square-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: T-Square fractals'>Fractals in C#: T-Square fractals</a> <small>A T-Square fractal is a relatively simple affair. The procedure...</small></li>
</ol>

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>Julia sets are very similar to Mandelbrot sets, and if you have not yet looked at my post on generating <a href="http://www.sergemeunier.com/blog/mandelbrot-set">Mandelbrot sets</a>, then I suggest you take a look. Most of the background is the same.<br />
<div id="attachment_802" class="wp-caption aligncenter" style="width: 310px"><img src="http://www.sergemeunier.com/blog/wp-content/uploads/2009/10/juliaset2-300x219.jpg" alt="Julia Set" title="Julia Set" width="300" height="219" class="size-medium wp-image-802" /><p class="wp-caption-text">Julia Set</p></div></p>
<p>The only major difference is between Julia sets and the Mandelbrot set is that the Mandelbrot iteration is based on the equation <strong>Z</strong> = <strong>Z</strong>^(Power 1) + <strong>Z</strong>^(Power 2) + <strong>C</strong>, where <strong>C</strong> is the point<strong>Z(0)</strong>. The Julia set is based on the equation <strong>Z</strong>^(Power 1) &#8211; <strong>Z</strong>^(Power 2) &#8211; <strong>L</strong>, where <strong>L</strong> is a constant complex number.</p>
<p>We iterate through each point, using the centre of the screen as the origin (0,0). For each point then, we iterate up to our maximum depth, using the Julia formula now instead of the Mandelbrot one, and break when the absolute value of <strong>Z</strong> reaches 2. </p>
<p>We can then draw the point, using the same method as we used for drawing the Mandelbrot point.</p>
<p>You can get the full source code <a href="http://www.sergemeunier.com/downloads/FractalizeSource.zip">here</a>.</p>
<pre name="code" class="c-sharp">
		public void Generate(Graphics g, int iIterations, double Scaling, int iInitialSize, Complex L, double iOffsetRe, double iOffsetIm, int iLeft, int iTop, int iWidth, int iHeight, int iPower, int iPower2)
		{
			Complex Z = new Complex( 0.0, -0.0);
			Complex Offset = new Complex( 0.0, -0.0);

			// iterate over the area in the complex plane indicated by the Scaling and Offset
			//   i is the real axis,  j is the complex axis

			for (double i = -iWidth/2; i < iWidth/2 ; i++)
			{
				for (double j = -iHeight/2; j < iHeight/2; j++)
				{
					// Normalize Z and adjust for Scaling and Offset
					Z.re = (i/((double)iInitialSize)) * Scaling + (double)iOffsetRe;
					Z.im = (j/((double)iInitialSize)) * Scaling + (double)iOffsetIm;

					// C is the Z(0) of the formula based on the pixel position
					// We've also added a ManualOffset from the text boxes on the screen

					int iteration = 0;

					for (int k = 1; k < iIterations; k++)
					{
						Z = (Z^iPower) - (Z^iPower2) - L;
						// if modulus of Z > 2, break out of the loop
						// and remember the current iteration to choose the color
						if (Z.Abs() > 2.0)
						{
							iteration = k;
							break;
						}
					}

					DrawComplexPoint(g, ((int)i) + (iWidth/2), ((int)j) + (iHeight/2), iteration);
				}
			}
		}
</pre>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.sergemeunier.com%2Fblog%2Fjulia-set%2F&amp;linkname=Fractals%20in%20C%23%3A%20Julia%20sets"><img src="http://www.sergemeunier.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>

<p>Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/mandelbrot-set/' rel='bookmark' title='Permanent Link: Fractals in C#: The Mandelbrot set'>Fractals in C#: The Mandelbrot set</a> <small>Of all the fractals around, the Mandelbrot set is one...</small></li>
<li><a href='http://www.sergemeunier.com/blog/newton-rhapson-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: Newton-Rhapson fractals'>Fractals in C#: Newton-Rhapson fractals</a> <small>For anyone who has studied calculus, the Newton-Rhapson method should...</small></li>
<li><a href='http://www.sergemeunier.com/blog/t-square-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: T-Square fractals'>Fractals in C#: T-Square fractals</a> <small>A T-Square fractal is a relatively simple affair. The procedure...</small></li>
</ol></p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.sergemeunier.com/blog/julia-set/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fractals in C#: The Mandelbrot set</title>
		<link>http://www.sergemeunier.com/blog/mandelbrot-set/</link>
		<comments>http://www.sergemeunier.com/blog/mandelbrot-set/#comments</comments>
		<pubDate>Fri, 02 Oct 2009 11:30:36 +0000</pubDate>
		<dc:creator>Serge Meunier</dc:creator>
				<category><![CDATA[Fractals]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.sergemeunier.com/blog/?p=770</guid>
		<description><![CDATA[Of all the fractals around, the Mandelbrot set is one of the most famous, largely because it creates quite a complex and beautiful image. In my view anyway.
The actual method of calculating a Mandelbrot is relatively easy to follow. easy, that is, if you know what complex numbers are. A complex number is an imaginary [...]


Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/julia-set/' rel='bookmark' title='Permanent Link: Fractals in C#: Julia sets'>Fractals in C#: Julia sets</a> <small>Julia sets are very similar to Mandelbrot sets, and if...</small></li>
<li><a href='http://www.sergemeunier.com/blog/newton-rhapson-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: Newton-Rhapson fractals'>Fractals in C#: Newton-Rhapson fractals</a> <small>For anyone who has studied calculus, the Newton-Rhapson method should...</small></li>
<li><a href='http://www.sergemeunier.com/blog/t-square-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: T-Square fractals'>Fractals in C#: T-Square fractals</a> <small>A T-Square fractal is a relatively simple affair. The procedure...</small></li>
</ol>

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>Of all the fractals around, the Mandelbrot set is one of the most famous, largely because it creates quite a complex and beautiful image. In my view anyway.<br />
<div id="attachment_772" class="wp-caption aligncenter" style="width: 310px"><img src="http://www.sergemeunier.com/blog/wp-content/uploads/2009/10/mandelbrot-300x232.jpg" alt="Mandelbrot" title="Mandelbrot" width="300" height="232" class="size-medium wp-image-772" /><p class="wp-caption-text">Mandelbrot</p></div><br />
The actual method of calculating a Mandelbrot is relatively easy to follow. easy, that is, if you know what complex numbers are. A complex number is an imaginary number that is based on the squareroot of -1, which does not exist as a real number, and is usually denoted by <em>i</em>. A complex number is made up of a real part and an imaginary part, in the form Z = x<em>i</em> + y, where x and y are both real numbers, except that x is multiplied by the imaginary <em>i</em>.</p>
<p>Right, so enough maths before I lose you all completely.</p>
<p>So for our function that generates the Mandelbrot, we pass it various parameters which control the scaling, size and offset, which can be used to zoom in on particular areas. This is unimportant in the actual calculation of the fractal, except as modifiers for the calculations so that they calculate the correct area. The important parameters are the iterations, and the powers, as they will directly influence the calculations.</p>
<p>The <strong>Complex</strong> class which is used in the code to define the complex numbers in a complex number class which I have written, which I wont go into detail here, but iti s included with the source code. I will cover the inner working of that class in another post in the future.</p>
<p>So, on to how to calculate the Mandelbrot. we first set the two complex numbers, <strong>Z</strong> and <strong>C</strong> to the origin (0, 0).</p>
<p>Now we iterate from the top left to bottom right corners of our screen, using the centre of the screen as the coordinates (0,0). When we draw the points physically, we will add the offset to draw on the right location, since (0,0) is the top left corner in most images, but for the calculations , the top left corner will be (-width / 2, -height / 2).</p>
<p>So for each iteration, we adjust the real and imaginary portions of <strong>Z</strong> using the scaling and offset values, and then set <strong>C</strong> to <strong>Z</strong>.</p>
<p>Now, we iterate up to the iteration depth we specified. Each time we iterate, we apply the formula Z = Z^(Power 1) + Z^(Power 2) + C. For a normal Mandelbrot, these values are set to 2 and 0, so for the standard Mandelbrot, this equation becomes Z = Z^2 + C. You are encouraged to experiment with other values to get some really interesting looking images.</p>
<p>If the absolute value of <strong>Z</strong> is greater than 2, we then stop iterating, and take note of which iteration number we stopped at. This will be used to determine what colour we are going to plot at that point.</p>
<p>So, now we are ready to plot our point, and using the <strong>DrawComplexPoint</strong> function we plot the point. At this point, we add the offsets needed, as mentioned above, to move our coordinate system to the correct places for our image. </p>
<p>What this function also does is selects the colour to draw. In our code, there are 16 predefined colours in an array, which is selected based on the modulus of the iteration number we found in the previous step. </p>
<p>The full source code for can be found <a href="http://www.sergemeunier.com/downloads/FractalizeSource.zip">here</a>.</p>
<pre name="code" class="c-sharp">
   		Color[] oColor = new Color[16];
		oColor[0] = Color.Black;
		oColor[1] = Color.Blue;
		oColor[2] = Color.Brown;
		oColor[3] = Color.Green;
		oColor[4] = Color.Magenta;
		oColor[5] = Color.Orange;
		oColor[6] = Color.Red;
		oColor[7] = Color.DarkGray;
		oColor[8] = Color.LightBlue;
		oColor[9] = Color.LightGreen;
		oColor[10] = Color.LightYellow;
		oColor[11] = Color.PaleVioletRed;
		oColor[12] = Color.Ivory;
		oColor[13] = Color.Yellow;
		oColor[14] = Color.Cyan;
		oColor[15] = Color.Lime;

		public void Generate(Graphics g, int iIterations, double Scaling, int iInitialSize, double iOffsetRe, double iOffsetIm, int iLeft, int iTop, int iWidth, int iHeight, int iPower, int iPower2)
		{
			Complex Z = new Complex( 0.0, -0.0);
			Complex C = new Complex( 0.0, -0.0);
			Complex Offset = new Complex( 0.0, -0.0);

			for (double i = -iWidth/2; i < iWidth/2 ; i++)
			{
				for (double j = -iHeight/2; j < iHeight/2; j++)
				{
					// Normalize Z and adjust for Scaling and Offset
					Z.re = (i/((double)iInitialSize)) * Scaling + (double)iOffsetRe;
					Z.im = (j/((double)iInitialSize)) * Scaling + (double)iOffsetIm;

					// C is the Z(0) of the formula based on the pixel position
					C.re = Z.re;
					C.im = Z.im;

					int iteration = 0;

					// break out if or when |Z| > 2
					for (int k = 1; k < iIterations; k++)
					{
						Z = (Z^iPower) + (Z^iPower2) + C;
						// if modulus of Z > 2, break out of the loop
						// and remember the current iteration to choose the color
						if (Z.Abs() > 2.0)
						{
							iteration = k;
							break;
						}
					}

					// draw the point on the complex plain and choose the color based on the iteration
					// the color is picked by casting the iteration to a KnownColor enumeration
					DrawComplexPoint(g, ((int)i) + (iWidth/2), ((int)j) + (iHeight/2), iteration);
				}
			}
		}

		private void DrawComplexPoint(Graphics g, int iX, int iY, int iColor)
		{
			g.FillRectangle(new SolidBrush(oColor[iColor%16]), iX, iY, 1, 1);
		}
</pre>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.sergemeunier.com%2Fblog%2Fmandelbrot-set%2F&amp;linkname=Fractals%20in%20C%23%3A%20The%20Mandelbrot%20set"><img src="http://www.sergemeunier.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>

<p>Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/julia-set/' rel='bookmark' title='Permanent Link: Fractals in C#: Julia sets'>Fractals in C#: Julia sets</a> <small>Julia sets are very similar to Mandelbrot sets, and if...</small></li>
<li><a href='http://www.sergemeunier.com/blog/newton-rhapson-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: Newton-Rhapson fractals'>Fractals in C#: Newton-Rhapson fractals</a> <small>For anyone who has studied calculus, the Newton-Rhapson method should...</small></li>
<li><a href='http://www.sergemeunier.com/blog/t-square-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: T-Square fractals'>Fractals in C#: T-Square fractals</a> <small>A T-Square fractal is a relatively simple affair. The procedure...</small></li>
</ol></p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.sergemeunier.com/blog/mandelbrot-set/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fractals in C#: T-Square fractals</title>
		<link>http://www.sergemeunier.com/blog/t-square-fractals/</link>
		<comments>http://www.sergemeunier.com/blog/t-square-fractals/#comments</comments>
		<pubDate>Fri, 02 Oct 2009 10:49:35 +0000</pubDate>
		<dc:creator>Serge Meunier</dc:creator>
				<category><![CDATA[Fractals]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.sergemeunier.com/blog/?p=793</guid>
		<description><![CDATA[A T-Square fractal is a relatively simple affair.
The procedure to create a T-Square starts off with a square canvas on which we are going to draw. It will work with rectangular canvases as well, but then the results will look slightly different.
When we call the Generate function, we need to pass to it the coordinates [...]


Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/julia-set/' rel='bookmark' title='Permanent Link: Fractals in C#: Julia sets'>Fractals in C#: Julia sets</a> <small>Julia sets are very similar to Mandelbrot sets, and if...</small></li>
<li><a href='http://www.sergemeunier.com/blog/newton-rhapson-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: Newton-Rhapson fractals'>Fractals in C#: Newton-Rhapson fractals</a> <small>For anyone who has studied calculus, the Newton-Rhapson method should...</small></li>
<li><a href='http://www.sergemeunier.com/blog/mandelbrot-set/' rel='bookmark' title='Permanent Link: Fractals in C#: The Mandelbrot set'>Fractals in C#: The Mandelbrot set</a> <small>Of all the fractals around, the Mandelbrot set is one...</small></li>
</ol>

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>A T-Square fractal is a relatively simple affair.<br />
<div id="attachment_794" class="wp-caption aligncenter" style="width: 310px"><img src="http://www.sergemeunier.com/blog/wp-content/uploads/2009/10/tsquare-300x285.jpg" alt="T-Square" title="T-Square" width="300" height="285" class="size-medium wp-image-794" /><p class="wp-caption-text">T-Square</p></div><br />
The procedure to create a T-Square starts off with a square canvas on which we are going to draw. It will work with rectangular canvases as well, but then the results will look slightly different.</p>
<p>When we call the <strong>Generate</strong> function, we need to pass to it the coordinates of the first square, which, to get the best fit into our canvas, we calculate the lengths of the sides of the square to be half the canvas sides, and then centre the square, essentially making the top left corner a quarter of the way to the right and down of the origin.</p>
<p>The first thing we do is draw a solid square using our coordinates.</p>
<p>Now, until we reach our desired recursion depth, we generate four new squares, which have half the width and height, and make the centres of each of these squares to be centred on each of the four corners of the original square. </p>
<p>This process is then repeated until we have recursed far enough.</p>
<p>You can download the full source code <a href="http://www.sergemeunier.com/downloads/FractalizeSource.zip">here</a>.</p>
<pre name="code" class="c-sharp">
        public void GenerateTSquare(Graphics g, int iIterations, double iLeft, double iTop, double iWidth, double iHeight, Color oColor)
        {
            g.FillRectangle(new SolidBrush(oColor), (float)iLeft, (float)iTop, (float)iWidth, (float)iHeight);
            if (iIterations > 1)
            {
                double dNewWidth = iWidth / 2.0;
                double dNewHeight = iHeight / 2.0;

                GenerateTSquare(g, iIterations - 1, iLeft - (dNewWidth / 2.0), iTop - (dNewHeight / 2.0), dNewWidth, dNewHeight, oColor);
                GenerateTSquare(g, iIterations - 1, iLeft + iWidth - (dNewWidth / 2.0), iTop - (dNewHeight / 2.0), dNewWidth, dNewHeight, oColor);
                GenerateTSquare(g, iIterations - 1, iLeft - (dNewWidth / 2.0), iTop + iHeight - (dNewHeight / 2.0), dNewWidth, dNewHeight, oColor);
                GenerateTSquare(g, iIterations - 1, iLeft + iWidth - (dNewWidth / 2.0), iTop + iHeight - (dNewHeight / 2.0), dNewWidth, dNewHeight, oColor);

            }
        }
</pre>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.sergemeunier.com%2Fblog%2Ft-square-fractals%2F&amp;linkname=Fractals%20in%20C%23%3A%20T-Square%20fractals"><img src="http://www.sergemeunier.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>

<p>Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/julia-set/' rel='bookmark' title='Permanent Link: Fractals in C#: Julia sets'>Fractals in C#: Julia sets</a> <small>Julia sets are very similar to Mandelbrot sets, and if...</small></li>
<li><a href='http://www.sergemeunier.com/blog/newton-rhapson-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: Newton-Rhapson fractals'>Fractals in C#: Newton-Rhapson fractals</a> <small>For anyone who has studied calculus, the Newton-Rhapson method should...</small></li>
<li><a href='http://www.sergemeunier.com/blog/mandelbrot-set/' rel='bookmark' title='Permanent Link: Fractals in C#: The Mandelbrot set'>Fractals in C#: The Mandelbrot set</a> <small>Of all the fractals around, the Mandelbrot set is one...</small></li>
</ol></p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.sergemeunier.com/blog/t-square-fractals/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fractals in C#: Brownian motion</title>
		<link>http://www.sergemeunier.com/blog/brownian-motion/</link>
		<comments>http://www.sergemeunier.com/blog/brownian-motion/#comments</comments>
		<pubDate>Fri, 02 Oct 2009 10:26:52 +0000</pubDate>
		<dc:creator>Serge Meunier</dc:creator>
				<category><![CDATA[Fractals]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.sergemeunier.com/blog/?p=787</guid>
		<description><![CDATA[Brownian motion is described by an essentially random motion, which, one of the most famous examples is the movement of a speck of dust floating on the surface of a glass of water.
For our fractal, the random element of the brownian motion, while essentially still being random is constrained by the end points. To create [...]


Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/plasma-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: Plasma fractals'>Fractals in C#: Plasma fractals</a> <small>This is the first in a series of posts that...</small></li>
<li><a href='http://www.sergemeunier.com/blog/fern-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: Fern fractals'>Fractals in C#: Fern fractals</a> <small>Fern fractals are another class of iterative fractals, a type...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-least-squares-fit-with-a-log-abscissa/' rel='bookmark' title='Permanent Link: Maths algorithms in C#: Least squares fit with a log abscissa'>Maths algorithms in C#: Least squares fit with a log abscissa</a> <small>This algorithm for the least squares fit uses a logarithmic...</small></li>
</ol>

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>Brownian motion is described by an essentially random motion, which, one of the most famous examples is the movement of a speck of dust floating on the surface of a glass of water.<br />
<div id="attachment_788" class="wp-caption aligncenter" style="width: 310px"><img src="http://www.sergemeunier.com/blog/wp-content/uploads/2009/10/brownian-300x237.jpg" alt="Brownian Motion" title="Brownian Motion" width="300" height="237" class="size-medium wp-image-788" /><p class="wp-caption-text">Brownian Motion</p></div></p>
<p>For our fractal, the random element of the brownian motion, while essentially still being random is constrained by the end points. To create the fractal, we start with an array of 128 double values. This array could in theory be any size, and is not a fixed requirement.</p>
<p>Now, the first element and last element are our starting and ending points of our path. In the code, these points are randomly generated, but could just as easily be set explicitly.</p>
<p>Before we look at the <strong>Generate</strong> function, I am going to look at the <strong>Gauss</strong> function. This function takes three parameters &#8211; the seed for the random number generator (so we can create the same fractal by passing the same seed), Mu and Sigma.</p>
<p>The Mu value is the base displacement we want the path to move, and the Sigma value is a multiplier for the random element.</p>
<p>A random number is generated, which is then multiplied by Sigma, which is then added to Mu to give us the displacement of the value for that step in the calculation.</p>
<pre name="code" class="c-sharp">
        private double Gauss(int iSeed, double fMu, double fSigma)
        {
            double fx;
            int i;

            fx = 0;
            for (i = 0; i < 12; i++)
            {
                fx = fx + (new System.Random(iSeed).NextDouble());
            }
            fx = fx - 6.0;
            return fMu + fSigma * fx;
        }
</pre>
<p><span id="more-787"></span><br />
The <strong>Generate</strong> function sets up our arrays, and gets a ratio which will be used as an additional multiplication factor in calculating the movement in each step, using the passed value of H.</p>
<p>Now we begin recursing to set the values of each element of the array.<br />
The last section of the function draws the values which have been generated by the recursion.</p>
<pre name="code" class="c-sharp">
        public void Generate(Graphics g, double fMu, double fSigma, double fScale, double fH, int fSeed, Color oColor)
        {

            double fRatio, fStd;
            int i;
            Pen oPen = new Pen(oColor);

            Fh[0] = Gauss(fSeed, fMu, fSigma) * fScale;
            Fh[256] = Gauss(0, fMu, fSigma) * fScale;
            fRatio = Math.Exp(-0.693147 * fH);
            fStd = fScale * fRatio;

            Subdivide(0, 255, fStd, fRatio, fMu, fSigma);

            for (i = 0; i < 255; i++)
            {
                g.DrawLine(oPen, 2 * i + 80, 275 - (int)Math.Round(Fh[i]), 2 * (i + 1) + 80, 275 - (int)Math.Round(Fh[i + 1]));
            }

        }
</pre>
<p>Now we come to the <strong>SubDivide</strong> function, which is where the heavy lifting occurs.</p>
<p>Having been passed the starting point and end point, this function calculates the midpoint, and then gets the average of the two points, and then adds the random displacement calculated by the <strong>Guass</strong> function multiplied by our ratio factor.</p>
<p>We now calculate a new ratio factor, by multiplying the scaled ratio by the original ratio.</p>
<p>Finally, we recursively call <strong>Subdivide</strong> for the two segments we have now that we have split the original segment into two by finding the midpoint. </p>
<p>If we have reached the point where there are no more points left in-between the end points, we just return, doing nothing, since our job is complete.</p>
<pre name="code" class="c-sharp">
        private void Subdivide(int f1, int f2, double std, double ratio, double fMu, double fSigma)
        {
            int fmid;
            double stdmid;

            fmid = (int)Math.Round((f1 + f2) / 2.0);
            if ((fmid != f1) &#038;&#038; (fmid != f2))
            {
                Fh[fmid] = (Fh[f1] + Fh[f2]) / 2.0 + Gauss(0, fMu, fSigma) * std;
                stdmid = std * ratio;
                Subdivide(f1, fmid, stdmid, ratio, fMu, fSigma);
                Subdivide(fmid, f2, stdmid, ratio, fMu, fSigma);
            }
        }
</pre>
<p>You can, as usual, get the full source code <a href="http://www.sergemeunier.com/downloads/FractalizeSource.zip">here</a>.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.sergemeunier.com%2Fblog%2Fbrownian-motion%2F&amp;linkname=Fractals%20in%20C%23%3A%20Brownian%20motion"><img src="http://www.sergemeunier.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>

<p>Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/plasma-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: Plasma fractals'>Fractals in C#: Plasma fractals</a> <small>This is the first in a series of posts that...</small></li>
<li><a href='http://www.sergemeunier.com/blog/fern-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: Fern fractals'>Fractals in C#: Fern fractals</a> <small>Fern fractals are another class of iterative fractals, a type...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-least-squares-fit-with-a-log-abscissa/' rel='bookmark' title='Permanent Link: Maths algorithms in C#: Least squares fit with a log abscissa'>Maths algorithms in C#: Least squares fit with a log abscissa</a> <small>This algorithm for the least squares fit uses a logarithmic...</small></li>
</ol></p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.sergemeunier.com/blog/brownian-motion/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fractals in C#: Fern fractals</title>
		<link>http://www.sergemeunier.com/blog/fern-fractals/</link>
		<comments>http://www.sergemeunier.com/blog/fern-fractals/#comments</comments>
		<pubDate>Fri, 02 Oct 2009 05:45:07 +0000</pubDate>
		<dc:creator>Serge Meunier</dc:creator>
				<category><![CDATA[Fractals]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.sergemeunier.com/blog/?p=764</guid>
		<description><![CDATA[Fern fractals are another class of iterative fractals, a type of iterative function system, that draws rather good images of ferns. And with a bit of tweaking of the input variables, the ferns of various sizes and shapes can be created using the same code.
To create a fractal fern you first need to supply a [...]


Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/mandelbrot-set/' rel='bookmark' title='Permanent Link: Fractals in C#: The Mandelbrot set'>Fractals in C#: The Mandelbrot set</a> <small>Of all the fractals around, the Mandelbrot set is one...</small></li>
<li><a href='http://www.sergemeunier.com/blog/newton-rhapson-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: Newton-Rhapson fractals'>Fractals in C#: Newton-Rhapson fractals</a> <small>For anyone who has studied calculus, the Newton-Rhapson method should...</small></li>
<li><a href='http://www.sergemeunier.com/blog/julia-set/' rel='bookmark' title='Permanent Link: Fractals in C#: Julia sets'>Fractals in C#: Julia sets</a> <small>Julia sets are very similar to Mandelbrot sets, and if...</small></li>
</ol>

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>Fern fractals are another class of iterative fractals, a type of iterative function system, that draws rather good images of ferns. And with a bit of tweaking of the input variables, the ferns of various sizes and shapes can be created using the same code.<br />
<div id="attachment_761" class="wp-caption aligncenter" style="width: 331px"><img src="http://www.sergemeunier.com/blog/wp-content/uploads/2009/10/fernfractal.jpg" alt="A Fern Fractal" title="A Fern Fractal" width="321" height="410" class="size-full wp-image-761" /><p class="wp-caption-text">A Fern Fractal</p></div></p>
<p>To create a fractal fern you first need to supply a rather large amount of input variables that will control the shape of the fern. So in the application, the variables are stored in a few arrays.</p>
<pre name="code" class="c-sharp">
            double[] dA = new double[2];
            double[] dB = new double[6];
            double[] dC = new double[6];
            double[] dD = new double[6];
            int[] iRand = new int[4];

            dA[0] = 0;
            dA[1] = 0.16;
            dB[0] = 0.2;
            dB[1] = -0.26;
            dB[2] = 0;
            dB[3] = 0.23;
            dB[4] = 0.22;
            dB[5] = 1.6;
            dC[0] = -0.15;
            dC[1] = 0.28;
            dC[2] = 0;
            dC[3] = 0.26;
            dC[4] = 0.25;
            dC[5] = 0.44;
            dD[0] = 0.85;
            dD[1] = 0.04;
            dD[2] = 0;
            dD[3] = -0.04;
            dD[4] = 0.85;
            dD[5] = 1.6;
            iRand[0] = 1;
            iRand[1] = 8;
            iRand[2] = 15;
            iRand[3] = 85;
</pre>
<p>So, now we have arrays dA, dB, dC, dD and iRand. Very simply, the values in dA control the rachis of the fern (the main stem for those, like me, who weren&#8217;t listening in biology class),  dB controls the left pinna (a &#8220;leaflet&#8221;), dC controls the right pinna, and dD controls the main shape of a frond (the fern&#8217;s &#8220;leaf&#8221;). iRand contains the probability that a value from each of the four arrays will be used.</p>
<p>Now the main function iterates through a specified number of points (which in the sample on this page, I used 100000 iterations), by first setting the current x and y coordinate to 0, and then it starts the iteration. </p>
<p>A random number is generated between 0 and 1, and if the number is less than iRand[0] then it calculates the new xy coordinate based on the dA array. It then checks each probability through all the probabililities, each time calculating the xy coordinate using the array and calculation specified at that value.</p>
<p>Once the new coordinates are calculated, the point is drawn using the desired colour, and then the function loops to the next iteration, using these coordinates as the base coordinates for the next iteration.</p>
<p>Once the function has iterated enough times, the function exits, and you should be left with a decent fern.</p>
<p>Half the fun of this type of fractal is playing around with the input variables to see how they affect the output, so have fun. The full  source code is available <a href="http://www.sergemeunier.com/downloads/FractalizeSource.zip">here</a>.</p>
<pre name="code" class="c-sharp">
        public void GenerateFern(Graphics g, int iIterations, double dStartX, double dStartY, double dScale, double[] dA, double[] dB, double[] dC, double[] dD, int[] iRand, Color oColor)
        {
            FastRandom rnd = new FastRandom();
            int iRandNum;
            double dX = 0;
            double dY = 0;
            double dNewX = 0;
            double dNewY = 0;

            for (int i = 0; i < iIterations; i++)
            {

                iRandNum = rnd.Next(0, 100);
                if (iRandNum < iRand[0])
                {
                    dNewX = dA[0];
                    dNewY = dA[1] * dY;

                }
                else if (iRandNum < iRand[1])
                {
                    dNewX = (dB[0] * dX) + (dB[1] * dY) + dB[2];
                    dNewY = (dB[3] * dX) + (dB[4] * dY) + dB[5];
                }
                else if (iRandNum < iRand[2])
                {
                    dNewX = (dC[0] * dX) + (dC[1] * dY) + dC[2];
                    dNewY = (dC[3] * dX) + (dC[4] * dY) + dC[5];
                }
                else
                {
                    dNewX = (dD[0] * dX) + (dD[1] * dY) + dD[2];
                    dNewY = (dD[3] * dX) + (dD[4] * dY) + dD[5];
                }
                dX = dNewX;
                dY = dNewY;
                g.FillRectangle(new SolidBrush(oColor), (float)(dStartX + (dNewX * dScale)), (float)(dStartY - (dNewY * dScale)), 1, 1);
            }

        }
</pre>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.sergemeunier.com%2Fblog%2Ffern-fractals%2F&amp;linkname=Fractals%20in%20C%23%3A%20Fern%20fractals"><img src="http://www.sergemeunier.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>

<p>Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/mandelbrot-set/' rel='bookmark' title='Permanent Link: Fractals in C#: The Mandelbrot set'>Fractals in C#: The Mandelbrot set</a> <small>Of all the fractals around, the Mandelbrot set is one...</small></li>
<li><a href='http://www.sergemeunier.com/blog/newton-rhapson-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: Newton-Rhapson fractals'>Fractals in C#: Newton-Rhapson fractals</a> <small>For anyone who has studied calculus, the Newton-Rhapson method should...</small></li>
<li><a href='http://www.sergemeunier.com/blog/julia-set/' rel='bookmark' title='Permanent Link: Fractals in C#: Julia sets'>Fractals in C#: Julia sets</a> <small>Julia sets are very similar to Mandelbrot sets, and if...</small></li>
</ol></p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.sergemeunier.com/blog/fern-fractals/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fractals in C#: Sierpinksi triangles and squares</title>
		<link>http://www.sergemeunier.com/blog/sierpinksi-triangles-and-squares/</link>
		<comments>http://www.sergemeunier.com/blog/sierpinksi-triangles-and-squares/#comments</comments>
		<pubDate>Thu, 01 Oct 2009 09:00:57 +0000</pubDate>
		<dc:creator>Serge Meunier</dc:creator>
				<category><![CDATA[Fractals]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.sergemeunier.com/blog/?p=744</guid>
		<description><![CDATA[Sierpinski triangles and squares are relatively easy fractals to draw, and although the principle is the same I will handle the two separately.
For Sierpinski triangles, you take your initial triangle (an equilateral triangle works nicely) and then finding the midpoints of each side and connecting them, break up the triangle into four new triangles. Then [...]


Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/t-square-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: T-Square fractals'>Fractals in C#: T-Square fractals</a> <small>A T-Square fractal is a relatively simple affair. The procedure...</small></li>
<li><a href='http://www.sergemeunier.com/blog/fern-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: Fern fractals'>Fractals in C#: Fern fractals</a> <small>Fern fractals are another class of iterative fractals, a type...</small></li>
<li><a href='http://www.sergemeunier.com/blog/newton-rhapson-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: Newton-Rhapson fractals'>Fractals in C#: Newton-Rhapson fractals</a> <small>For anyone who has studied calculus, the Newton-Rhapson method should...</small></li>
</ol>

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p><div id="attachment_748" class="wp-caption alignright" style="width: 160px"><img src="http://www.sergemeunier.com/blog/wp-content/uploads/2009/10/sierpinskitriangles1-150x150.jpg" alt="Sierpinski Triangles" title="Sierpinski Triangles" width="150" height="150" class="size-thumbnail wp-image-748" /><p class="wp-caption-text">Sierpinski Triangles</p></div><br />
Sierpinski triangles and squares are relatively easy fractals to draw, and although the principle is the same I will handle the two separately.</p>
<p>For Sierpinski triangles, you take your initial triangle (an equilateral triangle works nicely) and then finding the midpoints of each side and connecting them, break up the triangle into four new triangles. Then for each of the three triangles on the outside, repeat this process until you reach the desired recursion depth. The middle triangle is left alone, and remains unfilled. When you reach the recursion depth you require, you can then colour the triangle the desired colour.</p>
<p><div id="attachment_749" class="wp-caption alignright" style="width: 160px"><img src="http://www.sergemeunier.com/blog/wp-content/uploads/2009/10/sierpinskisquares1-150x150.jpg" alt="Sierpinski Squares" title="Sierpinski Squares" width="150" height="150" class="size-thumbnail wp-image-749" /><p class="wp-caption-text">Sierpinski Squares</p></div>Sierpinksi squares work in a similar way, except, instead of using the midpoint, you divide each edge into three pieces, and then split up the initial square into nine new squares. Repeat this process for the eight outer squares, leaving the middle square, as in for the triangles, alone. Once you reach the desired recursion depth, you then colour the square the desired colour.</p>
<p>So, then, the code to generate this is as follows. There is nothing tricky at all about it. In both cases, if the recursion depth is not yet met, the points are calculated, and the function is called recursively for each new shape, and if you have recursed far enough, then draw the shape based on the desired colour and coordinates. The coordinates of the initial shapes are passed as doubles to the functions, such as x1, y1 etc.</p>
<pre name="code" class="c-sharp">
        public void GenerateSquare(Graphics g, int iIterations, double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4, Color oColor)
        {
            if (iIterations &gt; 1)
            {
                double midx1a = x1 + ((x2 - x1) / 3);
                double midy1a = y1;
                double midx1b = x1 + ((x2 - x1) / 3 * 2);
                double midy1b = y1;
                double midx2a = x2;
                double midy2a = y2 + ((y3 - y2) / 3);
                double midx2b = x2;
                double midy2b = y2 + ((y3 - y2) / 3 * 2);
                double midx3a = x1 + ((x3 - x4) / 3);
                double midy3a = y3;
                double midx3b = x1 + ((x3 - x4) / 3 * 2);
                double midy3b = y3;
                double midx4a = x1;
                double midy4a = y1 + ((y4 - y1) / 3);
                double midx4b = x1;
                double midy4b = y1 + ((y4 - y1) / 3 * 2);
                double midx5a = x1 + ((x2 - x1) / 3);
                double midy5a = y1 + ((y4 - y1) / 3);
                double midx5b = x1 + ((x2 - x1) / 3 * 2);
                double midy5b = y1 + ((y4 - y1) / 3);
                double midx5d = x1 + ((x2 - x1) / 3);
                double midy5d = y1 + ((y4 - y1) / 3 * 2);
                double midx5c = x1 + ((x2 - x1) / 3 * 2);
                double midy5c = y1 + ((y4 - y1) / 3 * 2);

                GenerateSquare(g, iIterations - 1, x1, y1, midx1a, midy1a, midx5a, midy5a, midx4a, midy4a, oColor);
                GenerateSquare(g, iIterations - 1, midx1a, midy1a, midx1b, midy1b, midx5b, midy5b, midx5a, midy5a, oColor);
                GenerateSquare(g, iIterations - 1, midx1b, midy1b, x2, y2, midx2a, midy2a, midx5b, midy5b, oColor);
                GenerateSquare(g, iIterations - 1, midx5b, midy5b, midx2a, midy2a, midx2b, midy2b, midx5c, midy5c, oColor);
                GenerateSquare(g, iIterations - 1, midx5c, midy5c, midx2b, midy2b, x3, y3, midx3b, midy3b, oColor);
                GenerateSquare(g, iIterations - 1, midx5d, midy5d, midx5c, midy5c, midx3b, midy3b, midx3a, midy3a, oColor);
                GenerateSquare(g, iIterations - 1, midx4b, midy4b, midx5d, midy5d, midx3a, midy3a, x4, y4, oColor);
                GenerateSquare(g, iIterations - 1, midx4a, midy4a, midx5a, midy5a, midx5d, midy5d, midx4b, midy4b, oColor);
            }
            else
            {
                Pen o = new Pen(new SolidBrush(oColor));
                PointF[] points = new PointF[4];
                points[0] = new PointF((float)x1, (float)y1);
                points[1] = new PointF((float)x2, (float)y2);
                points[2] = new PointF((float)x3, (float)y3);
                points[3] = new PointF((float)x4, (float)y4);

                g.FillPolygon(new SolidBrush(oColor), points);
            }

        }

        public void GenerateTriangle(Graphics g, int iIterations, double x1, double y1, double x2, double y2, double x3, double y3, Color oColor)
        {

            if (iIterations &gt; 1)
            {
                double midx1 = (x1 + x2) / 2;
                double midy1 = (y1 + y2) / 2;
                double midx2 = (x2 + x3) / 2;
                double midy2 = (y2 + y3) / 2;
                double midx3 = (x3 + x1) / 2;
                double midy3 = (y3 + y1) / 2;
                GenerateTriangle(g, iIterations - 1, x1, y1, midx1, midy1, midx3, midy3, oColor);
                GenerateTriangle(g, iIterations - 1, midx1, midy1, x2, y2, midx2, midy2, oColor);
                GenerateTriangle(g, iIterations - 1, midx3, midy3, midx2, midy2, x3, y3, oColor);
            }
            else
            {
                PointF[] points = new PointF[3];
                points[0] = new PointF((float)x1, (float)y1);
                points[1] = new PointF((float)x2, (float)y2);
                points[2] = new PointF((float)x3, (float)y3);

                g.FillPolygon(new SolidBrush(oColor), points);
            }
        }
</pre>
<p>You can get the full source code, which includes all the other fractals, <a href="http://www.sergemeunier.com/downloads/FractalizeSource.zip">here</a>.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.sergemeunier.com%2Fblog%2Fsierpinksi-triangles-and-squares%2F&amp;linkname=Fractals%20in%20C%23%3A%20Sierpinksi%20triangles%20and%20squares"><img src="http://www.sergemeunier.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>

<p>Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/t-square-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: T-Square fractals'>Fractals in C#: T-Square fractals</a> <small>A T-Square fractal is a relatively simple affair. The procedure...</small></li>
<li><a href='http://www.sergemeunier.com/blog/fern-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: Fern fractals'>Fractals in C#: Fern fractals</a> <small>Fern fractals are another class of iterative fractals, a type...</small></li>
<li><a href='http://www.sergemeunier.com/blog/newton-rhapson-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: Newton-Rhapson fractals'>Fractals in C#: Newton-Rhapson fractals</a> <small>For anyone who has studied calculus, the Newton-Rhapson method should...</small></li>
</ol></p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.sergemeunier.com/blog/sierpinksi-triangles-and-squares/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fractals in C#: Plasma fractals</title>
		<link>http://www.sergemeunier.com/blog/plasma-fractals/</link>
		<comments>http://www.sergemeunier.com/blog/plasma-fractals/#comments</comments>
		<pubDate>Wed, 30 Sep 2009 12:08:10 +0000</pubDate>
		<dc:creator>Serge Meunier</dc:creator>
				<category><![CDATA[Fractals]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.sergemeunier.com/blog/?p=712</guid>
		<description><![CDATA[This is the first in a series of posts that I am going to do on generating fractals using C#. All code was compiled using Visual Studio 2008.
The source code for the application, which includes all the fractals which will be covered in the series is available for download here.
Everybody always covers the Mandelbrot as [...]


Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/proportionately-resizing-a-bitmap-in-c-sharp/' rel='bookmark' title='Permanent Link: Proportionately resizing a bitmap in C#'>Proportionately resizing a bitmap in C#</a> <small>Resizing a bitmap and keeping the sides proportions intact &#8211;...</small></li>
<li><a href='http://www.sergemeunier.com/blog/t-square-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: T-Square fractals'>Fractals in C#: T-Square fractals</a> <small>A T-Square fractal is a relatively simple affair. The procedure...</small></li>
<li><a href='http://www.sergemeunier.com/blog/sierpinksi-triangles-and-squares/' rel='bookmark' title='Permanent Link: Fractals in C#: Sierpinksi triangles and squares'>Fractals in C#: Sierpinksi triangles and squares</a> <small>Sierpinski triangles and squares are relatively easy fractals to draw,...</small></li>
</ol>

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>This is the first in a series of posts that I am going to do on generating fractals using C#. All code was compiled using Visual Studio 2008.</p>
<p>The source code for the application, which includes all the fractals which will be covered in the series is available for download <a href="http://www.sergemeunier.com/downloads/FractalizeSource.zip">here</a>.</p>
<p>Everybody always covers the Mandelbrot as the fractal of choice, so, in doing things a little differently, I decided to start with plasma fractals, and leave the Mandelbrot until later.</p>
<p><div id="attachment_719" class="wp-caption aligncenter" style="width: 310px"><img src="http://www.sergemeunier.com/blog/wp-content/uploads/2009/09/fractalplasma1-300x294.jpg" alt="A plasma fractal" title="A plasma fractal" width="300" height="294" class="size-medium wp-image-719" /><p class="wp-caption-text">A plasma fractal</p></div><br />
<div id="attachment_713" class="wp-caption alignright" style="width: 138px"><img class="size-full wp-image-713" title="Assigning values to the four corners" src="http://www.sergemeunier.com/blog/wp-content/uploads/2009/09/stage1.gif" alt="Assigning values to the four corners" width="128" height="100" /><p class="wp-caption-text">Assigning values to the four corners</p></div>So, what is a plasma fractal exactly? A plasma fractal is generated by taking a rectangle with a width x and height y. Then to each corner in the rectangle, assign a random value between 0 and 1.<br/><br/><br/><br/><br/><br/><br/><br />
<div id="attachment_715" class="wp-caption alignright" style="width: 138px"><img src="http://www.sergemeunier.com/blog/wp-content/uploads/2009/09/stage21.gif" alt="Find average for edges and centre" title="Find average for edges and centre" width="128" height="100" class="size-full wp-image-715" /><p class="wp-caption-text">Find average for edges and centre</p></div><br />
The next step is to find the midpoint of each side, and at that point, calculate the average value of the two points that this point is bisecting. A midpoint is also calculated, which is in the centre of the rectangle, which is the average of all four corners plus a random displacement.<br/><br/><br/><br/><br/></p>
<p><div id="attachment_716" class="wp-caption alignright" style="width: 138px"><img src="http://www.sergemeunier.com/blog/wp-content/uploads/2009/09/stage3.gif" alt="Repeat process with the four new rectangles" title="Repeat process with the four new rectangles" width="128" height="100" class="size-full wp-image-716" /><p class="wp-caption-text">Repeat process with the four new rectangles</p></div>Then for each of the four rectangle bounded by the new points, repeat the process, until all the pixels have been calculated.<br />
<br/><br/><br/><br/><br/><br/><br/><br />
After the values have been calculated, the values can be converted to colours using any method you like. Using the raw values unaltered will create a greyscale image very well with only adjusting the value to put it in the correct range.</p>
<p>Now, in the code to do this (which can be found in <em>Plasma.cs</em> in the source download), first, we have a few global variables</p>
<pre name="code" class="c-sharp">
        public double gRoughness;
        public double gBigSize;
        FastRandom rnd;
</pre>
<p>The roughness is amount in which we are going to vary the value by for the midpoint.gBigSize is defined as the width plus the height of the image we are generating. FastRandom is a random number generator, which works exactly like the builtin random number generator, except that it is faster.</p>
<p>Our starting point is the <strong>Generate</strong> function that return a two-dimensional array of values where each entry in the array corresponds to an xy coordinate and the value is the calculated value, which will be converted into a colour.<br />
<span id="more-712"></span></p>
<pre name="code" class="c-sharp">
        public double[,] Generate(int iWidth, int iHeight, double iRoughness)
        {
            double c1, c2, c3, c4;
            double[,] points = new double[iWidth+1, iHeight+1];

            //Assign the four corners of the intial grid random color values
            //These will end up being the colors of the four corners
            c1 = rnd.NextDouble();
            c2 = rnd.NextDouble();
            c3 = rnd.NextDouble();
            c4 = rnd.NextDouble();
            gRoughness = iRoughness;
            gBigSize = iWidth + iHeight;
            DivideGrid(ref points, 0, 0, iWidth, iHeight, c1, c2, c3, c4);
            return points;
        }
</pre>
<p>This function sets the four initial corners, and sets the global variables, and then starts the recursion to generate the rest of the points by calling <strong>DivideGrid</strong>, which is what follows next. The most import point here is that the array containing the points is passed as a reference variable to DivideGrid, so that as it recurses, it can update the points accordingly.</p>
<pre name="code" class="c-sharp">
        public void DivideGrid(ref double[,] points, double x, double y, double width, double height, double c1, double c2, double c3, double c4)
        {
            double Edge1, Edge2, Edge3, Edge4, Middle;

            double newWidth = Math.Floor(width / 2);
            double newHeight = Math.Floor(height / 2);

            if (width &gt; 1 || height &gt; 1)
            {
                Middle = ((c1 + c2 + c3 + c4) / 4)+Displace(newWidth + newHeight);	//Randomly displace the midpoint!
                Edge1 = ((c1 + c2) / 2);	//Calculate the edges by averaging the two corners of each edge.
                Edge2 = ((c2 + c3) / 2);
                Edge3 = ((c3 + c4) / 2);
                Edge4 = ((c4 + c1) / 2);//
                //Make sure that the midpoint doesn't accidentally "randomly displaced" past the boundaries!
                Middle= Rectify(Middle);
                Edge1 = Rectify(Edge1);
                Edge2 = Rectify(Edge2);
                Edge3 = Rectify(Edge3);
                Edge4 = Rectify(Edge4);
                //Do the operation over again for each of the four new grids.
                DivideGrid(ref points, x, y, newWidth, newHeight, c1, Edge1, Middle, Edge4);
                DivideGrid(ref points, x + newWidth, y, width - newWidth, newHeight, Edge1, c2, Edge2, Middle);
                DivideGrid(ref points, x + newWidth, y + newHeight, width - newWidth, height - newHeight, Middle, Edge2, c3, Edge3);
                DivideGrid(ref points, x, y + newHeight, newWidth, height - newHeight, Edge4, Middle, Edge3, c4);
            }
            else	//This is the "base case," where each grid piece is less than the size of a pixel.
            {
                //The four corners of the grid piece will be averaged and drawn as a single pixel.
                double c = (c1 + c2 + c3 + c4) / 4;

                points[(int)(x), (int)(y)] = c;
                if (width == 2)
                {
                    points[(int)(x+1), (int)(y)] = c;
                }
                if (height == 2)
                {
                    points[(int)(x), (int)(y+1)] = c;
                }
                if ((width == 2) &#038;&#038; (height == 2))
                {
                    points[(int)(x + 1), (int)(y+1)] = c;
                }
            }
        }
</pre>
<p>If the rectangle is bigger than a pixel, then this function now calculates the average for the four edges, as well as the average of all four corners with the displacement added for the centre.</p>
<p>After this the values are rectified, so that the values stay within the bounds set, and the <strong>DivideGrid</strong> function is called again for each new rectangle.</p>
<p>If the rectangle is a pixel big, then we have reached the base case, and only the centre is calculated and assigned. At this point the function does not recurse any deeper but now returns.</p>
<p>Lastly we just have <strong>Rectify</strong> and <strong>Displace</strong> which we have dealt with already. <strong>Displace</strong> just calcualtes a random displacement based on the size of the rectangle and the roughness.</p>
<pre name="code" class="c-sharp">
        private double Rectify(double iNum)
        {
            if (iNum < 0)
            {
                iNum = 0;
            }
            else if (iNum > 1.0)
            {
                iNum = 1.0;
            }
            return iNum;
        }

        private double Displace(double SmallSize)
        {

            double Max = SmallSize/ gBigSize * gRoughness;
            return (rnd.NextDouble() - 0.5) * Max;
        }
</pre>
<p>Stay tuned for future posts in this series on fractals&#8230;.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.sergemeunier.com%2Fblog%2Fplasma-fractals%2F&amp;linkname=Fractals%20in%20C%23%3A%20Plasma%20fractals"><img src="http://www.sergemeunier.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>

<p>Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/proportionately-resizing-a-bitmap-in-c-sharp/' rel='bookmark' title='Permanent Link: Proportionately resizing a bitmap in C#'>Proportionately resizing a bitmap in C#</a> <small>Resizing a bitmap and keeping the sides proportions intact &#8211;...</small></li>
<li><a href='http://www.sergemeunier.com/blog/t-square-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: T-Square fractals'>Fractals in C#: T-Square fractals</a> <small>A T-Square fractal is a relatively simple affair. The procedure...</small></li>
<li><a href='http://www.sergemeunier.com/blog/sierpinksi-triangles-and-squares/' rel='bookmark' title='Permanent Link: Fractals in C#: Sierpinksi triangles and squares'>Fractals in C#: Sierpinksi triangles and squares</a> <small>Sierpinski triangles and squares are relatively easy fractals to draw,...</small></li>
</ol></p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.sergemeunier.com/blog/plasma-fractals/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
