Approximating Pi

Status
Not open for further replies.

Wozzy

Well-known member
In honor of Pi Day, I created the following sketch which will approximate Pi to over 4000 decimal places.

Code:
// Pi.ino
// R. Wozniak  March 14th 2014
// Robert dot Wozniak at gmail dot com
// Approximate Pi to 4000+ decimal places on Teensy 3.1
//        http://www.pjrc.com/teensy/index.html
// Based on the simple spigot algorithm developed by mathematicians Stan Wagon and Stanley Rabinowitz in 1995.
// Core code from PHP code here:  http://www.codecodex.com/wiki/index.php?title=Digits_of_pi_calculation
// For Teensy 3.1 set MAXARR to 15000
// For Teensy 3.0 set MAXARR to 2800 (not tested)

  #define SCALE 10000
  #define MAXARR 15000   // for 64k Teensy 3.1
  #define ARRINIT 2000
  int i;
  int j;
  int k=0;
  int carry = 0;
  int arr[MAXARR+1];
  int sum;

void setup(void) {
  Serial.begin(9600);
  delay(5000);      // give time to open serial monitor window.
  Serial.printf("%s", "Pi = 3.");
}
 
void loop(void)
{
        for (i = 0; i <= MAXARR; ++i)
                arr[i] = ARRINIT;
        for (i = MAXARR; i; i -= 14) {
                sum = 0;
                for (j = i; j > 0; --j) {
                        sum = sum*j + SCALE*arr[j];
                        arr[j] = sum % (j*2-1);
                        sum /= (j*2-1);
                }
          PrintPi();
          carry = sum % SCALE;          
        }
}

void PrintPi(void)
{              
  if (k == 0){    
  Serial.printf("%01d", ((carry + sum/SCALE)-3000));
  }    
  if (k != 0){    
  Serial.printf("%04d", ((carry + sum/SCALE)));
  }  
  k=k+1;        
 delay(50);
}

Sample Output:
Code:
  Pi = 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881...
 
Last edited:
Approximation_Pi.jpg

I honor of Pi day, an approximation of pie. :p
 
I should have added the following statements to the code:

Code:
Pi != Pie
Turnovers < Pie
Pie > Cake
 
Status
Not open for further replies.
Back
Top