🧪 We're running a cheminformatics notebook competition!

Enter by October 4
78 / 106
Mandelbrot with Cython

Mandelbrot with Cython

by Cemrehan Çavdar

Mandelbrot set computation that uses the marimo-cython plugin for speedup.

About this notebook

This notebook draws the Mandelbrot set and compares two ways to compute it. One version uses a Cython-compiled function. The other version uses plain Python. The notebook creates no external dataset. It generates a square pixel grid and counts escape iterations for each point. It uses marimo, numpy, cython, marimo_cython, anywidget, and traitlets. The Cython kernel is compiled at runtime with the cy.compile decorator from marimo_cython.

The reader drags a slider to set the image resolution from 100 to 800 pixels. Both versions then run in parallel on two threads. The reader sees a side-by-side widget with two panels, one labeled Cython and one labeled Python. Each panel shows a spinner while it computes. Each panel then shows the rendered image and the run time in seconds. A caption below the panels reports the pixel size of the grid.

The Cython function is compiled with boundscheck, wraparound, and cdivision options set for speed. Each run fills a numpy integer array with iteration counts up to 200. The notebook encodes each array as a PNG in pure Python with the zlib, struct, and base64 modules. A ThreadPoolExecutor runs both functions, and asyncio.as_completed updates each panel as its result arrives.

Related notebooks