首页 > 解决方案 > 布冯针模拟

问题描述

import java.lang.Math;
public class BuffonNeedle
{
public static void main(String args[])
{
  double drops = 100;
  int hit = 0;
  for(int r=1; r<=6; r++)
  {
     for(int i = 1; i <= drops; i++)
     {
        double y = Math.random() * 2;

        if(Math.sin(Math.random()*Math.PI) + y >= 2.){
           hit++;
        }   
     }

     System.out.println(drops/hit);
     drops = drops * 10;  
  }
 }
}

当约束相距 2 英寸且针为 1 英寸时,为什么这不会产生Pi ?

模拟运行 6 次:100、1000、10000、100000、1000000、10000000。

标签: javamath

解决方案


你需要重置hit

System.out.println(drops/hit);
drops = drops * 10;  
hit = 0;  //<------reset

推荐阅读