Reputation: 516
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
Upvotes: 0
Views: 561
Reputation: 14720
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:
(define (sum term a b) (accumulate + 0 term a 1+ b)) (define (product term a b) (accumulate * 1 term a 1+ b)) (define (identity x) x) (define (fact n) (if (= n 0) 1 (product identity 1 n))) (define (exp1 x n) (define (term i) (/ (expon x i) (fact i))) (sum term 1 n))
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:
(define (exp1 x n) (define (term i) (/ (expon x i) (fact i))) (+ 1 (sum term 1 n))) => (exp1 0 3) 1 => (exp1 1 1) 2
Upvotes: 3