September 14, 2007

Tom Tech Fridays Part III

I wouldn't call this one Tech all that much but I think it is interesting and it is my blog so here goes. The other day I was listening to an algorithms class and they mentioned Stirling's Approximation which basically says this:

If you have a number N, you can approximate the Factorial of that number with an approximation. In computing, if you have a really large number to compute the factorial on, you will have to do a lot of calculations and thus use a lot of CPU time. But the Stirling approximation can save you a lot of time, assuming the number is large enough. But it is only an approximation and the accuracy gets better as the number gets larger.

So being a hands on guy I decided to write a little bit of javascript to illustrate the factorial, Stirling's Approximation, and the difference between the two numbers all on the same page. And sure enough as N gets larger the difference between the two numbers gets smaller. It isn't the prettiest thing in the world, but here it is. The actual code part is only 6 lines:

var fact = 1;
for(i=1; i < 101;i++) {
fact = fact*i;
stirling = (Math.sqrt(2*Math.PI*i))*(Math.pow((i/Math.E),i));
difference = ((fact - stirling)/fact) * 100;
}

Posted by troutm8 at September 14, 2007 11:32 AM