sicp 1.40

 

Exercise 1.40.  Define a procedure cubic that can be used together with the newtons-method procedure in expressions of the form

 

 

(newtons-method (cubic a b c) 1)

 

to approximate zeros of the cubic x3 + ax2 + bx + c.

 


cubic函数及计算示例如下:

(define (cubic a b c)
  (lambda (x)
    (+ (* x x x)
       (* a x x)
       (* b x)
       c)))

(define (deriv g)
  (lambda (x)
    (/ (- (g (+ x dx)) (g x))
       dx)))

(define dx 0.00001)

(define (newton-transform g)
  (lambda (x)
    (- x (/ (g x) ((deriv g) x)))))

(define (newtons-method g guess)
  (fixed-point (newton-transform g) guess))

(define (fixed-point f first-guess)
  (let ((eps 0.000001))
    (define (close-enough? g1 g2)
      (< (abs (- g1 g2)) eps))
    (define (try x)
      (if (close-enough? x (f x))
          x
          (try (f x))))
    (try first-guess)))

(newtons-method (cubic 3 3 1) 1)
 

-0.9999937402110022

你可能感兴趣的:(SICP)