Skip to content

Instantly share code, notes, and snippets.

@tautologico
Created March 14, 2013 21:39
Show Gist options
  • Save tautologico/5165511 to your computer and use it in GitHub Desktop.
Save tautologico/5165511 to your computer and use it in GitHub Desktop.
Estimating pi by simulation of Buffon's needle. Pure functional version in OCaml.
(* estimating pi by monte carlo and buffon's needle *)
let mc_pi ~repeats =
let halfpi = asin 1.0 in
let rec loop i crosses =
if i = 0 then crosses
else
let x = Random.float 1.0 in
let theta = Random.float halfpi in
if x <= (0.5 *. (sin theta)) then loop (i-1) (crosses+1)
else loop (i-1) crosses in
let crosses = loop repeats 0 in
(float repeats) /. (float crosses)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment