complex - Why is this Mandelbrot set's implementation infeasible: takes a massive amount of time to do?
The Mandelbrot set is defined by complex numbers such as $z=z^2+c$ where $z_0=0$ for the initial point and $c\in\mathbb C$. The numbers grow very fast in the iteration.
z = 0; n = 0; l = {0};
While[n < 9, c = 1 + I; l = Join[l, {z}]; z = z^2 + c; n++];l
If n
is very large, the numbers become too large and impossible to calculate in practical time limits. I don't know what it would look after long time but doubting whether it would look like here.
What is wrong with this implementation? Why does it take so long time to calculate?
Answer
What is wrong: a) you're using exact arithmetic. b) You keep iterating even if the point seems to be escaping.
Try this
ClearAll@prodOrb;
prodOrb[c_, maxIters_: 100, escapeRadius_: 1] :=
NestWhileList[#^2 + c &,
0.,
Abs[#] < escapeRadius &,
1,
maxIters
]
prodOrb[0. + 10. I]
prodOrb[0. + .1 I]
(if you don't need the entire list but only the final point, replace NestWhileList
by NestWhile
).
Here, I use approximate numbers by using 0.
rather than 0
. See this tutorial for more.
EDIT: Since we're doing interactive manipulation:
ClearAll[mnd];
mnd = Compile[{{maxiter, _Integer}, {zinit, _Complex}, {dt, _Real}},
Module[{z, c, iters},
Table[
z = zinit;
c = cr + I*ci;
iters = 0.;
While[(iters < maxiter) && (Abs@z < 2),
iters++;
z = z^2 + c
];
Sqrt[iters/maxiter],
{cr, -2, 2, dt}, {ci, -2, 2, dt}
]
],
CompilationTarget -> "C",
RuntimeOptions -> "Speed"
];
Manipulate[
lst = mnd[100, {1., 1.*I}.p/500, .01];
ArrayPlot[Abs@lst],
{{p, {250, 250}}, Locator}
]
Clicking around changes the fractal. Note the magic numbers sprinkled throughout the code. Why? Because ListContourPlot
is way too slow, so that using the coords of the clicked point ended up being too much of a waste of time (and my coffee break is over).
EDIT2: So much for the break being over. Here we have the Mandelbrot set being blown away by strong winds:
tbl = Table[
lst = mnd[100, (1 + 1.*I)*p/500, .01];
ArrayPlot[Abs@lst],
{p, 0, 500, 10}
];
ListAnimate[tbl]
And see, here it is, sliding off the table while being melted:
tbl2 = Table[
mnd[100, (1 + 1.*I)*p/500, .05] // Abs //
ListPlot3D[#, PlotRange -> {0, 1},
ColorFunction -> "BlueGreenYellow", Axes -> False,
Boxed -> False,
ViewVertical -> {0, (p/500), Sqrt[1 - (p/500)^2]}] &,
{p, 0, 500, 25}
];
(this is very slow, because ListPlot3D
is very slow)
Maximal silliness has now been achieved. Or has it?
Comments
Post a Comment