SICPノートと練習問題-第1章

1815 ワード

練習問題1.3:
(define (sum2Greater a b c)
  (cond ((and (< a b) (< a c)) (+ b c))
        ((and (< b a) (< b c)) (+ a c))
        ((and (< c a) (< c b)) (+ a b))))
(define (sum2Bigger a b c)
  (if (and (< a b) (< a c)) (+ b c)
      (sum2Bigger b c a)))
(sum2Greater 1 2 3)
(sum2Bigger 1 2 3)

第1の方法はcondによって3つの状況を列挙して和を求めることであり,第2の方法はifを利用して判断し,
再帰的に和を求める.
p 14ニュートン法は平方根を求めます
#lang racket
(define (square x) (* x x))

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

(define (abs x)
  (if (< x 0) (- x)
      x))

(define (guess_enough guess x)
  (< (abs (- (square guess) x)) 0.00001))

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

(define (sqrt_iter guess x)
  (if (guess_enough guess x)
      guess
      (sqrt_iter (improve guess x)
            x)))

(define (sqrt x)
  (sqrt_iter 1 x))
呼び出し時に(sqrt 2)のように入力すればよい.
練習問題1.7:
#lang racket

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

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

(define (abs x)
  (if (< x 0) (- x)
      x))

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

(define (guess_enough guess x)
  (< (abs (- guess x)) 0.01))

(define (sqrt_iter guess x)
  (if (guess_enough guess (improve guess x))
      guess
      (sqrt_iter (improve guess x)
            x)))

(define (sqrt x)
  (sqrt_iter 1 x))

練習問題1.8:
#lang racket

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

(define (abs x)
  (if (< x 0) (- x)
      x))

(define (improve guess x)
  (/ (+ (/ x (square guess)) (* 2 guess)) 3))

(define (guess_enough guess x)
  (< (abs (- guess x)) 0.001))

(define (cbrt_iter guess x)
  (if (guess_enough guess (improve guess x))
      guess
      (cbrt_iter (improve guess x)
            x)))

(define (cbrt x)
  (cbrt_iter 1 x))