I have received an admission assignment for the Computer Science program, where I have to approach PI. To calculate pi I have to make a ratio between the area of a square, a circle, the total number of dots and the number of dots within the circle.
The formula of the area of a circle
radius^2 * π or diameter^2 * π / 4
The formula of the area of a square
2*radius^2 or diameter^2
I had the formule ( M / N ) * 4
This is how I got it:
(d^2 * π / 4) : d^2 = M : N
π / 4 = M / N
π = ( M / N ) * 4
the problem is that I don't get pi as output, but about 14.2..
Does anyone know what I am doing wrong?
So in Processing I wrote the following code
float N = 0;
float M = 0;
void setup()
{
size(400, 400);
frameRate(90000);
background(255, 255, 255);
ellipse(200,200,400,400);
}
void draw()
{
/* Random x- en y-coordinate. */
float x = random(0,400);
float dx= (x-200);
float y = random(0,400);
float dy = (y-200);
float d = (float)(Math.sqrt(Math.pow(dx,2) + Math.pow(dy,2)));
/*Red in the circle*/
if(d <= 200 ){
stroke(255,0,0);
M++;
}
else{
stroke(0,255,0); /*green around the circle*/
N++;
}
point(x,y);
println
((M/N)*4);
}
The dots that land inside the circle also land in the square since the circle lays inside the square.
You need to do 4*M/(M+N).