. The Monte Carlo technique is often used to evaluate multi-dimensional integral
ID: 3920246 • Letter: #
Question
. The Monte Carlo technique is often used to evaluate multi-dimensional integrals. As an illustrative example, we can generate random points in the unit square [0, 1]2 in the xy?plane. If we count the points satisfying x^2 + y^2 </ 1 as “hits”, then the hits divided by the total number of points should be an approximation to the area of a quadrant of a disk with unit radius. Since the total area of such a disk is ?, this gives us a (rather inefficient) way of calculating ?.
Write a procedure to estimate the value of ? based on the above Monte Carlo method. Have your program list the deviations from the true value as the number of points increases (for example, give the deviations for every 1000 points).
Use arrays please
Explanation / Answer
Program:
//Include files
#include <iostream>
#include <cmath>
#define LIMIT 200
using namespace std;
//DEfine function
double findPI()
{
//Declare variable
int inter, i;
//Declare variable
double xRand, yRand, distOrigin, pi;
//Declare variable
int ptCircle = 0, ptSquare = 0;
//Loop
for (i = 1; i <= (LIMIT * LIMIT); i++) {
//Create points
//Create x
xRand = double(rand() % (LIMIT + 1)) / LIMIT;
//Create y
yRand = double(rand() % (LIMIT + 1)) / LIMIT;
//Find distance
distOrigin = xRand * xRand + yRand * yRand;
//Check condition
if (distOrigin <= 1)
//Increase circle point count
ptCircle++;
//Increase square point count
ptSquare++;
//Compute pi
pi = double(4 * ptCircle) / ptSquare;
//Check condition
if (i %1000==0)
{
//Print error for every 1000th iteration
cout<<"Error:"<<abs(pi-3.14)<<endl;
}
}
//Return
return pi;
}
//Define function
int main()
{
//Seed
srand(time(NULL));
cout << " Final Value of PI = " << findPI();
//Return
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.