现在的位置: 首页 > 综合 > 正文

蒙特拉罗方法求解PI值

2018年05月11日 ⁄ 综合 ⁄ 共 851字 ⁄ 字号 评论关闭

 

Code:
  1. //蒙特卡洛方法求PI  
  2. //原题出自编程之美,但是算法有误,  
  3. //我的是改正过的  
  4. //但是方法可能有问题,精确度不是很好,不过还是发上来了,供我以后该进研究  
  5. //designed by YoungEr.ShEn  
  6. #include <stdio.h>  
  7. #include <math.h>  
  8. #include <stdlib.h>  
  9. #include <time.h>  
  10. #define N 500000  
  11.   
  12. double rand_num()  
  13.     {  
  14.       
  15.         srand(time(NULL));  
  16.         double f;  
  17.   
  18.         f=double((rand()/RAND_MAX));  
  19.         f/=100;  
  20.       
  21.         return f;  
  22.     }  
  23. int main(int argc,char ** argv)  
  24. {  
  25.     int i=0;  
  26.     int caseSum=0;  
  27.     double temp1;  
  28.     double temp2;  
  29.     for(;i<N;i++)  
  30.         {  
  31.             temp1=rand_num();  
  32.             temp2=rand_num();  
  33.             if((temp1*temp1+temp2*temp2) <1)caseSum++;  
  34.         }  
  35.     double PIs;  
  36.     PIs=(double)((caseSum/N));  
  37.     PIs*=4;  
  38.     printf("number PI is %f/n",PIs);  
  39.     printf("%f/n",rand_num());  
  40.     printf("%ld/n",caseSum);  
  41.     printf("%f",RAND_MAX);  
  42.   
  43.   
  44.   
  45. }  

 

抱歉!评论已关闭.