普通算法
f1(x) = a0 + a1x + a2x^2 + ... + an-1x^(n-1) + anx^n
double f1(int n, double a[], double x){
int i;
double p = a[0];
for (int i = 1; i <= n; ++i){
p += (a[i] * pow(x, i));
}
return p;
}
秦九韶算法
每次把x當(dāng)做公因子提取出來(lái),然后從最里面向外計(jì)算。
f2(x) = a0 + x(a1 + x(...x(an-1 + x(an))...))
double f2(int n, double a[], double x){
int i;
double p = a[n];
for (i = n; i > 0; --i){
p = a[i - 1] + x * p;
}
return p;
}
速度測(cè)試
#include <iostream>
#include <vector>
#include <time.h>
#define MAXN 10 /* 多項(xiàng)式最大項(xiàng)數(shù),即多項(xiàng)式階數(shù)+1 */
#define MAXK 1e6 /* 被測(cè)函數(shù)最大重復(fù)調(diào)用次數(shù) */
using namespace std;
clock_t start, stop;
/* clock_t是clock()函數(shù)返回的變量類型 */
double duration;
/* 記錄函數(shù)運(yùn)行時(shí)間,以秒為單位 */
double f1(int n, double a[], double x){
int i;
double p = a[0];
for (int i = 1; i <= n; ++i){
p += (a[i] * pow(x, i));
}
return p;
}
double f2(int n, double a[], double x){
int i;
double p = a[n];
for (i = n; i > 0; --i){
p = a[i - 1] + x * p;
}
return p;
}
int main(){
int i;
double a[MAXN]; /* 存儲(chǔ)多項(xiàng)式的系數(shù) */
for (i = 0; i < MAXN; ++i){
a[i] = (double)i;
}
/* 不在測(cè)試范圍的準(zhǔn)備工作寫在clock()調(diào)用之前 */
start = clock(); /* 開(kāi)始計(jì)時(shí) */
for (int j = 0; j < MAXK; ++j){
f1(MAXN - 1, a, 1.1);
}
stop = clock(); /* 停止計(jì)時(shí) */
duration = ((double)(stop - start)) / CLK_TCK / MAXK;
printf("f1-duration: %6.2e\n", duration);
start = clock(); /* 開(kāi)始計(jì)時(shí) */
for (int j = 0; j < MAXK; ++j){
f2(MAXN - 1, a, 1.1);
}
stop = clock(); /* 停止計(jì)時(shí) */
duration = ((double)(stop - start)) / CLK_TCK / MAXK;
printf("f2-duration: %6.2e\n", duration);
return 0;
}
運(yùn)行結(jié)果
分析
可以看出來(lái)單次運(yùn)行的時(shí)間上,秦九韶算法比普通算法快了一個(gè)數(shù)量級(jí)。