算法初步

比较计算多项式的两种不同的算法

#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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容