Skip to content

Instantly share code, notes, and snippets.

@raulpy271
Last active August 9, 2021 01:03
Show Gist options
  • Save raulpy271/7b187d13ca488999581d4efbc2c6ab69 to your computer and use it in GitHub Desktop.
Save raulpy271/7b187d13ca488999581d4efbc2c6ab69 to your computer and use it in GitHub Desktop.
Creating a recursive program which use tail recursion
type float_operation = float -> float -> float
let shift (operation: float_operation) =
let is_sum = operation 1.0 1.0 = 2.0 in
if is_sum then (-.) else (+.)
;;
let calculate_pi ?(limit=20) () : float =
let rec calculate_a_pi_term
(term: int) (acc: float) (operation: float_operation): float =
if term >= limit then acc
else
let dividend = float_of_int (term * (term + 1) * (term + 2)) in
let step_value = 4.0 /. dividend in
let new_acc = operation acc step_value in
calculate_a_pi_term (term + 2) new_acc (shift operation)
in calculate_a_pi_term 2 3.0 (+.)
;;
let () =
let limit = 1000000000 in
let initial = Sys.time () in
let _ = calculate_pi ~limit () in
let final = Sys.time () in
final -. initial
|> string_of_float
|> print_endline
;;
(* To compile:
ocamlopt -o pi.exe nilakantha.ml
*)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment