Click to See Complete Forum and Search --> : Jeremy


Gnu/Vince
02-04-2002, 12:44 AM
The program below compiles fine, but won't give me the correct result. Normally it would calculate Pi, but instead I get a '3' followed by infinite zeros. Here's my O'Caml code (warning: lots of big_int):


open Big_int

let _ =
let k = ref (big_int_of_int 2) in
let a = ref (big_int_of_int 4) in
let b = ref unit_big_int in
let a1 = ref (big_int_of_int 12) in
let b1 = ref (big_int_of_int 4) in

while true do
let p = (square_big_int !k) in
let q = (add_big_int (mult_big_int (big_int_of_int 2) !k) unit_big_int) in
k := (add_big_int !k unit_big_int);
a := !a1;
b := !b1;
a1:= (add_big_int (mult_big_int p !a) (mult_big_int q !a1));
b1:= (add_big_int (mult_big_int p !b) (mult_big_int q !b1));
let d = ref (div_big_int !a !b) in
let d1 = ref (div_big_int !a1 !b1) in

while (eq_big_int !d !d1) do
Printf.printf "%s" (string_of_big_int !d);
flush stdout;
a := mult_big_int (mod_big_int !a !b) (big_int_of_int 10);
a1:= mult_big_int (mod_big_int !a1 !b1) (big_int_of_int 10);
d := div_big_int !a !b;
d1:= div_big_int !a1 !b1;
done;
done



and if that can be of any help, the Python version:


#!/usr/bin/env python

from sys import stdout

k, a, b, a1, b1 = 2, 4, 1, 12, 4

while 1:
# Next approximation
p, q, k = k*k, 2*k+1, k+1
a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
# Print common digits
d = a / b
d1 = a1 / b1
while d == d1:
stdout.write("%d" % d)
stdout.flush()
a, a1 = 10*(a%b), 10*(a1%b1)
d, d1 = a / b, a1 / b1



Thanks a lot.

Gnu/Vince
02-04-2002, 02:11 PM
Nevermind, I got it:


let _ =
let k = ref (big_int_of_int 2) in
let a = ref (big_int_of_int 4) in
let b = ref unit_big_int in
let a1 = ref (big_int_of_int 12) in
let b1 = ref (big_int_of_int 4) in

(* Moo *)
let a2 = ref (big_int_of_int 2) in
let b2 = ref (big_int_of_int 2) in

while true do
let p = (square_big_int !k) in
let q = (add_big_int (mult_big_int (big_int_of_int 2) !k) unit_big_int) in
k := (add_big_int !k unit_big_int);


a2:= !a;
b2:= !b;
a := !a1;
b := !b1;
a1:= (add_big_int (mult_big_int p !a2) (mult_big_int q !a1));
b1:= (add_big_int (mult_big_int p !b2) (mult_big_int q !b1));

let d = ref (div_big_int !a !b) in
let d1 = ref (div_big_int !a1 !b1) in

while (eq_big_int !d !d1) do
Printf.printf "%s" (string_of_big_int !d);
flush stdout;
a := mult_big_int (mod_big_int !a !b) (big_int_of_int 10);
a1:= mult_big_int (mod_big_int !a1 !b1) (big_int_of_int 10);
d := div_big_int !a !b;
d1:= div_big_int !a1 !b1;
done;
done