- //蒙特卡洛方法求PI
- //原题出自编程之美,但是算法有误,
- //我的是改正过的
- //但是方法可能有问题,精确度不是很好,不过还是发上来了,供我以后该进研究
- //designed by YoungEr.ShEn
- #include <stdio.h>
- #include <math.h>
- #include <stdlib.h>
- #include <time.h>
- #define N 500000
- double rand_num()
- {
- srand(time(NULL));
- double f;
- f=double((rand()/RAND_MAX));
- f/=100;
- return f;
- }
- int main(int argc,char ** argv)
- {
- int i=0;
- int caseSum=0;
- double temp1;
- double temp2;
- for(;i<N;i++)
- {
- temp1=rand_num();
- temp2=rand_num();
- if((temp1*temp1+temp2*temp2) <1)caseSum++;
- }
- double PIs;
- PIs=(double)((caseSum/N));
- PIs*=4;
- printf("number PI is %f/n",PIs);
- printf("%f/n",rand_num());
- printf("%ld/n",caseSum);
- printf("%f",RAND_MAX);
- }