(wat-aro)

無職から有職者にランクアップしました

SICP 問題 5.03

1章でやったNewton法で求めるsqrt手続き.
これをデータパス図で描き,レジスタ計算機言語で定義する.

(define (sqrt n)
  (sqrt-iter 1.0 x))

(define (sqrt-iter guess x)
  (if (good-enough? guess x)
      guess
      (sqrt-iter (improve guess x)
                 x)))

(define (improve guess x)
  (average guess (/ x guess)))

(define (average x y)
  (/ (+ x y) 2))

(define (good-enough? guess x)
  (< (abs (- (square guess) x)) 0.001))

 
good-enough?, improveを使った場合

定義

;; good-enough?, improveを使った場合
(controller
 sqrt
   (assign x (op read))
   (assign guess (const 1.0))
 test-b
   (test (op good-enough?) (reg guess) (reg x))
   (branch (label sqrt-done))
   (assign t (op improve) (reg guess) (reg x))
   (assign guess (reg t))
   (goto (label test-b))
 sqrt-done
   (perform (op peinr) (reg guess)))

 
good-enough?, improveを使わなかった場合  
定義

;; good-enough?, improveを使わずに
(controller
  sqrt
    (assign x (op read))
    (assign guess (const 1.0))
  good-enough?
    (assign p (op square) (reg guess))
    (assign diff (op -) (reg p) (reg x))
    (assign g (op abs) (reg diff))
    (test (op <) (reg g) (const 0.001))
    (branch (label sqrt-done))
  improve
    (assign d (op /) (reg x) (reg guess))
    (assign t (op average) (reg d) (reg guess))
    (assign guess (reg t))
  sqrt-done
    (perform (op print) (reg guess)))