Working on your programmer 'game'. Calc pi.

OK.  I'm feeling pretty good right now.  I was looking at stackoverflow and saw a question by Jon Skeet,  "What is your most controversial Programming opinion".  Someone posted that developers should know how to code and gave an example of an interview question to calculate pi.  Wow.  I have never seen the calc to generate PI before, so I gave it a whirl.  Here's what I came up with in javascript:


Math.PI;
3.141592653589793
var pi = function() { var a = 0; var b=true; for (var i = 1; i< 10000000; i+=2) { if (b) a+= 1/i; else a-=1/i; b=!b; } return 4 * a; }
undefined
pi();
3.1415924535897797

I only did that in a few minutes, so I might code it differently if I wanted to do more iterations, but it worked for now.
And I also did the area calc for fun too:


var area = function(r) { return Math.PI * r * r; };
undefined
area(1);
3.141592653589793
area(5);
78.53981633974483

Comments

Popular Posts