SICP exercise 1.37: My iterative solution got the right answer but got wrong in 1.38
题
My iterative solution to SICP 1.37 is
(define (con-frac n d k)
(define (iter i result)
(if (= 1 i)
result
(iter (- i 1) (/ (n i) (+ (d i) result)))))
(iter k (/ (n k) (d k))))
(con-frac (lambda (i) 1.0) (lambda (i) 1.0) 11)
(define (euler-d i)
(if (= 2 (remainder i 3))
(* (/ 2 3) (+ i 1))
1))
(define (e)
(+ 2 (con-frac (lambda (i) 1.0) euler-d 9)))
(e)
It returns:
Welcome to DrRacket, version 5.2.1 [3m]. Language: SICP (PLaneT 1.17); memory limit: 128 MB. 0.6180555555555556 2.39221140472879
It should be return:
Welcome to DrRacket, version 5.2.1 [3m]. Language: SICP (PLaneT 1.17); memory limit: 128 MB. 0.6180555555555556 2.718283582089552
I don't know what's wrong with my solution.
解决方案
You are off by one in the iter
.
In
(define (iter i result)
(if (= 1 i)
result
(iter (- i 1) (/ (n i) (+ (d i) result)))))
change (= 1 i)
to (= 0 i
.
(define (iter i result)
(if (= 0 i)
result
(iter (- i 1) (/ (n i) (+ (d i) result)))))
The test using phi
doesn't catch this since all numerators and denominators are equal.
其他提示
As has been pointed in @soegaard's answer, there's a simple off-by-one error in your code. Just replace this line:
(if (= 1 i)
With this one - it's a bit more idiomatic than asking if (= 0 i)
:
(if (zero? i)
... And that's all!
不隶属于 StackOverflow