给定另一个100阶多项式,用不同方法计算 x 在 1.1 的值:
在开始之前,先理一下思路,主要有两种方式:
1.使用math.h中的pow,通过for循环一次计算
2.通过多项式拆分,从最内部向外计算,例如先计算1/99+x/100的值再依次向外延伸
为实现以上两个方法,并分别验证它们的运行效率,需要用到<time.h>中的clock_t,以及CLK_TCK,完整代码如下:
#include <stdio.h>
#include <math.h>
#include <time.h>
#define MAXN 100
#define MAXK 1e6
#define VX 1.1
'''定义了几个量,便于修改,分别代表阶数、循环次数,变量x的值'''
// 定义方法变量
typedef double (*p)(int n, double a[], double x);
double f1(int n, double a[], double x);
double f2(int n, double a[], double x);
// 此处的p调用了上方定义的方法变量
void time_count(p func, int n, double a[], double x, int m);
// 定义clock的类型,用于计算程序运行时间
clock_t start, stop;
double duration;
int main(){
int i;
double a[MAXN];
// 获取系数列表
for ( i=0;i<=MAXN;i++) a[i] = 1/(double) i;
a [0] = 1;
time_count(f1, MAXN, a, VX, MAXK);
time_count(f2, MAXN, a, VX, MAXK);
return 0;
}
void time_count(p func, int n, double a[], double x, int m){
double p;
int i;
start = clock();
// 循环1000000次,计算平均运行速度
for ( i=0;i<m;i++) p = func(n, a, x);
stop = clock();
duration = (double)(stop - start) / CLK_TCK / m;
printf("ticks1 = %f\n", (double)(stop - start) / m);
printf("duration1 = %6.2e\n", duration);
}
double f1(int n, double a[], double x){
int i;
double p = a[0];
for ( i=1; i<=n; i++){
p += a[i]*pow(x, i);
}
// printf("f1: %.2f\n", p);
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;
}
// printf("f2: %.2f\n", p);
return p;
}
注:MOOC讨论区中其实很多答案不正确,主要体现在a[ ] 数列的值上,需要取到MAXN才对,同时需要对a[0]的值进行初始化,不然a[0]=1/0,为无限大,使得运行结果始终为 1.#J
最终结果:
可见方法2比方法1快了一个量级