
Create a program to continually calculate and output the next decimal digit of   



π


{\displaystyle \pi }

   (pi).

The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.

The output should be a decimal sequence beginning   3.14159265 ...



Note: this task is about   calculating   pi.   For information on built-in pi constants see Real constants and functions.



Related Task Arithmetic-geometric mean/Calculate Pi

/* Uses the algorithm of S. Rabinowicz and S. Wagon, "A Spigot Algorithm */
/* for the Digits of Pi".                                                */
(subrg, fofl, size):
Pi_Spigot: procedure options (main);                 /* 21 January 2012. */
   declare (n, len) fixed binary;
 
   n = 1000;
   len = 10*n / 3;
   begin;
      declare ( i, j, k, q, nines, predigit ) fixed binary;
      declare x fixed binary (31);
      declare a(len) fixed binary (31);
 
      a = 2; /* Start with 2s */
      nines, predigit = 0; /* First predigit is a 0 */
      do j = 1 to n;
         q = 0;
         do i = len to 1 by -1; /* Work backwards */
            x = 10*a(i) + q*i;
            a(i) = mod (x, (2*i-1));
            q = x / (2*i-1);
         end;
         a(1) = mod(q, 10); q = q / 10;
         if q = 9 then nines = nines + 1;
         else if q = 10 then
            do;
               put edit(predigit+1) (f(1));
               do k = 1 to nines;
                  put edit ('0')(a(1)); /* zeros */
               end;
               predigit, nines = 0;
            end;
         else
            do;
               put edit(predigit) (f(1)); predigit = q;
               do k = 1 to nines; put edit ('9')(a(1)); end;
               nines = 0;
            end;
      end;
      put edit(predigit) (f(1));
   end; /* of begin block */
end Pi_Spigot;