SICP 1.3.3 二分法作为方程的根

这次所犯的错误是abs函数括号闭合错了,不懂得怎么调Bug,有点烦。

(define (search f neg-point pos-point)
  (let ((mid-point (average neg-point pos-point)))
    (if (close-enough? neg-point pos-point)
      mid-point
      (let ((test-value (f mid-point)))
        (cond ((positive? test-value) (search f neg-point mid-point)) ((negative? test-value) (search f mid-point pos-point)) (else mid-point))))))

(define (close-enough? x y)
  (< (abs (- x y)) 0.001))

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

(define (half-interval-method f a b)
  (let ((a-value (f a))
        (b-value (f b)))
    (cond ((and (negative? a-value) (positive? b-value)) 
           (search f a b))
          ((and (negative? b-value) (positive? a-value))
           (search f b a))
          (else 
            (error "Values are not of opposite sign" a b)))))

(newline)
(display (half-interval-method sin 2.0 4.0))

(newline)
(display (half-interval-method (lambda (x) (- (* x x x) (* 2 x) 3))
                               1.0
                               2.0))

(newline)
(display (half-interval-method sin 2.0 3.0))

你可能感兴趣的:(SICP)