您的位置:首页 > 编程语言 > C语言/C++

霍纳法则(Horner Rule)介绍及C语言实现

2014-03-30 09:51 411 查看



参考自:http://flynoi.blog.hexun.com/31272178_d.html



霍纳法则简介

假设有n+2个实数a0,a1,…,an,和x的序列,要对多项式Pn(x)= anxn+an-1xn-1+…+a1x+a0求值,直接方法是对每一项分别求值,并把每一项求的值累加起来,这种方法十分低效,它需要进行n+(n-1)+…+1=n(n+1)/2次乘法运算和n次加法运算。有没有更高效的算法呢?答案是肯定的。通过如下变换我们可以得到一种快得多的算法,即Pn(x)= anxn +an-1xn-1+…+a1x+a0=((…(((anx +an-1)x+an-2)x+ an-3)…)x+a1)x+a0,这种求值的安排我们称为霍纳法则。



霍纳法则C语言实例

/* 霍纳算法实例 */

#include <stdio.h>

long int
horner(int coefficient[], int n, int x) //coefficient[]为待求多项式的系数数组,n为数组大小,x为多项式中未知数x的具体值
{                                       //注意:coefficient[0]存放系数a0,coefficient[1]存放系数a1,以此类推…
int i;
long int result;

result = coefficient[n-1];
for(i = 1; i <= n-1; i++)
{
result = result * x + coefficient[n-1-i];
}

return result;
}

int
main(void)
{
long int p;
int a[4] = {3, 2, 1, 1};
p = horner(a, 4, 1);
printf("polynomial x^3 + x^2 + 2x + 3 = %ld\n", p);
}


实例测试结果:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: