SICP-练习2.34

【练习2.34】

对于x的某个给定值,求出一个多项式在x的值,也可以形式化为一种累积。假定需要求下面多项式的值:

an*x^n + an-1*x^n-1 + .... + a1*x + a0

采用著名的Horner规则,可以构造出下面的计算:

(...(an*x + an-1)*x + ... + a1)*x + a0

换句话说, 我们可以从an开始,乘以x,再加上an-1,乘以x,如此下去,直到处理完a0.请填充下面的模板,做出一个利用Horner规则求多项式值得过程。假定多项式的系数安排在一个序列里,从a0直到an。

(define (horner-eval x coefficient-sequence)

      (accumulate (lambda  (this-coeff higher-terms) <??>)

                               0

                               coefficient-sequence))

例如,为了计算1 + 3x + 5x^3 + x^5 在x=2的值,你需要求值:

(horner-eval 2 (list 1 3 0 5 0 1))

【分析】

根据 Horner 规则,算式  1+3x+5x3+x5  可以转换成:

1+x(3+x(0+x(5+x(0+x))))

以上算式又可以转换为相应的前序表示:

(+1(x(+3(x(+0(x(+5(x(+0x)))))))))

lambda 部分每次的工作就是取出一个因数,并生成以下表达式(假设当前因数 this- coeff 为 1x 为 2): (+ 1 (*2 (accumulate ...))) ,由此可以给出完整的 horner-eval 函数定义:

【代码】

(define (horner-eval x coefficient-sequence)
    (accumulate (lambda (this-coeff higher-terms)
                    (+ this-coeff (* x higher-terms)))
                0
                coefficient-sequence))
【C语言版】

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int horner(int x, int k, int n, int *arr)
{
	if(k == n)
		return arr[k];
	else
		return (x * horner(x, k+1, n, arr) +arr[k]);
}

int main(void)
{
	int arr[6] = {1, 3, 0, 5, 0, 1};
	int x = 2;
	int result;
	result = horner(x, 0, 5, arr);
	printf("%d\n", result);
	return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值