Month of Code 14 – Loop

HAPPY PI DAY!

In honor of this day, I decided to make a pi-related loop hack. Don’t take the results to seriously, but it’s a fun little demo.

The code for the loop is using the Leibniz approximation of pi. The for loop uses

var pi=0;
var n=1;
for(var i=0;i<100000000;i++) {
    pi=pi+(4/n)-(4/(n+2));
    n = n+4;
}

The while loop looks like this:

var pi=0;
var n=1;
var i=0;
while(i<100000000) {
    pi=pi+(4/n)-(4/(n+2));
    n = n+4;
    i++;
}

Informally, my testing showed that the while loop was consistently just a hair faster.

Leave a Reply