比较计算多项式的两种不同的算法
#include <stdio.h>
#include <math.h>
#include <time.h>
#define MAXN 100
#define MAXK 1e6
clock_t start,stop;
double duration;
double func1(int n , double a[], double x)
{
double p = a[n];
for(int i = 1;i<=n;i++)
{
p += a[i]*pow(x,i);
}
return p;
}
double func2(int n, double a[], double x)
{
double p = a[n];
for (int i = n; i >=1 ;i--) {
p = a[n-1]+x*p;
}
return p;
}
int main(void)
{
double a[101];
a[0] = 1;
for (int i = 1; i < MAXN; ++i) {
a[i] = 1.0/i;
}
start = clock();
for (int j = 0; j < MAXK; ++j) {
func1(MAXN,a,1.1);
}
stop = clock();
duration = ((double)(stop-start)/CLOCKS_PER_SEC/MAXK);
printf("%.2f\n",(double)(stop-start));
printf("%.2e\n",duration);
start = clock();
for (int j = 0; j < MAXK; ++j) {
func2(MAXN,a,1.1);
}
stop = clock();
duration = ((double)(stop-start)/CLOCKS_PER_SEC/MAXK);
printf("%.2f\n",(double)(stop-start));
printf("%.2e\n",duration);
return 0;
}