|
Estimate pi Using the Monte Carlo Method
// calculate PI by throwing darts
#include <iostream>
using namespace std;
#include <cstdlib>
#include <ctime>
#include <iomanip>
double darts(int); //prototype
int main()
{
int num_darts;
double PI;
cout << "Enter the number of darts to be thrown:
";
cin >> num_darts;
srand(time(NULL)); // random number seed
PI = darts(num_darts);
cout << "For " << num_darts << "
darts thrown the value of PI is " << PI << endl;
}
double darts(int num_darts)
{
int i, p=0;
for (i = 1; i <= num_darts; i++)
{
double x, y;
x = static_cast< double >( rand() )/RAND_MAX;
y = static_cast< double >( rand() )/RAND_MAX;
if ( (x*x + y*y) <= 1.0)
p++;
}
return 4.0*static_cast< double >( p )/num_darts;
}
% g++ ran_pi.cpp
% a.out
Enter the number of darts to be thrown: 500
For 500 darts thrown the value of PI is 3.176
|