使用accumulate 计算总和
程序accumulate的定义如下:
(define (accumulate combiner null-value term a next b)
(if (> a b) null-value
(combiner (term a)
(accumulate combiner null-value term (next a) next b))))
问题1:x^n ;解决方案:递归无累加
(define (expon x n)
(if (> n 0) (* x
(expon x (- n 1))
)
1))
问题2:x + x^2 + x^4 + x^6 + ...+ ,计算给定的n 序列的前n 个元素。
问题3:1+x/1! + x^2/2! + ... + x^n/n!;计算给定 x,n 的总和 可能不正确的解决方案:
(define (exp1 x n)
(define (term i)
(define (term1 k) (/ x k))
(accumulate * 1 term1 1 1+ i))
(accumulate + 0 term 1 1+ n))
为什么前面的代码不正确:
(exp1 0 3) ->; 0 ;应该是1 (exp1 1 1)-> 1 ;应该是2
procedure accumulate is defined like this:
(define (accumulate combiner null-value term a next b)
(if (> a b) null-value
(combiner (term a)
(accumulate combiner null-value term (next a) next b))))
problem 1: x^n
;Solution: recursive without accumulate
(define (expon x n)
(if (> n 0) (* x
(expon x (- n 1))
)
1))
problem 2: x + x^2 + x^4 + x^6 + ...+ ,calculate for given n the first n elements of the sequence.
problem 3: 1 + x/1! + x^2/2! + ... + x^n/n!; calculate the sum for given x,n
possibly incorrect solution:
(define (exp1 x n)
(define (term i)
(define (term1 k) (/ x k))
(accumulate * 1 term1 1 1+ i))
(accumulate + 0 term 1 1+ n))
why the previous code is incorrect:
(exp1 0 3) -> 0 ; It should be 1
(exp1 1 1) -> 1 ; It should be 2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,我想说你的 EXP1 过程在根据累加定义时的运行水平太低,并且为了洞察力,用总和和阶乘重写它:
现在回答你的问题:你的原因是得到
(EXP1 0 3)
→ 0 只不过是您忘记在系列开头添加 1,而只是计算 x/1! + x^2/2! + ... + x^n/n!更改 EXP1 以包含缺失的术语可以按预期工作:
First off, I would say that your EXP1 procedure is operating at too low a level in being defined in terms of ACCUMULATE, and for the sake of perspicacity rewrite it instead in terms of sums and factorials:
Now to your question: the reason you are getting
(EXP1 0 3)
→ 0 is no more than that you forgot to add the 1 at the start of the series, and are just computing x/1! + x^2/2! + ... + x^n/n!Changing EXP1 to include the missing term works as expected: