SICP 필기와 연습문제 - 제1장

1845 단어
연습 문제 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)

첫 번째 방법은cond를 통해 세 가지 상황을 열거하고 화합을 구하는 것이고, 두 번째 방법은if를 이용하여 판단하고 통과하는 것이다.
차례로 화합을 구하다.
p14 뉴턴 법구 제곱근
4
#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))
호출할 때 (sqrt2)와 같이 입력하면 됩니다.
연습문제 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))

좋은 웹페이지 즐겨찾기