The problem with Pi (i)

Well, it’s not specifically a problem with π. But if we wanted to calculate π to a bunch of decimal places, and print them out, in most programming languages it is challenging. That is partially due to the limitations of data types. Take for example the recursive relation of French mathematician Vieta (1540-1603).

It’s easy to use this in a recursive function to calculate π to a large number of decimal places.

If we look at a C program to calculate this using a double, we end up with a result of the form:

Calc π   = 3.1415926535897940041763832
Actual π = 3.1415926535897932384626433832795

Not ideal, but it is calculated to the precision extent of a double.

First let’s look at the iterative version in C:

#include <stdio.h>
#include <math.h>

int main(void)
{
   double prod, r;
   int i;
   prod = 1.0;
   r = 0.0;

   for (i=1; i<=10; i=i+1) {
      r = sqrt(2.0 + r);
      prod = prod * (0.5*r);
   }

   printf("pi is approximately %.25lf\n", 2.0/prod);

   return 0;
}

It’s easy to use this in a recursive function to calculate π as well:

#include <stdio.h>
#include <math.h>

double recursivePI(int n, double r)
{
   double ra;

   if (n == 1)
      return sqrt(2.0 + r) * 0.5;
   else {
      ra = sqrt(2.0 + r);
      return (ra * 0.5) * recursivePI(n-1,ra);
   }
}

int main(void)
{
   double prod, r;
   r = 0.0;

   prod = recursivePI(50,r);
   printf("pi is approximately %.25lf\n", 2.0/prod);

   return 0;
}

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.