Here is the example on the textbook about fixed-point.
(defvar tolerance 0.00000001)1.35
(defun average(x y)
(/ (+ x y) 2))
(defun fixed-point (f first-guess)
(defun close-enough(x y)
(< (abs (- x y)) tolerance))
(defun try(guess)
(let ((next (funcall f guess)))
(if (close-enough guess next)
next
(try next))))
(try first-guess))
(defun f-sqrt(x)
(fixed-point (lambda(y)(average y (/ x y))) 1.0))
(defun golden-ratio()
(fixed-point (lambda (x) (+ 1 (/ 1 x))) 1.0))
1.36
(defun fixed-pointv2 (f first-guess)
(defun close-enough(x y)
(< (abs (- x y)) tolerance))
(defun try(guess)
(let ((next (funcall f guess)))
(if (close-enough guess next)
next
(progn
(format t "The number is ~A~%" next)
(try next)))))
(try first-guess))
(defun log-fixed()
(fixed-pointv2 (lambda(x)(/ (log 1000) (log x))) 2))
1.37
(defun cont-frac(n d k)
(defun cont-frac-aux(i)
(if (= i k)
0
(/ (funcall n i)
(+ (funcall d i)
(cont-frac-aux (+ i 1))))))
(cont-frac-aux 1))
(defun cont-fracv2(n d k)
(defun cont-frac-iter(i result)
(if (= i 0)
result
(cont-frac-iter (- i 1)
(/ (funcall n i)
(+ (funcall d i)
result)))))
(cont-frac-iter k 0))
(defun cont-frac-aux(i)
(if (= i k)
0
(/ (funcall n i)
(+ (funcall d i)
(cont-frac-aux (+ i 1))))))
(cont-frac-aux 1))
(defun cont-fracv2(n d k)
(defun cont-frac-iter(i result)
(if (= i 0)
result
(cont-frac-iter (- i 1)
(/ (funcall n i)
(+ (funcall d i)
result)))))
(cont-frac-iter k 0))
1.38
(defun Euler-e(i)
(cont-fracv2 (lambda(x) 1.0)
(lambda(x)
(if (= 0 (rem (+ x 1) 3))
(* 2 (/ (+ x 1) 3))
1))
i))
No comments:
Post a Comment