Skip to content

Instantly share code, notes, and snippets.

@rcampbell
Created August 20, 2010 13:46
Show Gist options
  • Save rcampbell/540352 to your computer and use it in GitHub Desktop.
Save rcampbell/540352 to your computer and use it in GitHub Desktop.
Monte Carlo calculation of Pi
(ns mc.core
(:use [clojure.contrib.seq-utils :only [separate]]))
; http://math.fullerton.edu/mathews/n2003/MonteCarloPiMod.html
(defn- square [x]
(* x x))
(defn- distance [[x y]]
(Math/sqrt (+ (square x)
(square y))))
(defn- point
([] (point (rand) (rand)))
([x y] (vector x y)))
(defn- in-circle? [point]
(< (distance point) 1))
(defn- points []
(lazy-seq (cons (point) (points))))
(defn monte-carlo-pi [n]
(let [[in out] (separate in-circle? (take n (points)))]
(double (* 4 (/ (count in) (+ (count in) (count out)))))))
; > (monte-carlo-pi 100000)
; 3.14456
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment