Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing the Spigot algorithm for π (pi)

I'm having a hard time understanding the Spigot algorithm for π (pi) found here at the bottom of the page.

I'm getting lost at the bottom of part 2 "Put A into regular form", I'm not exactly sure how to implement this in C (or any language really)

like image 865
Devan Buggay Avatar asked Nov 03 '10 06:11

Devan Buggay


People also ask

How do you find the nth digit of pi?

Pi = SUMk=0toinfinity 16-k [ 4/(8k+1) – 2/(8k+4) – 1/(8k+5) – 1/(8k+6) ]. The reason this pi formula is so interesting is because it can be used to calculate the N-th digit of Pi (in base 16) without having to calculate all of the previous digits!

Who created algorithm for pi?

The first calculation of π was done by Archimedes of Syracuse (287–212 BC), one of the greatest mathematicians of the ancient world.

How is pi efficient calculated?

The circumference of a circle is found with the formula C=πd=2πr. Thus, pi equals a circle's circumference divided by its diameter. Plug your numbers into a calculator: the result should be roughly 3.14.


1 Answers

  #include <math.h>
  #include <stdio.h>
  #define N 100

  int len = floor(10 * N/3) + 1;
  int A[len];

  for(int i = 0; i < len; ++i) {
    A[i] = 2;
  }

  int nines    = 0;
  int predigit = 0;

  for(int j = 1; j < N + 1; ++j) {        
    int q = 0;

    for(int i = len; i > 0; --i) {
      int x  = 10 * A[i-1] + q*i;
      A[i-1] = x % (2*i - 1);
      q = x / (2*i - 1);
    }

    A[0] = q%10;
    q    = q/10;

    if (9 == q) {
      ++nines;
    }
    else if (10 == q) {
      printf("%d", predigit + 1);

      for (int k = 0; k < nines; ++k) {
        printf("%d", 0);
      }
      predigit, nines = 0;
    }
    else {
      printf("%d", predigit);
      predigit = q;

      if (0 != nines) {    
        for (int k = 0; k < nines; ++k) {
          printf("%d", 9);
        }

        nines = 0;
      }
    }
  }
  printf("%d", predigit);
like image 131
Pedro Silva Avatar answered Oct 14 '22 10:10

Pedro Silva