我已经收到了计算机科学计划的录取通知,我必须在那里学习PI。为了计算pi,我必须在正方形,圆形的面积,圆点总数和圆点数之间求一个比率。
圆的面积公式
半径^ 2 *π或直径^ 2 *π/ 4
正方形面积的公式
2 *半径^ 2或直径^ 2
我的配方为(M / N)* 4
这是我得到的方式:
(d ^ 2 *π/ 4):d ^ 2 = M:N
π/ 4 = M / N
π=(M / N)* 4
问题是我没有得到pi作为输出,而是大约14.2。
有人知道我在做什么错吗?
因此在处理过程中,我编写了以下代码
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);
}
答案 0 :(得分:2)
落在圆内的点也落在正方形内,因为圆位于正方形内。
您需要执行4 * M /(M + N)