The Code

While I was working on the assignment I had trouble finding C implementations to serve as examples on the internet, so I’ve decided to share mine on Github.¬†Note that I’m using¬†libbmp¬†for saving my output.

Implementation Details

For our purposes, Newton’s method essentially means that by iteratively computing , such that we obtain the complex function . After a several¬†iterations (I’ve found that to be under 20) each should converge to one of three basins of attraction (the cubic roots of unity: , , and ).

To do this requires us to do a little arithmetic on complex numbers. There are a number of open source C/C++ libraries out there that can take care of the details for us, but I found them to be a bit overkill for computing just one function. As such, I’ve written a few very simple helper functions.

Notice the __device__ and __host__ prefixes? Those indicate that these functions are available both on the cpu (host) and the gpu (device).

Since we’re trying to map a complex function to an image, the x¬†co√∂rdinate in our image will correspond to the real component of z, and the y¬†co√∂rdinate will map to the imaginary component of z. Essentially what we’re going to do is, for each pixel, iteratively evaluate until we converge on one of our basin attractors, and colour that pixel accordingly. Pretty simple!

And Cuda?

Well, it turns out we don’t need to make too many changes for our Cuda version! The main iteration loop is going to stay the same – the only difference is that we no longer need the outer X¬†and Y¬†loops. Instead, each Cuda threads is going to map directly to one pixel in our output matrix.