Created
March 14, 2013 21:39
-
-
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.
This file contains hidden or 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
(* 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