Thursday, February 4, 2010

Mandelbrot Fractal - Part 2


This is the follow-up to part 1. I'm going to continue the explanation from part 1 and describe some initial pseudocode. Beware: this pseudocode is slow. I'll probably handle optimization in a later post.

In my previous post I gave you two formulas that describe the Mandelbrot set :

|z| > 2
z = z2 + c


I also told you what z and c were (complex numbers), and how c relates to the screen point.

First of all, I'm going to describe 3 basic operations with complex numbers. You'll use these to calculate the formulas.

a and b are complex numbers, where .real is the real part, and .imag is the imaginary part.

(a + b).real = a.real + b.real
(a + b).imag = a.imag + b.imag

(a * b).real = (a.real * b.real) - (b.imag * b.imag)
(a * b).imag = (a.imag * b.real) + (a.real * b.imag)

|a| = sqrt( (a.real * a.real) + (a.imag * a.imag) )

Be careful with multiplication: the imaginary part depends on the original real part. This means, save the real part in a temporary variable! It drove me crazy when I first programmed the fractal.

In my previous post, I told you the Mandelbrot set is evaluated using a iterative process: if the condition (|z| > 2) is false, try again, until the counter reaches the limit, or the condition evaluates to true. That counter is going to be important in the process, since it'll determine the final color for the point. I'll refer to it as i.

Knowing this, we can write down some pseudocode, like this:

i = 0
limit = 20

z.real = 0
z.imag = 0

c.real = x
c.imag = y

while i < limit then
- if sqrt( z.real2 + z.imag2 ) > 2 then
-- plot as white
-- break
- z = z2 + c
- i = i + 1

If you plot that code, using C, you'll notice two things:
  • It's ugly.
  • It's slow.

It should look like the photo, if everything ia correct. The photo fractal uses limit=50. It's ugly, but it changes dramatically when you add color. I'll address that in the next part.

No comments:

Post a Comment