Hi all, The code below implements a Monte Carlo simulation to estimate the value of pi. It works, and it was easy to reuse the original single- threaded approach across multiple agents.
How idiomatic is this use of agents? Other than bringing in ForkJoin, are there other idiomatic ways to parallelize divide-and-conquer in Clojure? Cheers, Stuart (defn in-circle? [[x y]] (<= (Math/sqrt (+ (* x x) (* y y))) 1)) (defn random-point [] [(dec (rand 2)) (dec (rand 2))]) ; take samples, tracking number that land ; :in circle and :total number (defn sample-for-pi [count] (reduce (fn [{in :in total :total} point] {:in (if (in-circle? point) (inc in) in) :total (inc total)}) {:in 0 :total 0} (take count (repeatedly random-point)))) (defn guess-from-samples [samples] (assoc samples :guess (/ (* 4.0 (:in samples)) (:total samples)))) ; guess pi by running Monte Carlo simulation count times (defn guess-pi [count] (guess-from-samples (sample-for-pi count))) ; guess pi by running Monte Carlo simulation count times ; spread across n agents (defn guess-pi-agent [n count] (let [count (quot count n) agents (for [_ (range n)] (agent count))] (doseq a agents (send a sample-for-pi)) (apply await agents) (guess-from-samples (reduce (fn [a1 a2] {:in (+ (:in @a1) (:in @a2)) :total (+ (:total @a1) (:total @a2))}) agents)))) --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~----------~----~----~----~------~----~------~--~---