# Daily Archives: January 31, 2014

## A Program to calculate value of PI

Very recently I was attending an online programming course and the Instructor happened to ask a question,

How man of you have ever written a program to calculate value of PI ?What has happened to the world ? In our days students used to attempt at least 2-3 algorithms to find value of PI.It was only then that I realized that I have never even bothered to think about one of the most popular problems in the history of computing. So finally I decided to learn an algorithm to calculate the value of PI, so that next time someone asks me the same question I should not run out of words. This blogpost is for all those out there lie me who have never attempted any algorithm to find the value of PI. Here I will be introducing one of the oldest and simplest algorithm to find the value of the value of PI accurately. The accuracy of the result depends specifically on the machine and the size of the floating point numbers alloted by the programming language. Liu Hui was a mathematician who lived in ancient China, in his days the value of pi was approximated to be 3. But he proved that the ratio of the circumfrence to the diameter of a hexagon inscribed in a circle was 3 therefor value of Pi had to be greater than 3. Here we start by considering a hexagon which is inscribed in a circle with radius =1. So the area of the circle is PI. Let the side length of the hexagon be 1. Then k

_{2n }=√(2+k

_{n}) S

_{n }=√(2-k

_{n}) Area of the polygon = (1/2)(nSa) as the number of the sides of the polygon increases the value of a=radius. So as the value of n increases we get a more and more accurate value of PI. Below is the code for the algorithm

/*Author Vineeth kartha*/ #include<stdio.h> #include<math.h> int main() { double k=1,n=6,S=0,N; int i; long double pi; printf("Enter the number of iterations required : "); scanf("%lf",&N); for(i=0;i<N;i++) { S=sqrt(2-k); n=n*2; k=sqrt(2+k); } n=n/2; pi=n*0.5*S*1; printf("The value of PI is %.10Lf\n",pi); return 0; } The results upto the 16th iteration seems to be correct with this algorithm.

Advertisements