[数据结构] 算法效率 以“计算多项式值”为例

计算多项式值

计算下面多项式的数值: f ( x ) = ∑ i = 0 9 i ∗ x i f\left ( x \right )=\sum_{i=0}^{9}i*x^{i} f(x)=i=09ixi

  • 途径1:通过循环来实现 f ( x ) = a 0 + a 1 x + ⋅ ⋅ ⋅ + a n − 1 x n − 1 + a n x n f\left ( x \right )= a_{0}+a_{1}x+\cdot \cdot \cdot +a_{n-1}x^{n-1}+a_{n}x^{n} f(x)=a0+a1x++an1xn1+anxn
  • 途径2:通过秦九韶算法来实现 f ( x ) = a 0 + x ( a 1 + x ( ⋅ ⋅ ⋅ ( a n − 1 + x ( a n ) ) ⋅ ⋅ ⋅ ) ) f\left ( x \right )= a_{0}+x(a_{1}+x(\cdot \cdot \cdot \left ( a_{n-1}+x\left ( a_{n} \right ) \right )\cdot \cdot \cdot )) f(x)=a0+x(a1+x((an1+x(an))))

两种不同的计算方法时间比较

#include <stdio.h>
#include <math.h>
#include <time.h>

#define MAXN 10
#define MAXK 1e7

clock_t start, stop;
double duration;
double f1(int n, double a[], double x);//循环方法实现计算
double f2(int n, double a[], double x);//秦九韶算法实现计算

int main()
{
	int i;
	double a[MAXN];
	for (i = 0; i <= MAXN ; i++)
		a[i] = (double)i;

	start = clock();
	for (i = 0; i <= MAXK;i++)
		f1(MAXN - 1, a, 1.1);
	stop = clock();
	duration = ((double)(stop - start)) / CLK_TCK / MAXK;
	printf("ticks1 = %f\n", (double)(stop - start));
	printf("duration1 = %6.2e\n",duration);

	start = clock();
	for (i = 0; i <= MAXK; i++)
		f2(MAXN - 1, a, 1.1);
	stop = clock();
	duration = ((double)(stop - start)) / CLK_TCK / MAXK;
	printf("ticks2 = %f\n", (double)(stop - start));
	printf("duration2 = %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));
	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;
}

###运行结果
运行结果


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值