ウォンツテック

そでやまのーと

SICPの問題を解こう16

問題 1.29

Simpson's ruleを使ってintegralを求めよという問題

(define (integral f a b n)                                                      
  (define h 0)                                                                  
  (define (i-term count x)                                                      
    (cond ((= count 0) (f a))                                                   
          ((= count n) (f b))                                                   
          ((even? count) (* 2 (f x)))                                           
          (else (* 4 (f x)))))                                                  
  (define (i-next x) (+ x h))                                                   
  (set! h (/ (- b a) n))                                                        
  (* (/ h 3)                                                                    
     (sum i-term 0 a i-next b)))                                                
(define (sum term count a next b)                                               
  (if (> a b)                                                                   
      0                                                                         
      (+ (term count a)                                                         
         (sum term (+ count 1) (next a) next b))))                              
(define (cube x) (* x x x))                                                     
                                                                                
(display (integral cube 0 1 100)) 

termが関数ポインタみたいな役割。
※なぜかgaucheだと動かなかった。。guileでも分割数10くらいで1/4になってしまって細かい数値が計測出来なかった。

問題 1.30

sumのrecursionによるcode

(define (sum term a next b)                                                     
  (define (iter a result)                                                       
    (display result)                                                            
    (newline)                                                                   
    (if (> a b)                                                                 
        result                                                                  
      (iter (next a) (+ result (term a)))))                                     
  (iter a 0))                                                                   
(define (sum-int n)                                                             
  (define (term x) x)                                                           
  (define (next x) (+ x 1))                                                     
  (sum term 1 next 10))                                                         
(display (sum-int 10))