牛顿迭代求平方根算法的两个例子

一个scheme写的牛顿迭代求平方根算法

v1

#lang racket
(define (square x) (* x x))

(define (yabs x)
  (cond ((< x 0) (- 0 x))
        (else x)))

(define (good-enough? guess y)
  (< (yabs (- (square guess) y)) 0.00000001))

(define (find-root y guess)
  (if (good-enough? guess y)
      (exact->inexact guess)
      (find-root y (/ (+ (/ y guess) guess) 2))))

(define (sqrt x)
  (find-root x 1))

(sqrt 2)

v2

#lang racket
(define (square x) (* x x))

(define (yabs x)
  (cond ((< x 0) (- x))
        (else x)))

(define (get-dist x y)
  (yabs (- x y)))

(define (good-enough? guess y)
  (< (get-dist (square guess) y) 0.00000001))

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

(define (get-better-guess guess y)
  (get-average (/ y guess) guess))

(define (find-root y guess)
  (if (good-enough? guess y)
       guess
      (find-root y (get-better-guess guess y))))

(define (sqrt x)
  (find-root x 1))

(exact->inexact (sqrt 2))

看出有什么区别吗?