THE WEEKEND TEASER: Write a C++ program to calculate the mathematical constant o
ID: 3551638 • Letter: T
Question
THE WEEKEND TEASER:
Write a C++ program to calculate the mathematical constant of PI:
(a) Imagine a circle, whose area is given by: Area=PI*R^2
(b) Now imagine that you divide the circle exactly into 4 quadrants.
(c) The area of one quadrant is hence: Area=0.25*PI*R (d) Now let us set the radius to be R=1;
(e) The equation hence becomes: Area=0.25*PI
(f) So we can simply say: PI = Area*4
y-axis
x=0 y=1
x=0 y=0
Note that this square is 1.0 x 1.0 in size.
x-axis
???????x=1 y=0
Now the big question is how do you calculate the area of the grey shaded quadrant of the circle above? Use a random number generator and guess effectively the correct answer. (Hint: use rand() from <cstdlib> and make sure that you divide through by RAND_MAX.)
The technique you should use is to:
- guess a random number between 0.00 and 1.00 and assign this to x.
- guess a random number between 0.00 and 1.00 and assign this to y.
- find out if this (x,y) coordinate lies inside the grey shaded quadrant or
outside. Hint: sqrt(x +y ).
- Repeat these steps N times, where N is sufficiently big and then find the ratio of points inside the circle divided by the total number N, to determine the area of the grey shaded area.
- Apply this to your equation to find the mathematical constant PI.
Explanation / Answer
Sourcecode: https://www.dropbox.com/s/xsq2j29oimc8v5h/areaCircle.cpp
#include <iostream>
#include<cstdlib>
#include<time.h>
#include<math.h>
#include<iomanip>
using namespace std;
double getRand(void)
{
return rand()/(double)RAND_MAX;
}
int main()
{
cout<<setprecision(7)<<fixed;
time_t t;
srand((unsigned) time(&t));
double x,y,r;
int i,count=0,N=1000000;
for(i=0;i<N;i++)
{
x = getRand();
y = getRand();
r = sqrt(x*x + y*y);
if(r<=1) count++;
}
cout<< 4*count/(double)N;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.