Created
October 3, 2012 18:45
-
-
Save wolfiestyle/3828945 to your computer and use it in GitHub Desktop.
an over-elaborate way of generating the mandelbrot fractal
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
#!/usr/bin/lua | |
-- complex number class | |
do | |
local _meta = { | |
__tostring = function(self) | |
return "(" .. self.re .. ", " .. self.im .. ")" | |
end, | |
__add = function(self, rhs) | |
return Complex(self.re + rhs.re, self.im + rhs.im) | |
end, | |
__sub = function(self, rhs) | |
return Complex(self.re - rhs.re, self.im - rhs.im) | |
end, | |
__mul = function(self, rhs) | |
return Complex(self.re*rhs.re - self.im*rhs.im, self.im*rhs.re + self.re*rhs.im) | |
end, | |
__div = function(self, rhs) | |
local d = rhs:size_sq() | |
return Complex((self.re*rhs.re + self.im*rhs.im)/d, (self.im*rhs.re - self.re*rhs.im)/d) | |
end, | |
__unm = function(self) | |
return Complex(-self.re, -self.im) | |
end | |
} | |
local function _size_sq(self) | |
return self.re*self.re + self.im*self.im | |
end | |
function Complex(_re, _im) | |
local self = { | |
re = _re or 0, | |
im = _im or 0, | |
size_sq = _size_sq | |
} | |
setmetatable(self, _meta) | |
return self | |
end | |
end | |
-- generates the mandelbrot iteration | |
function mandel_gen(c, max_iter) | |
local z = Complex() | |
return function() | |
if max_iter <= 0 then return nil end | |
max_iter = max_iter - 1 | |
z = z*z + c | |
return z:size_sq() < 4 and z or nil | |
end | |
end | |
-- iterates over the [a, b] range in 'ns' steps | |
function range_gen(a, b, ns) | |
incr = ns and (b - a) / (ns - 1) or 1 | |
return coroutine.wrap(function() | |
for i = a, b, incr do | |
coroutine.yield(i) | |
end | |
end) | |
end | |
-- converts a value into an ascii-art gradient | |
do | |
local ascii = " `.,:;*o0@#" | |
function ascii_gradient(val, max) | |
local i = (#ascii - 1) * val / (max + 1) | |
return ascii:sub(i+1, i+1) | |
end | |
end | |
-- draws the mandelbrot set | |
local max_it = 32 | |
for y in range_gen(-1.25, 1.25, 21) do | |
local line = "" | |
for x in range_gen(-2, 1, 40) do | |
local i = 0 | |
for z in mandel_gen(Complex(x, y), max_it) do | |
i = i + 1 | |
end | |
line = line .. ascii_gradient(i, max_it) | |
end | |
print(line) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment