SICP笔记与习题-第一章

习题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 牛顿法求平方根

#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))


你可能感兴趣的:(SICP笔记与习题-第一章)