Tuesday, October 27, 2009

Pi with awk

The other day I needed to find a good rational estimation for pi - don't ask why.
Awk was at hand, and with this few lines I found, what I forgot: 22/7, and 355/113 are the most 'famous' estimations for pi. The next - more precise - approximation is 52.163/16.604, which is not that 'nice.'

Here are the lines:
BEGIN{
x = 3;
y = 1;
pi = 3.1415926535897932384626433832795;
diff = 1;
searchfor = pi;

for(f = 0; f < 100000; f++){
if(x / y < searchfor){x = x + 1;}else{y = y + 1;}
diffnew = abs(searchfor - x / y);
if(diffnew < diff){
printf ("%d/%d=%10.20f\n",x,y, x/y);
diff = diffnew;
}
}
}

function abs(number){
if(number < 0){return -number;}else{return number;}
}

No comments: