At the moment, I'm working on a fractal renderer for stuff like the Mandelbrot set for my computer science coursework, and I want to use recursion instead of iteration on the function below since it will get me more marks.
The original iterative function is below. (I've removed some parts of the function which are for rendering other fractals, but I haven't included them otherwise this would be too long)
function fractal:compute(x,y)
iteration = 1
local zx = 0
local zy = 0
while iteration < self.maxIterations and zx^2 + zy^2 < 4 do
temp = zx
if self.current == "Mandelbrot" then
zx, zy = Mandelbrot(zx,zy,x,y)
end
iteration = iteration + 1
end
return iteration
end
function Mandelbrot(zx, zy, x, y)
return zx^2-zy^2+x, 2*zx*zy+y
end
I've tried to do this with a few methods, like using:
x^2 + y^2 > 4 or iteration == maxIterations
as the base case but for some reason it doesn't seem to work- such as this:
function fractal:compute_Recursively(x,y, cx, cy, count)
if count >= fractal.maxIterations or x^2 + y^2 >= 4 then
return count
else return self.compute_Recursively(x^2-y^2+cx, 2*x*y + cy, cx, cy, count+1)
end
end
function formulae.Mandelbrot_Recursive(x, y, cx, cy, i)
if i >= fractal.maxIterations or x^2 + y^2 >= 4 then
return i
else return formulae.Mandelbrot_R(x^2-y^2+cx, 2*x*y + cy, cx, cy, i+1)
end
end
In my humble opinion, this is not the case when recursion would be useful. Since you need to count the iterations, special measures, like additional parameters, need to be taken to store the current iteration count.
However, below is the code, where you can choose recursive or non-recursive variants of the function by commenting out one of them. To make it more beautiful and hopefully, to get more points, the code is made somewhat more generic. It relies on a small library for complex numbers. Tables with methods are not used.