sicp3.5.2、3.5.3節部分習題嚐試解答
本節主要講述無窮流。3.53,顯然
(define s (cons-stream 1 (add-stream s s)))
定義是2的n次方組成的無窮數列,2,4,8,16,32...3.54,定義階乘組成的無窮序列:
(define (mul-streams s1 s2)
(stream-map * s1 s2))
(define factorials (cons-stream 1 (mul-streams factorials (stream-cdr integers))))
(stream-map * s1 s2))
(define factorials (cons-stream 1 (mul-streams factorials (stream-cdr integers))))
3.55解答,比較有趣,也是不難的題目,列出來找出規律就成了,就是將(stream-car s)加到生成的序列中的每個元素上,通過stream-map,最後的結果就是每個元素都是前n個元素累積的結果,我的解答:
(define (partial-sums s)
(cons-stream (stream-car s) (stream-map (lambda(x) (+ x (stream-car s))) (partial-sums (stream-cdr s)))))
(cons-stream (stream-car s) (stream-map (lambda(x) (+ x (stream-car s))) (partial-sums (stream-cdr s)))))
3.56,有了merge就好辦了,根據條件合並起3種情況來就好:
(define S (cons-stream 1 (merge (scale-stream s 2) (merge (scale-stream s 3) (scale-stream s 5)))))
3.57,略過
3.58,觀察到,num每次都與radix相乘並且radix保持不變,那麼radix可以認為是一個基數,den也保持不變作為除數,那麼這個序列就是以radix為基數對den求整數商的序列,不明白num為什麼每次要變換成餘數?這個序列有啥特別的用途呢?未解。
(expand 1 7 10)3.59解答:
=> 1 4 2 8 5 7 1 4 2 8
(expand 3 8 10)
=> 3 7 5 0 0 0 0 0 0 0
a)隻要將序列通過前麵定義的mul-streams與整數的倒數序列相乘:
(define (integrate-series s)
(mul-streams (stream-map (lambda(x) (/ 1 x)) integers) s))
(mul-streams (stream-map (lambda(x) (/ 1 x)) integers) s))
b)照著定義來了,cons的級數注意使用scale-stream乘以-1:
(define sine-series
(cons-stream 0 (integrate-series cosine-series)))
(define cosine-series
(cons-stream 1
(scale-stream
(integrate-series sine-series)
-1)))
(cons-stream 0 (integrate-series cosine-series)))
(define cosine-series
(cons-stream 1
(scale-stream
(integrate-series sine-series)
-1)))
3.64解答:
(define (stream-limit s tolerance)
(define (stream-limit-iter stream current)
(cond ((or (stream-null? stream) (null? (stream-car stream))) #f)
(else
(let ((next (stream-car stream)))
(if (< (abs (- next current)) tolerance)
next
(stream-limit-iter (stream-cdr stream) next))))))
(stream-limit-iter (stream-cdr s) (stream-car s)))
(define (stream-limit-iter stream current)
(cond ((or (stream-null? stream) (null? (stream-car stream))) #f)
(else
(let ((next (stream-car stream)))
(if (< (abs (- next current)) tolerance)
next
(stream-limit-iter (stream-cdr stream) next))))))
(stream-limit-iter (stream-cdr s) (stream-car s)))
習題3.65:
(define (ln-summands n)
(cons-stream (/ 1.0 n)
(stream-map - (ln-summands (+ n 1)))))
(define ln-stream (partial-sums (ln-summands 1)))
(define ln-stream2 (euler-transform ln-stream))
(define ln-stream3 (accelerated-sequence euler-transform ln-stream))
(cons-stream (/ 1.0 n)
(stream-map - (ln-summands (+ n 1)))))
(define ln-stream (partial-sums (ln-summands 1)))
(define ln-stream2 (euler-transform ln-stream))
(define ln-stream3 (accelerated-sequence euler-transform ln-stream))
經過歐拉變換加速過的級數收斂的很快,測測就知道
文章轉自莊周夢蝶 ,原文發布時間2008-05-13
最後更新:2017-05-17 18:01:47