时间:2021-07-01 10:21:17 帮助过:11人阅读
计算函数f(x)=1+(Σxi/i)(i从1取到m);
用ctime时间函数来测试运行时间,带入x=0.9来计算
#include
#include
#include
using namespace std;
double Fn1(double x);
double Fn2(double x);
#define m 1000000000
clock_t start, stop;
int main(){
double x;
x = 0.9;
start = clock();
cout << Fn1(x) << endl;
stop = clock();
cout << double(stop - start) / CLK_TCK << endl;
//-----------------------------------
start = clock();
cout << Fn2(x) << endl;
stop = clock();
cout << double(stop - start) / CLK_TCK << endl;
return 0;
}
double Fn1(double x){
int i;
double f=1.0;
for (i = 1; i <= m; i++)
f += pow(x, i)/i;
return f;
}
double Fn2(double x){
int i;
double f = 0.0;
for (i = m; i >= 1; i--) /*秦九韶多项式算法*/
f = f*x + 1.0 / i;
return f*x + 1.0;
}
运行时间见下表格
m | 100 | 1000 | 10000 | 100000 | 1000000 | 10000000 | 1000000 | 1000000000 |
Fn1 | 0.001 | 0.001 | 0.003 | 0.015 | 0.157 | 1.619 | 17.955 | 191.608 |
Fn2 | 0 | 0 | 0 | 0.001 | 0.005 | 0.049 | 0.472 | 4.706 |
从运行时间的结果可以看出来,秦九韶算法效率远远高于pow调用方法
以上就介绍了多项式计算的效率测试,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。