In 1748, Leonhard Euler published a formula describing an identity that connected and generalized an infinite series and infinite continued fraction. The continued fraction function can be defined as follows. Let n represent a numerator, d a denominator, and k a number of iterations. Upon each loop, our function will decrement its count and recurse on itself until reaching its iteration limit:
Altogether, courtesy of Wikipedia:
Putting it together, we can write this recursive function concisely in Lisp, with k defining the iterations or approximation accurary. We'll set it to 10.
(defun cont-frac (n d k)
(labels ((iter (i result)
(if (= i 0)
result
(iter (- i 1) (/ (funcall n i) (+ (funcall d i) result))))))
(iter k 0)))
(format t "~a" (cont-frac (lambda (i) 1.0) (lambda (i) 1.0) 10))
Upon execution, the Lisp interpreter iterates ten times, then prints our result, 0.6179775.
Comments
Post a Comment