# A c++ code for calculating pi value. Reply

## A c++ code for calculating pi value.

### — by random number generation.

Attn: Geek world.

Finally I am successful in calculating pi value — less than 0.3% error, by using random number generation. Although my computer needs some fixation on its compiler or path definition etc, there are very good online compilers which helps in testing and running c++ codes: try the given link.

OUTPUT
Computing the value of pi using std::rand()
Enter number of trials: 10000
Enter number of random (x,y) points per trial: 10
pi = 3.14376 +- 0.00519107
average – exact = 0.00216735
CPU time = 0.004027 secs

Here is the code I found by searching a good deal on the web. Yes I did tinker around but only because my own compiler (Turbo C++ on windows 10, 64 bits) was throwing some exceptions on the included headers.

#include
#include
#include
#include
//#include
using namespace std;

double pi_estimate(const unsigned long points)
{
unsigned long hits = 0;
for (unsigned long i = 0; i < points; i++) {
double x = rand() / (RAND_MAX + 1.0);
double y = rand() / (RAND_MAX + 1.0);
if ( (x – 0.5)*(x – 0.5) + (y – 0.5)*(y – 0.5) < 0.25 )
++hits;
}
return 4 * double(hits) / double(points);
}

void measure_pi(const unsigned long trials, const unsigned long points, double& average, double& std_dev)
{
double sum = 0;
double squared_sum = 0;
for (unsigned long t = 0; t < trials; t++)
{
double pi = pi_estimate(points);
sum += pi;
squared_sum += pi * pi;
}
average = sum / trials;
std_dev = squared_sum / trials – average * average;
std_dev = sqrt(std_dev / (trials – 1));
}

int main()
{
//clrscr();
cout << " Computing the value of pi using std::rand()" << endl;
unsigned long trials, points;
cout trials;
cout points;
clock_t start_time = clock();
double average, std_dev;
measure_pi(trials, points, average, std_dev);
double secs = (clock() – start_time) / double(CLOCKS_PER_SEC);
cout << " pi = " << average << " +- " << std_dev << '\n'
<< " average – exact = " << average – 4*atan(1.0) << '\n'
<< " CPU time = " << secs << " secs" << endl;
//getch();
return 0;
}