我写这个是为了通过为 x 和 y 选择一个随机点并检查它是否在单位圆内部或外部来计算 pi,但我遇到了一个问题,我无法找出原因。 N 是一个数字,如 10、100、1000,它是它尝试查看的圆内点数。
然后,如果它在圆的内部,则增加“内部”,然后将内部除以 N 的数量以获得比率,该比率应该更接近 3.1415。
我没有得到任何值,我不确定我是否是这样写的,是否会为 while 循环的每个循环获得一个新的随机数 我是 C 新手,我想在 Java 之后学习它。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
void initrand(void)
{
srand(time(0));
}
float randfloat(void)
{
return rand()/(float)RAND_MAX;
}
int main(void)
{
int n = 10;
float x;
float y;
float pi = 3.1415;
float rootxy;
initrand();
int z = 0;
int inside = 0;
x = randfloat();
y = randfloat();
float area = 0.25 * pi;
float calculatedpi;
rootxy = sqrt(pow(x,2) + (pow(y,2)));
while (z < n){
if (rootxy > area) {
inside++;
z++;
}
else{
return 0;
}
calculatedpi = (inside/n);
printf("%f", calculatedpi);
}
//printf("%f", calculatedpi);
}
<小时/>
这是我调试时修改后的循环,它似乎有效,一直到 calculatedpi 部分,它打印出 0.00000 并且不会从循环内部获取值。
while (z < n){
x = randfloat();
y = randfloat();
rootxy = sqrt(pow(x,2) + (pow(y,2)));
if (rootxy < area) {
inside++;
}
else{
}
z++;
}
calculatedpi = (inside/n);
printf("%f", calculatedpi);
}
最佳答案
以下是计算 pi 的蒙特卡罗方法的说明:
http://www.chem.unl.edu/zeng/joy/mclab/mcintro.html
试试这个:
snits@perelman:~/proj/c=>cat pi.c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define MAXSTR 256
int main(int argc, char **argv)
{
unsigned long int z = 0, n = 0, inside = 0;
float x, y, rootxy, calculatedpi;
char *str;
size_t sz = MAXSTR;
str = (char *)malloc(sz);
if(!str){
fprintf(stderr,"malloc failed. exiting\n");
exit(EXIT_FAILURE);
}
printf("enter number of points to check: ");
getline(&str,&sz,stdin);
sscanf(str,"%lu",&n);
srand(time(0));
while(z < n){
x = rand()/(float)RAND_MAX;
y = rand()/(float)RAND_MAX;
rootxy = sqrt(pow(x,2) + pow(y,2));
if (rootxy <= 1.0)
inside++;
z++;
}
/* pi = 4 * (number of hits)/(number of points checked)
* for simple explanation of monte carlo method for pi
* calculation see:
* http://www.chem.unl.edu/zeng/joy/mclab/mcintro.html
*/
calculatedpi = 4*(float)inside/n;
printf("%f\n",calculatedpi);
return 0;
}
这是一个测试运行:
snits@perelman:~/proj/c=>gcc -Wall -o pi -lm -O2 pi.c
snits@perelman:~/proj/c=>./pi
enter number of points to check: 999999999
3.141638
编辑:注意检查条件是rootxy <= 1.0,而不是rootxy <区域。单位cicle的半径为1.0,如果该点在圆rootxy之内(或之上),则将小于或等于1.0。
关于c - C 语言的 Pi 计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8029219/