円周率計算

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
double f(double x)
{
return sqrt(1-x*x);
}
main()
{
double Ymax = 1.0;
double x,y,P;
int i,num,n,count;
char buf[256];
printf("モンテカルロ法による積分により円周率を求めます。\n");
printf("疑似乱数の発生回数は何回にしますか?");
while(1) {
fgets(buf,100,stdin);
n = sscanf(buf,"%d",&num);
if(n == 1) {
break;
} else if(n == -1) {
continue;
} else {
return 1;
}
}
srand( (unsigned int) time(NULL) );
count = 0;
for(i = 0 ; i < num ; i++){
x = (double)rand() / RAND_MAX * 2 - 1;
y = (double)rand() / RAND_MAX * Ymax;
if(y < f(x)) {
count++;
}
}
P = 4 * Ymax * count / num;
printf("円周率 = %lf\n",P);
return 0;
}

もどる

SEO [PR] 爆速!無料ブログ 無料ホームページ開設 無料ライブ放送