jblog
toc

Pi Day MMXVII

2018-03-14, post № 192

C, mathematics, programming, #improper integral, #power series, #source layout, #Taylor series

Today it is the fourteenth of March 2018. Today’s date — when written in the M/D/Y format —, 3/14/18, looks close enough to Archimedes’ constant’s decimal representation for it to be the constant’s celebratory day.
As always on Pi Day, I have implemented an algorithm to generate 𝜋, albeit this year’s accuracy is not the greatest (Try it online [1]).

           typedef double d;typedef long l;l f(l n
      ){l f=1;while(n>1)f*=n--;return f;}d ne(d v,
    l p){d r=1;for(l k=0;k<p;k++)r*=v;return r;}d 
   ps(d(*c)(l),l i,d x){d s=0;for(l k=0;k<i;k++)s 
  +=c(k)*       ne(x,        k);return            
 s;}           d exc         (     l              
n){            return       1./f (n)              
              ; } d         exp(d x               
             )   {         return                 
            ps(exc        ,20,x);}                
           d G( d         x){return               
           exp(-x        *x);}d I                 
          (d a,d         b,d g,d                  
        (* f)(d         )){d cs=                  
       0;for( d         x=a;x<=                   
      b;x +=g)         cs+=f(x)                   
    *g;return          cs ;  }          int       
  main( ) { d          pi_root         =I(        
 -2.5, 2.5 ,           1e-4,G);      d pi         
= pi_root *            pi_root+(0xf&0xf0          
) ; printf(             "%c%c%c%c%c%f%c"          
,'p','i',                ' ','=',' ',pi           
  ,'\n'                     ) ; }                 

I use various methods of generating 𝜋 throughout the Pi Days; this time I chose to use an improper integral paired with a power series. 𝜋 is calculated using a famous identity involving infinite continuous sums, roots, e, statistics and — of course — 𝜋.

\int\limits_{-\infty}^\infty e^{-x^2}\mathrm{d}x=\sqrt{\pi}

Furthermore, to compute 𝑒, the following identity is used.

\exp{x}=\sum\limits_{n=0}^\infty\frac{x^n}{n!}

Both formulae are combined, the approximated value of \sqrt{\pi} is squared and 𝜋 is printed to stdout.

You can download this program’s prettified (some call it obfuscated, see above) source code pi.c and also the (nearly, as #include is not missing so that the compiler does not need to guess my dependencies) equivalent code in a more traditional source layout tpi.c.

Happy Pi Day!

Extra assets: pi_no-warnings.c

Footnotes

  1. [2020-08-07] In the TIO link, there is some leading and trailing whitespace around the 𝜋.