當柳上原的風吹向天際的時候...

          真正的快樂來源于創(chuàng)造

            BlogJava :: 首頁 :: 聯(lián)系 :: 聚合  :: 管理
            368 Posts :: 1 Stories :: 201 Comments :: 0 Trackbacks

           

          package com.heyang;

          /**
           * 概率法求PI
           * 
          @author: 何楊(heyang78@gmail.com)
           * @date: 2009-2-19-下午07:08:57
           
          */

          public class FindPie{
              
          public static void main(String[] args){
                  
          int count=100;
                  
          double simuPie;
                  
                  
          do{
                      simuPie
          =getPie(count);
                      count
          +=10;
                  }
          while(isEquslPie(simuPie)==false);
                    
                  System.out.println(
          "當數(shù)量為"+count+"時按概率法得到的Pi="+simuPie+"接近圓周率"+Math.PI);
              }
              
              
              
          public static double getPie(int count){
                  
          int countIntheCorcle=0;
                  
                  
          for(int i=0;i<count;i++){
                      
          double x=Math.random()-0.5;
                      
          double y=Math.random()-0.5;
                      
                      
          if(Math.sqrt(x*x+y*y)<0.5){
                          countIntheCorcle
          ++;
                      }

                  }

                         
                  
          return (double)(4.0d*countIntheCorcle/count);
              }

              
              
          public static boolean isEquslPie(double simuPie){
                  
          return isEqual(simuPie,Math.PI);
              }

              
              
          private static boolean isEqual(double a,double b){
                  
          final double epsilon=0.000001;
                  
                  
          return Math.abs(a-b)<epsilon;
              }

          }

          結(jié)果:
          當數(shù)量為98150時按概率法得到的Pi=3.141593641736295接近圓周率3.141592653589793
          posted on 2009-02-19 17:32 何楊 閱讀(278) 評論(0)  編輯  收藏

          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導航:
           
          主站蜘蛛池模板: 全椒县| 丰原市| 正阳县| 屯门区| 灵武市| 崇州市| 葫芦岛市| 依兰县| 扬州市| 湛江市| 玛纳斯县| 松江区| 屯昌县| 洪雅县| 南木林县| 女性| 陇南市| 玉树县| 来宾市| 龙山县| 荥阳市| 饶河县| 海伦市| 共和县| 繁昌县| 瑞丽市| 桑植县| 呼伦贝尔市| 奉节县| 和田县| 上高县| 永靖县| 齐齐哈尔市| 伊宁县| 广灵县| 磐安县| 河南省| 潍坊市| 邵东县| 马尔康县| 基隆市|