这个问题属于数值分析的内容,或者是离散数学。
这个题目的意思是给你了一个多项式,然后用这个多项式来去逼近Pi,在学科中,这个多项式是应该自己找寻的,题目直接给了出来。
几个问题是提出因为在计算机的多项式的计算都有精确度,根据我们需求的不同精确度计算机的在同一算法同一浮点运算的前提下,时间开销也是不同的,所以问题转化为若计算到3。14,3.141,3.1415,3.14159这个不同精确度下,需要计算机计算多少次(次数跟算法直接挂钩,我们知道循环次数和前提计算机的浮点运算速度,就能推断出时间开销,这个在科学运算中,十分很重要,因为一次循环往往就耗费大量时间,后续可以提升算法时间复杂度,提升计算机的浮点运算量,来尽量快的模拟结果)
下面是代码:#include <iostream>
using namespace std;
int signal(int n);
float n_for_sum(int i);
int main()
{
bool check_for314=false;
bool check_for3141=false;
bool check_for31415=false;
bool check_for314159=false;
float sum=0;
int i=0;
while(1)
{
sum=sum+n_for_sum(i);
// printf("i = %d sum = %.6f\n",i,sum);
if(sum<3.144&& sum>3.135&&check_for314==false)
{
printf("before find 3.14 i-1 = %d sum = %.6f\n",i-1,sum-n_for_sum(i-1));
printf("find approx 3.14 i = %d sum = %.6f\n",i,sum);
printf("after find 3.14 i+1 = %d sum = %.6f\n",i+1,sum+n_for_sum(i+1));
check_for314=true;
printf("\n");
}
if(sum<3.1414&& sum>3.1405&&check_for3141==false)
{
printf("before find 3.141 i-1 = %d sum = %.6f\n",i-1,sum-n_for_sum(i-1));
printf("find approx 3.141 i = %d sum = %.6f\n",i,sum);
printf("after find 3.141 i+1 = %d sum = %.6f\n",i+1,sum+n_for_sum(i+1));
check_for3141=true;
printf("\n");
}
if(sum<3.14154&& sum>3.14145&&check_for31415==false)
{
printf("before find 3.1415 i-1 = %d sum = %.6f\n",i-1,sum-n_for_sum(i-1));
printf("find approx 3.1415 i = %d sum = %.6f\n",i,sum);
printf("after find 3.1415 i+1 = %d sum = %.6f\n",i+1,sum+n_for_sum(i+1));
check_for31415=true;
printf("\n");
}
if(sum<3.141594&& sum>3.141585)
{
printf("before find 3.14159 i-1 = %d sum = %.6f\n",i-1,sum-n_for_sum(i-1));
printf("find approx 3.14159 i = %d sum = %.6f\n",i,sum);
printf("after find 3.14159 i+1 = %d sum = %.6f\n",i+1,sum+n_for_sum(i+1));
check_for314159=true;
printf("\n");
break;
}
i++;
}
return 0;
}
int signal(int n)
{
return (-1)*(n%2*2)+1;
}
float n_for_sum(int i)
{
return signal(i)*4.0/float(2*i+1);
}
说明下:每组的i是结果,我把前后两项也打出来进行比较,其实可以前后四项更科学,其实这个写法是局部最优下求全局最优的情况,具体证明过程就不写了。
结果如下:
before find 3.14 i-1 = 150 sum = 3.121724
find approx 3.14 i = 151 sum = 3.135013
after find 3.14 i+1 = 152 sum = 3.148128
before find 3.141 i-1 = 914 sum = 3.138315
find approx 3.141 i = 915 sum = 3.140502
after find 3.141 i+1 = 916 sum = 3.142684
before find 3.1415 i-1 = 6696 sum = 3.141151
find approx 3.1415 i = 6697 sum = 3.141450
after find 3.1415 i+1 = 6698 sum = 3.141749
before find 3.14159 i-1 = 91678 sum = 3.141563
find approx 3.14159 i = 91679 sum = 3.141585
after find 3.14159 i+1 = 91680 sum = 3.141607
--------------------------------
Process exited after 0.1054 seconds with return value 0
请按任意键继续. . . |