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))
)

SICP ex1-23 ex1-25_第1张图片

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)
)


SICP ex1-23 ex1-25_第2张图片

(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)
)

SICP ex1-23 ex1-25_第3张图片

由于结果是用分数表示,所以这里可能有些偏差,结果大约0.8多一点约等于pi/4

你可能感兴趣的:(SICP ex1-23 ex1-25)