巴丰投针算法的模拟

来源:互联网 发布:电力综合数据网 编辑:程序博客网 时间:2024/06/06 16:34
 

    To run the Buffon needle experiment, we have to work a little harder. When you throw a die, it has to come up with one of six faces. When throwing a needle, however, there are many possible outcomes. You must generate two random numbers: one to describe the starting position and one to describe the angle of the needle with the x - axis.

    Then you need to test whether the needle touches a grid line. Stop after 10,000 tries. 

     Let us agree to generate the lower point of the needle. Its x - coordinate is irrelevant, and you may assume its y - coordinate ylow to be any random number between 0 and 2. However, because it can be a random floating - point number, we use the nextDouble method of the Random class. It returns a random floating - point number between 0 and 1. Multiply by 2 to get a random number between 0 and 2. 

   The angle α between the needle and the x - axis can be any value between 0 degrees and 180 degrees. The upper end of the needle has y – coordinate

               yhigh=ylog+sin(a);

The needle is a hit if yhigh is at least 2. See Figur below:

          

     实现原码如下:

 

import java.util.Random;public class NeedleTest {public static void main(String[] args) {Needle n=new Needle();final int COUNT1=1000;final int COUNT2=10000000;for(int i=1;i<=COUNT1;i++){n.drop();}System.out.printf("尝试:%d,命中的次数比率为:%8.5f",COUNT1,(double)n.getTries()/n.getHits());for(int i=COUNT1+1;i<=COUNT2;i++){n.drop();}System.out.printf("尝试:%d,命中的次数比率为:%8.5f",COUNT2,(double)n.getTries()/n.getHits());}}class Needle{private Random random;    //随机数生成器private int hits;         //击中次数private int tries;        // 尝试次数public Needle(){this.hits=0;this.tries=0;random=new Random();}/** * 获取针压线的次数 */public int getHits(){return hits;}/** * 获取投什总次数 */public int getTries(){return tries;}/** * 往等距线上投针,并记录下针是否压线 * 业务实现: 1. 随机生成针的 最下端底坐标y值 *           2. 随机生成针的角度 *           3. 计算针的上端的位置 */public void drop(){double ylow=2*random.nextDouble();double angle=180*random.nextDouble();//计算针的上端y位置//Math.toRadians(angle): Converts an angle measured in degrees to an approximately equivalent angle measured in radiansdouble yhigh=ylow+Math.sin(Math.toRadians(angle));if(yhigh>=2){hits++;}tries++;}}


 

       

 

 

原创粉丝点击