I'm trying to learn common lisp "by example" out of some course based on scheme. Here's my adaptation of the classic Newton algorithm to find square roots:
Code: Select all
(defun fixed-point (f start)
(defvar tolerance 0.00001)
(labels ((close-enough? (u v)
(< (abs (- u v)) tolerance))
(iter (old new)
(if (close-enough? old new)
new
(iter new (funcall f new)))))
(iter start (funcall f start))))
(defvar dx 0.00001)
(defun deriv (f)
#'(lambda (x) (/ (- (funcall f (+ x dx))
(funcall f x))
dx)))
(defun newton (f guess)
(labels ((df () (deriv f)))
(fixed-point
#'(lambda (x) (- x (/ (funcall f x) ((df) x))))
guess)))
(defun mysqrt-newton (x)
(labels ((square (x) (* x x)))
(newton #'(lambda (y) (- x (square y))) 1)))
(mysqrt-newton 2)
Please help.