What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleDraw Mandelbrot sets
KeywordsMandelbrot, fractal, chaos
CategoriesGraphics, Algorithms
See my book Visual Basic Graphics Programming for full details. This book also explains many other fractals including Julia sets, Hilbert curves, and Sierpinski curves.

The heart of this program is subroutine DrawMandelbrot. The idea is to repeatedly calculate Z(n+1) = Z^2 + C where Z(n) and C are complex numbers. For each point (X, Y) in the picture, the program sets C = X + i*Y (where i is the imaginary square root of -1). The program evaluates Z(n) repeatedly until it has performed a set limit of steps or the value has a magnitude greater than 2 (it can be shown that the value grows infinitely if it ever exceeds 2). The program assigns the point a color depending on how quickly its magnitude exceeded 2. See the book for more details.

Private Sub DrawMandelbrot()
Const MAX_MAG_SQUARED = 4  ' Work until the magnitude
    ' squared > 4.

Dim clr As Long
Dim i As Integer
Dim j As Integer
Dim ReaC As Double
Dim ImaC As Double
Dim dReaC As Double
Dim dImaC As Double
Dim ReaZ As Double
Dim ImaZ As Double
Dim ReaZ2 As Double
Dim ImaZ2 As Double
Dim wid As Integer
Dim hgt As Integer

    DrawMode = vbCopyPen
    Line (0, 0)-(ScaleWidth, ScaleHeight), BackColor, BF
    MousePointer = vbHourglass
    ' Adjust the aspect ratio.
    ' dReaC is the change in the real part
    ' (X value) for C. dImaC is the change in the
    ' imaginary part (Y value).
    wid = ScaleWidth
    hgt = ScaleHeight
    dReaC = (VisibleXmax - VisibleXmin) / (wid - 1)
    dImaC = (VisibleYmax - VisibleYmin) / (hgt - 1)
    ' Calculate the values.
    ReaC = VisibleXmin
    For i = 1 To wid
        ImaC = VisibleYmin
        For j = 1 To hgt
            ReaZ = 0
            ImaZ = 0
            ReaZ2 = 0
            ImaZ2 = 0
            clr = 1
            Do While clr < MaxIterations And _
                    ReaZ2 + ImaZ2 < MAX_MAG_SQUARED
                ' Calculate Z(clr).
                ReaZ2 = ReaZ * ReaZ
                ImaZ2 = ImaZ * ImaZ
                ImaZ = 2 * ImaZ * ReaZ + ImaC
                ReaZ = ReaZ2 - ImaZ2 + ReaC
                clr = clr + 1
            PSet (i, j), QBColor(clr Mod 16)
            ImaC = ImaC + dImaC
        Next j
        ReaC = ReaC + dReaC
    Next i
    Picture = Image

    MousePointer = vbCrosshair
    DrawMode = vbInvert
End Sub
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.