Home > C++, Fractals, Graphics > It’s Compilin’ Time!

It’s Compilin’ Time!

Further to my last post, I actually have coded a very simply Mandelbrot set renderer in C++.

I’m quite familiar with the basic syntax of C++, so at the outset I though the main challenges would be:

  1. dealing with complex numbers
  2. saving the results as an image file

After some mild Googling both of these challenges were surmountable.

C++ has a standard library header “complex,” which implements complex as a template class. Whatever that means. Anyway, import “complex” and you now have complex number support. See the code below for a demonstration.

For PNG support I used PNGwriter (also available in the Ubuntu repos). PNGwriter’s project site has plenty of example code, and the usage seems very straight forward. The only stumbling block (for me at least) was getting the compiling options right to “link” the PNGwriter library. As it turns out, some or all of the following command is required to compile this code:

g++ main.cpp -o my_program `freetype-config –cflags` -I/usr/local/include -L/usr/local/lib -lpng -lpngwriter -lfreetype

Aside from that bit of unpleasantness, it was really no harder to write this in C++ than in Python. Here it the finished code:

#include <iostream>
#include <complex>
#include <pngwriter.h>

using namespace std;

int main()
    int bailout = 256;
    int size = 800;
    pngwriter png1(size,size,0,"mandel2.png");

    for(int x=0;x<size;x++)
        for(int y=0;y<size;y++)
            int i = 0; //iterations
            complex<double> c(x/(size/4.)-2, y/(size/4.)-2);
            complex<double> z(0, 0);

            while(abs(z)<2 and i<bailout)
                // iterate through mandelbrot dynamic
                z = pow(z, 2) + c;

                // c is outside the mandelbrot set
                float value = (float) i / bailout;
                png1.plot(x, y, value, value, value);

        } // for y
    } //for x


    cout << "done!" << endl;

    return 0;

Remember, if you want to try running this code you will need the PNGwriter library.

The output is of course no different from the Python version that I posted previously, but here it is for the sake of completeness:

The Mandelbrot Set

The Mandelbrot Set

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: