SICP ex1-23 ex1-25

今天的題目要求編程

1-23要求運用Simpson'sRule來求積分

公式=h/3[y0+4y1+2y2+4y3+2y4...+2y(n-2)+4y(n-1)+yn]

h=(b-a)/n

yk=f(a+kh)

(define (integral a b)
	(define n 100)
	(define dx (/ (- b a) n))
	(define (reminder x y) (if (< x y) x (reminder (- x y) y)))
	(define (y bottom count) (f (+ bottom (* count h))))
	(define h (/ (- b a) n))
	(define (iseven? n) (= (reminder n 2) 0))
	(define (exy bottom count top) 
		(cond ((or (= count 0) (= count n)) (y bottom count))
			(else
				(if (iseven? count) (* 2 (y bottom count) ) (* 4 (y bottom count) )  )
			)
		)
	)
	(define (sum function bottom count top dx)
		(if (> count n) 0
			(+ (function bottom count top) (sum function bottom (+ count 1) top dx)))
	)
	(* (/ h 3) (sum exy a 0 b dx))
)

1-24由於基本同於1-25中的iter部分,所以直接給出1-25答案

要求運用heigher-order 創建product模板(遞歸,迭代)然後給出階乘和求pi的程序

(define (product term a next b)
	(if (= a b) 1
		(* (product term (next a) next b) (term a))
	)
)
(define (f n) n)
(define (plus n) (+ n 1))
(define (factorial n) 
	(product f 1 plus n )
)


(define (pi-f n) (/ (* (* 2 n) (+ (* 2 n) 2) ) (* (+ 1 (* 2 n)) (+ 1 (* 2 n)))))
(define (get-pi n)
	(product pi-f 1 plus n)
)


(define (iproduct term a next b)
	(define (iter a result)
		(if (= a b) result
			(iter (next a) (* result (term a))))
	)
	(iter a 1)
)
(define (f n) n)
(define (plus n) (+ n 1))
(define (ifactorial n) 
	(iproduct f 1 plus n )
)


(define (pi-f n) (/ (* (* 2 n) (+ (* 2 n) 2) ) (* (+ 1 (* 2 n)) (+ 1 (* 2 n)))))
(define (iget-pi n)
	(iproduct pi-f 1 plus n)
)

由於結果是用分數表示,所以這裏可能有些偏差,結果大約0.8多一點約等於pi/4

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章