Skip to content

Instantly share code, notes, and snippets.

@peterc
Created November 24, 2024 21:00
Show Gist options
  • Save peterc/dd24475edea090f88319bee7ffbfdc75 to your computer and use it in GitHub Desktop.
Save peterc/dd24475edea090f88319bee7ffbfdc75 to your computer and use it in GitHub Desktop.
Mandelbrot set in Postgres SQL
WITH RECURSIVE
xaxis(x) AS (
SELECT -2.0
UNION ALL
SELECT x + 0.05 FROM xaxis WHERE x < 1.2
),
yaxis(y) AS (
SELECT -1.0
UNION ALL
SELECT y + 0.1 FROM yaxis WHERE y < 1.0
),
m(iter, cx, cy, x, y) AS (
SELECT 0, x, y, 0.0::float, 0.0::float
FROM xaxis, yaxis
UNION ALL
SELECT iter+1, cx, cy,
x*x - y*y + cx,
2.0*x*y + cy
FROM m
WHERE (x*x + y*y) < 4.0 AND iter < 28
),
m2(iter, cx, cy) AS (
SELECT max(iter), cx, cy FROM m GROUP BY cx, cy
),
mandel(line) AS (
SELECT string_agg(
CASE
WHEN iter < 7 THEN ' '
WHEN iter < 14 THEN '.'
WHEN iter < 21 THEN '+'
WHEN iter < 28 THEN '*'
ELSE '#'
END,
'' ORDER BY cx
) as line
FROM m2
GROUP BY cy
ORDER BY cy DESC
)
SELECT line FROM mandel;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment