Database Reference
In-Depth Information
(filter #(<= % 1.0))
count))
4.
This simpliies our deinition of the base (serial) version. This calls count-in-circle
to get the proportion of random points in a unit square that fall inside a circle. It
multiplies this by 4 , which should approximate pi:
(defn mc-pi [n]
(* 4.0 (/ (count-in-circle n) n)))
5.
We'll use a different approach for the simple pmap version. The function that we'll
parallelize will take a point and either return 1 if it's in the circle, or it will return 0 if it
is not. Then, we can add these up to ind the number in the circle:
(defn in-circle-flag [p]
(if (<= (center-dist p) 1.0) 1 0))
(defn mc-pi-pmap [n]
(let [in-circle (->> (repeatedly n rand-point)
(pmap in-circle-flag)
(reduce + 0))]
(* 4.0 (/ in-circle n))))
6.
Moreover, for the version that chunks the input, we'll do something different again.
Instead of creating a sequence of random points and partitioning it, we'll have a
sequence that tells us how large each partition should be and have pmap walk across
it, calling count-in-circle . This means that the creation of larger sequences is
also parallelized:
(defn mc-pi-part
([n] (mc-pi-part 512 n))
([chunk-size n]
(let [step (int
(Math/floor (float (/ n chunk-size))))
remainder (mod n chunk-size)
parts (lazy-seq
(cons remainder
(repeat step chunk-size)))
in-circle (reduce + 0
(pmap count-in-circle
parts))]
(* 4.0 (/ in-circle n)))))
Now, how well do these work? We'll bind our parameters to names, and then we'll run one set
of benchmarks before we take a look at a table of all of them. We'll discuss the results in the
next section.
user=> (def chunk-size 4096)
#'user/chunk-size
 
Search WWH ::




Custom Search