Skip to content

Instantly share code, notes, and snippets.

@rijesha
Created January 20, 2018 22:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rijesha/4ce0fc35c5907f0c422cb670ad78f2e0 to your computer and use it in GitHub Desktop.
Save rijesha/4ce0fc35c5907f0c422cb670ad78f2e0 to your computer and use it in GitHub Desktop.
(*Probabilistically Calculating pi with OCaml*)
let f x = float_of_int x in
let hyp a b = sqrt((a *. a ) +. (b *. b)) in
let randcheck () = hyp (Random.float 1.0) (Random.float 1.0) < 1.0 in
let total_iterations = 1000000 in
let count_inside_quarter_circle = ref 0 in
for i = 1 to total_iterations do
let a = if (randcheck ()) then 1 else 0 in
count_inside_quarter_circle := !count_inside_quarter_circle + a;
done;
print_string (string_of_float ( 4.0 *. ( (f !count_inside_quarter_circle) /. (f total_iterations) )));;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment