多項式計算調用庫函數pow方法和秦九韶算法,我們來測算下他們的運行效率
計算函數f(x)=1+(Σxi/i)(i從1取到m);
用ctime時間函數來測試運行時間,帶入x=0.9來計算
#include<iostream>#include<cmath>;#include<ctime>using namespace std;double Fn1(double x);double Fn2(double x);#define m 1000000000clock_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調用方法
新聞熱點
疑難解答