π Day Bonus!

I plan my Lessons weeks in advance. So, only recently did it dawn upon me that today is March 14th, 3/14, known to nerds all over as Pi Day. Here is yet another nerdy program I wrote to calculate the value of π:

#include <stdio.h>

float wallis(float a)
{
    return(a/(a-1.0)) * (a/(a+1.0));
}

int main()
{
    float p,pi;

    pi = wallis(2.0);
    for( p=4.0; p<=100000.0; p+=2.0 )
    {
        pi *= wallis(p);
    }

    printf("%f\n",pi*2);

    return(0);
}

This code uses the Wallis Product, named for English mathematician John Wallis who thunk it up back in 1656. You can click the Wikipedia link to witness the true horror of the Wallis product as he wrote it, all calculus-y and stuff. Anyway, my code above emulates what he did, working out the calculation several thousand times to get close to π.

Here’s a sample run:

3.141350

Close! I assume I’m doing something wrong, but the code is as much of a proximation to what he did as I can muster in good ol’ C.

Challenge yourself by devising your own π calculation code. It’s fun! Or, at least I think it’s fun.

Leave a Reply