The Computer Language
Benchmarks Game

pidigits OCaml program

source code

(*
 * The Computer Language Benchmarks Game 
 * http://benchmarksgame.alioth.debian.org/
 *
 * contributed by Christophe TROESTLER
 * modified by Matthias Giovannini?
 * ported to Gmp by David Teller
 *)
open Printf
open Gmp.Z2
open Gmp.Z.Infixes

let big_0      = Gmp.Z.zero
let big_1      = Gmp.Z.one
let big_3      = Gmp.Z.of_int 3
let big_4      = Gmp.Z.of_int 4
let big_10     = Gmp.Z.of_int 10
let big_10_neg = Gmp.Z.of_int (-10)

let q = Gmp.Z.of_int 1 
and r = Gmp.Z.of_int 0
and s = Gmp.Z.of_int 0
and t = Gmp.Z.of_int 1

let u = create () and v = create () and w = create ()

let k = ref 0 and digit = create ()

(* Entier part of the linear fractional transform qrst of x *)
let extract x ~out:item= 
  mul u q x;
  add u u r;
  mul v s x;
  add v v t;
  tdiv_q item u v

let next () = extract big_3 ~out:digit
and safe () = extract big_4 ~out:w; Gmp.Z.equal w digit
and produce () = 
  mul r r big_10;
  mul w big_10_neg digit;
  mul v t w;
  add r r v;
  mul q q big_10;  
and consume () =
  incr k;
  let big_k = Gmp.Z.of_int !k in
  let den = Gmp.Z.of_int (2 * !k + 1) in
  let den2 = Gmp.Z.mul_2exp den 1 in
  mul r r den;
  mul u q den2;
  add r r u;
  mul t t den;
  mul v s den2;
  add t t v;
  mul s s big_k;
  mul q q big_k

let digits n = 
  for i = 1 to n do
    next ();
    while not (safe ()) do
      consume ();
      next ();
    done;
    produce ();
    print_string (Gmp.Z.to_string digit);
    if i mod 10 = 0 then 
      printf "\t:%i\n" i;
  done;
  if n mod 10 != 0 then 
    printf "%*s\t:%i\n" (10- n mod 10) "" n

let () = digits (try int_of_string (Array.get Sys.argv 1) with _ -> 27)
    

notes, command-line, and program output

NOTES:
64-bit Ubuntu quad core
The OCaml native-code compiler, version 4.06.0


Sun, 05 Nov 2017 22:27:14 GMT

MAKE:
mv pidigits.ocaml pidigits.ml
/opt/src/ocaml-4.06.0/bin/ocamlopt -noassert -unsafe -fPIC -nodynlink -inline 100 -O3 -I /usr/local/lib/ocaml/gmp gmp.cmxa pidigits.ml -o pidigits.ocaml_run
File "pidigits.ml", line 10, characters 5-11:
Error: Unbound module Gmp
/home/dunham/benchmarksgame/nanobench/makefiles/u64q.programs.Makefile:417: recipe for target 'pidigits.ocaml_run' failed
make: [pidigits.ocaml_run] Error 2 (ignored)
rm pidigits.ml

0.02s to complete and log all make actions

COMMAND LINE:
./pidigits.ocaml_run 2000

MAKE ERROR