Last active
June 12, 2020 17:10
-
-
Save lovasoa/905a8dc1ab35734f3388a17fde60652a to your computer and use it in GitHub Desktop.
Mandelbrot rendering implemented in SQL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
WITH RECURSIVE | |
-- First, we define the grid we are working on | |
xaxis(x) AS (VALUES(-2.0) UNION ALL SELECT x+0.05 FROM xaxis WHERE x<0.5), | |
yaxis(y) AS (VALUES(-1) UNION ALL SELECT y+0.1 FROM yaxis WHERE y<1), | |
-- Then we compute the iterations of the mandelbrot function | |
iterations(iter, cx, cy, x, y) AS ( -- one value per iteration step per point | |
SELECT 0, x, y, 0.0, 0.0 FROM xaxis, yaxis -- c = cx + i * cy | |
UNION ALL | |
SELECT iter+1, cx, cy, x*x-y*y + cx, 2.0*x*y + cy -- z(iter+1) = z(iter)^2 + c. x=Re(z(iter+1)), y=Im(z(iter+1)) | |
FROM iterations | |
WHERE (x*x + y*y) < 4 AND iter<50 -- if z(n)^2 >= 4, we diverged | |
), | |
max_iter(iter, cx, cy) AS ( -- the number of iterations it takes to diverge for each point | |
SELECT max(iter), cx, cy FROM iterations GROUP BY cx, cy | |
), | |
lines(t) AS ( | |
-- For the values of c where the function does not diverge, we made 50 iterations | |
SELECT group_concat(case iter when 50 then '*' else ' ' end, '') | |
FROM max_iter GROUP BY cy | |
) | |
SELECT group_concat(t,x'0a') as mandelbrot FROM lines; | |
-- source: https://sqlite.org/lang_with.html | |
-- changed the table names and added comments to make the code clearer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment