C编程:如何计算Pi到小数点后第四位?
好的,我想做一个C程序,精确到小数点后第四位(3.1415…)。我认为double比float类型更精确。。。即使是万亿次(n=万亿次),该计划也无法超过3.1414。。。有人能帮忙吗?我是否使用了不正确的数据类型来存储Pi值,还是我的循环不正确C编程:如何计算Pi到小数点后第四位?,c,loops,do-while,pi,approximation,C,Loops,Do While,Pi,Approximation,好的,我想做一个C程序,精确到小数点后第四位(3.1415…)。我认为double比float类型更精确。。。即使是万亿次(n=万亿次),该计划也无法超过3.1414。。。有人能帮忙吗?我是否使用了不正确的数据类型来存储Pi值,还是我的循环不正确 #include <stdio.h> #include <stdlib.h> int main(int argc, char** argv) { int n; while(1){ printf(
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
int n;
while(1){
printf("Please enter how many terms (n) you wish to add to approximate Pi: ");
scanf("%d", &n);
if(n>=1)
break;
}
int x;
int count =2;
double negSum=0;
double posSum=0;
double pi = 0;
for(x=1;x<=n;x++){
do{
if(x%2==1){
posSum += (4.0)/(2.0*x-1.0);
count++;
}
else{
negSum += (-4.0)/(2.0*x-1.0);
count++;
}
pi = negSum + posSum;
}
while(pi>3.1414999 && pi<3.14160000);
}
//pi = negSum + posSum;
printf("The value of Pi using your approximation is %f, and the iteration was %d", pi, count);
return (EXIT_SUCCESS);
}
您正在使用的系列:
pi = 4(1 - 1/3 + 1/5 - 1/7 + 1/9 ...)
收敛到π的速度非常慢。它是对4arctan(x)在x=1时的泰勒级数的求值,并且有条件地收敛(它正好位于收敛区间的边缘)。这不是一个计算π的非常有效的方法
除此之外,我没有仔细检查您的实现,但其他一些人在评论中指出了问题。您正在使用的系列:
pi = 4(1 - 1/3 + 1/5 - 1/7 + 1/9 ...)
收敛到π的速度非常慢。它是对4arctan(x)在x=1时的泰勒级数的求值,并且有条件地收敛(它正好位于收敛区间的边缘)。这不是一个计算π的非常有效的方法
除此之外,我没有仔细检查您的实现,但其他一些人在评论中指出了问题。要将Pi计算到小数点后4位,您可以使用: 输出
要将Pi计算到小数点后第四位,可以使用: 输出
为什么在(pi>3.1414999&&pi)时继续近似值
while?为什么有两个循环?有指向各种计算选项的链接。请不要破坏您自己的问题。回滚。为什么在(pi>3.1414999&&pi)时继续近似值while(pi>3.1414999&&pi为什么有两个循环?有指向各种计算选项的链接。请不要破坏您自己的问题。已回滚。
#include <math.h>
#include <stdio.h>
int main(void) {
const double PI = acos(-1), SQRT2 = sqrt(2.0);
double a = 1, b = 1/SQRT2, t = .25, p = 1;
double an, piold, pi = 1, eps = 1e-6; /* use +2 decimal places */
int iteration_count = 0;
do {
++iteration_count;
an = .5 * (a + b);
b = sqrt(a * b);
t -= p * (a - an) * (a - an);
a = an;
p *= 2;
piold = pi;
pi = (a + b) * (a + b) / (4 * t);
} while (fabs(pi - piold) > eps);
printf("got pi=%f with rel. err=%.2e in %d iterations\n",
pi, (pi - PI) / PI, iteration_count);
return 0;
}
$ gcc *.c -lm && ./a.out
got pi=3.141593 with rel. err=2.83e-16 in 3 iterations