SICP-answers icon indicating copy to clipboard operation
SICP-answers copied to clipboard

1.45补充

Open jiakai0419 opened this issue 8 years ago • 0 comments

这里提供一个自适应的求n次方根的函数(所谓自适应是指,不需要提前知道要进行几次平均阻尼)

(define (average-damp f)
  (lambda (x) (/ (+ x (f x)) 2)))

(define (adapt-fixed-point f first-guess)
  (define (close-enough? guess next)
    (let ((tolerance 0.00001)) (< (abs (- guess next)) tolerance)))
  (define (try guess times damped-f damped-times)
    (let ((times-thr 100000)
          (next (damped-f guess)))
      (cond ((> times times-thr) (try first-guess 1 (average-damp damped-f) (+ damped-times 1)))
            ((close-enough? guess next) (display "damped-times=") (display damped-times) (newline) next)
            (else (try next (+ times 1) damped-f damped-times)))))
  (try first-guess 1 (average-damp f) 1))

(define (nrt x n)
  (adapt-fixed-point (lambda (y) (/ x (expt y (- n 1)))) 1.0)

link:https://github.com/jiakai0419/SICP/blob/master/chapter-1/exercise-1.45.scm

jiakai0419 avatar Oct 06 '16 09:10 jiakai0419