Database Reference
In-Depth Information
For this recipe, we'll calculate the Mandelbrot set. Each point in the output takes enough
time that this is a good candidate to parallelize. We can just swap map for pmap and
immediately see a speedup.
How to do it…
The Mandelbrot set can be found by feeding a point into a function and then feeding the
results of this back into the function. The point will either settle on a value or it will take off.
The Mandelbrot set contains the points that don't settle that is, points whose values explode
after repeatedly being feed into the function.
1.
We need a function that takes a point and the maximum number of iterations in order
to return the iteration it escapes on. This just means that the value goes above four:
(defn get-escape-point
[scaled-x scaled-y max-iterations]
(loop [x 0, y 0, iteration 0]
(let [x2 (* x x)
y2 (* y y)]
(if (and (< (+ x2 y2) 4)
(< iteration max-iterations))
(recur (+ (- x2 y2) scaled-x)
(+ (* 2 x y) scaled-y)
(inc iteration))
iteration))))
2.
The scaled points are the pixel points in the output. These are scaled to relative
positions in the Mandelbrot set. Here are the functions that handle the scaling.
Along with a particular x-y coordinate in the output, they're given the range of the
set and the number of pixels in each direction:
(defn scale-to [pixel maximum [lower upper]]
(+ (* (/ pixel maximum)
(Math/abs (- upper lower))) lower))
(defn scale-point
[pixel-x pixel-y max-x max-y set-range]
[(scale-to pixel-x max-x (:x set-range))
(scale-to pixel-y max-y (:y set-range))])
3.
The output-points function returns a sequence of X , Y values for each of the
pixels in the inal output:
(defn output-points [max-x max-y]
(let [range-y (range max-y)]
(mapcat (fn [x] (map #(vector x %) range-y))
(range max-x))))
 
Search WWH ::




Custom Search