Created
August 20, 2010 13:46
-
-
Save rcampbell/540352 to your computer and use it in GitHub Desktop.
Monte Carlo calculation of Pi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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