SICP exercise 1.7 1.8

exercise 1.7:這道題有個前提,很大和很小的數都是不溢出,若是溢出就沒意義了。原始的good-enough?是平方後與待求平方根的值相減再比較結果是否小於0.001,這很明顯有問題,若是待求的數的平方根小於0.001,不管怎麼減都是小於0.001的。很大的數沒法精確算到0.001,會一直循環。scala


exercise 1.8:common lisp實現以下code

(defun cuberoot (xx)
  (defun improve (x y)
    (/ (+ (/ x (* y y)) (* 2 y)) 3))
  (defun good-enough? (x y)
    (< (/ (abs (- (* y y y) x)) x) 0.001))
  (let ((prev 0.0))
    (defun good-enough?2 (y)
      (if (< (abs (- y prev)) 0.001)
          t
          (progn (setf prev y)
                 nil))))
  (defun cuberoot-iter (x y)
    (if (good-enough? x y)
        y
        (cuberoot-iter x (improve x y))))
  (cuberoot-iter xx 1.0))
相關文章
相關標籤/搜索