2008. 3. 17.

연습문제 1.31

a. product는 sum을 흉내내어 만들면 다음과 같다.

(define (product term a next b)
  (if (> a b)
      1
      (* (term a)
         (product term (next a) next b))))

존 월리스의 공식의 각 항은 (n-1)*(n+1)/n*n 으로 둘 수 있으며 초항은 3부터.. 다음항부터는 2씩 증가하는 형태로 볼 수 있다.
따라서 pi/4를 구하는 함수는

(define (square x) (* x x))

(define (leap-by-2 x) (+ x 2.0))

(define (pi-product-term x)
  (/ (* (- x 1) (+ x 1)) (square x)))

(define (quater-pi n)
  (product pi-product-term 3.0 leap-by-2 n))
처럼 구할 수 있다.
결과는 다음과 같다

> (* 4.0 (quater-pi 10))
3.302393550012597
/> (* 4.0 (quater-pi 100))
3.1573396892175642
/> (* 4.0 (quater-pi 1000))
3.143163842419204
/>

이 함수의 결과가 pi에 수렴함을 알 수 있다.

b. 반복형태로 product를 만들면 다음과 같다.

(define (product-iter term a next b)
  (define (iter a result)
    (if (> a b)
        result
        (iter (next a) (* (term a) result))))
  (iter a 1))

이제 만들어진 product로 pi 함수를 다시 작성하면


(define (quater-pi2 n)
  (product-iter pi-product-term 3.0 leap-by-2 n))

     
이며 이제 이전의 버전과 이번 버전을 비교해보면
> (quater-pi 10)
0.8255983875031493
/> (quater-pi2 10)
0.8255983875031493
/> (quater-pi 100)
0.7893349223043911
/> (quater-pi2 100)
0.7893349223043911


로서 동일한 결과를 얻음을 알 수 있다.

댓글 없음:

댓글 쓰기