/* Pi (Rosetta Code) in Picat. From http://rosettacode.org/wiki/Pi """ Create a program to continually calculate and output the next digit of π (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each digit in succession. The output should be a decimal sequence beginning 3.14159265 ... """ This Picat model was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ % import util. % import cp. main => go. go => pi1, nl. go2 => pi2, nl. go3 => writeln(pi(1000)), nl. % Some small Pi calculations, inspired by % http://stackoverflow.com/questions/407518/code-golf-leibniz-formula-for-pi go4 => % MathPi = math.pi, println(4*sum([((-1)**(I+1))/(2*I-1):I in 1..10**6])), println(4*sum([((-1)**I)/(2*I+1):I in 0..10**6])), println(sum([8/I/(I+2):I in 1..4..10**6])), nl. % Inspired by the D solution pi1 => Ndigits = 0, Q = 1, R = 0, T = Q, K = Q, N = 3, L = N, First = 1, C = 1, % counter for presentation while (1=1) if 4 * Q + R - T < N * T then print(N), C := C + 1, if C mod 30 == 0 then printf(" %% (%d)\n", C) end, Ndigits := Ndigits + 1, if First == 1 then First := 0, print('.') end, NR := 10 * (R - N * T), N := ((10 * (3 * Q + R)) // T) - 10 * N, Q := Q* 10, R := NR else NR := (2 * Q + R) * L, NN := (Q * (7 * K + 2) + R * L) // (T * L), Q := Q * K, T := T* L, L := L + 2, K := K+1, N := NN, R := NR end end, nl. % Inspired by the Erlang version pi2 => pi2b(1,0,1,1,3,3,0). pi2b(Q,R,T,K,N,L,C) => if C == 50 then nl, pi2b(Q,R,T,K,N,L,0) else if (4*Q + R-T) < (N*T) then print(N), P := 10*(R-N*T), pi2b(Q*10, P, T, K, ((10*(3*Q+R)) div T)-10*N, L,C+1) else P := (2*Q+R)*L, M := (Q*(7*K)+2+(R*L)) div (T*L), H := L+2, J := K+ 1, pi2b(Q*K, P, T*L, J, M, H, C) end end, nl. % Get first Len digits of Pi pi(Len) = Res => Ndigits = 0, Q = 1, R = 0, T = Q, K = Q, N = 3, L = N, Res = [], C = 1, % counter for presentation while (C <= Len) if 4 * Q + R - T < N * T then Res := Res ++ [N], C := C + 1, Ndigits := Ndigits + 1, NR := 10 * (R - N * T), N := ((10 * (3 * Q + R)) // T) - 10 * N, Q := Q* 10, R := NR else NR := (2 * Q + R) * L, NN := (Q * (7 * K + 2) + R * L) // (T * L), Q := Q * K, T := T* L, L := L + 2, K := K+1, N := NN, R := NR end end, nl.