Lesson 5 — Mandelbrot (generate an image)

So far each thread did a little arithmetic. Now each thread will run a loop and we will draw the result. This is the Mandelbrot set: for every pixel we treat its position as a complex number c = x0 + i·y0, iterate z ← z² + c starting from z = 0, and count how many steps it takes for |z| to exceed 2 (we stop at max_iter). Points that never escape are in the set.

One GPU thread computes one pixel. The kernel writes the normalised escape count (iter / max_iter) into output; the page maps that to a colour and paints it on the canvas. The whole image (240×240 pixels) is computed in one dispatch on your GPU.

Your task

The escape iteration is z ← z² + c. Writing z = zx + i·zy and c = x0 + i·y0, the real part of z² + c is zx² − zy² + x0 and the imaginary part is 2·zx·zy + y0 (already written for you). Replace the (* TODO *) with the real part, then click Run on my GPU.

Rendered on your GPU
Fill in the TODO and click "Run on my GPU".
Hint

The real part is (zx *. zx) -. (zy *. zy) +. x0. Note the float operators *., -., +..

This uses a small 240×240 image and max_iter = 100 so it runs instantly. Larger images, deeper zooms, or higher iteration counts cost proportionally more GPU time.