处理布冯针模拟

时间:2018-08-19 19:02:03

标签: graph processing simulation approximation

大家好,我们今天开始在我的计算机课上编写布冯针模拟程序。我的老师向我们展示了以下代码,但无法解释为什么模拟无法获得准确的近似值。噪声很大,其近似值在3.6至2.8之间变化很大。我认为有些瑕疵,但我看不到哪一部分。我也不理解程序的最后一部分(如何在图形上绘制点)。这18位来自哪里?

如果您有空闲时间,我将不胜感激,因为我目前正在努力地进行计算。预先感谢您提供任何答案。

//set up and define all the variables that we will use
int numTrials = 0;
int intersects = 0;
int lineWidth = 30;
int needleWidth = 0.5*lineWidth;
int boardHeight;
float piApprox;
final float PI = 3.14159265359;

//Defines our initial enviroment properties and creates our grid
void setup(){
  size(600,800);
  background(255);
  stroke(0);
  boardHeight = int (height - 200);
  for (int i = 0; i<=width; i+=lineWidth){ 
    line(i,0,i,boardHeight);
  }
}

//Continously executes the same command
void draw(){
  //generates a random x and y co-ordinate. This becomes the first point
    int a = round(random(width));
  int b = round(random(boardHeight));
  float theta = random(PI);
  //Generates a random x and y co-ordinate which is one needlelength away from first point. This becomes the second point
    int c = round(needleWidth*cos(theta)+a);
  int d = round(needleWidth*sin(theta)+b);
  numTrials++;

  //checks for intersections
  boolean touching = false;
  for (int i = 0; i<=width; i+=lineWidth){
    if ((min(a,c) <= i) && (max(a,c) > i)){
      intersects++;
      touching = true;
    }
  }
  //changes colour of line
    if (touching){
    stroke(0,50,155);
  }
  else{
    stroke(0,155,0);
  }
  line(a,b,c,d);
  //Calculates PI and then calls upon the GUI and the graph functions which are updated after every new line)
    piApprox =((numTrials)/( intersects));
  printData();
  graph();
}

void printData(){
  PFont f;
  f = createFont("LetterGothicStd.ttf",32,true);
  textFont(f,12);
  String e = "Number of Trials:" + numTrials + "     ";
  String f = "PI approximation: " + piApprox;
  fill(255);
  stroke(255);
  rect(0,height-20,400,20);
  fill(0);
  text(e,3,height-8);
  text(f,150,height-8);
}

void graph(){
  //draw PI line
  int piLine = height - 20 - round(18 * PI);
  stroke(255,0,0);
  line(0,piLine,width,piLine);

    //Speed determines how often a point is drawn
  int speed = 5;
  //Clears graph when it reaches the end of the screen
  if (round(numTrials/speed) % width == 0){
    fill(255);
    stroke(255);
    rect(0,boardHeight,width,180);
  }

  //plots points
  if(numTrials % speed == 0){
    int pointW = round(numTrials/speed) % width;
        int pointH = height - 20 - round(18 * piApprox);
    stroke(0,55,55);
    point(pointW,pointH);
  }
}

1 个答案:

答案 0 :(得分:1)

我运行了代码,并删除了字体,更改了颜色(供我使用)并将intersectsnumTrials更改为float类型后,它收敛得很好并且似乎可以正常工作如预期。也许您没有进行足够的试验,这导致您的PI估计值不合理地波动(您可以在下面的截屏中看到,在我的贯穿过程中,是在较早的试验期间发生的)。

我添加了frameRate(600),以使仿真运行速度提高了10倍。

enter image description here

选择数字 18 是为了在舞台底部和画线的位置之间提供合理的边界。更改此数字将影响红线所在的位置和近似线收敛到的y坐标。