Skip to main content

Euler's Continued Fraction in Lisp

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:

cont-frac(n,d,k)={resultif i=0iter(i1,n(i)d(i)+result)otherwise .. where the iter function is defined as follows: iter(i,result)={resultif i=0iter(i1,n(i)d(i)+result)otherwise

Altogether, courtesy of Wikipedia:

a0+a0a1+a0a1a2++a0a1a2an=a01a11+a1a21+a2an11+an1an1+an To calculate the continued fraction using higher-order functions, such that our function accepts another function as input, we can use lambda functions, like so: cont-frac(λ(i)1.0,λ(i)1.0,10)

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

Popular posts from this blog

yt-dlp Archiving, Improved

One annoying thing about YouTube is that, by default, some videos are now served in .webm format or use VP9 encoding. However, I prefer storing media in more widely supported codecs and formats, like .mp4, which has broader support and runs on more devices than .webm files. And sometimes I prefer AVC1 MP4 encoding because it just works out of the box on OSX with QuickTime, as QuickTime doesn't natively support VP9/VPO9. AVC1-encoded MP4s are still the most portable video format. AVC1 ... is by far the most commonly used format for the recording, compression, and distribution of video content, used by 91% of video industry developers as of September 2019. [ 1 ] yt-dlp , the command-line audio/video downloader for YouTube videos, is a great project. But between YouTube supporting various codecs and compatibility issues with various video players, this can make getting what you want out of yt-dlp a bit more challenging: $ yt-dlp -f "bestvideo[ext=mp4]+bestaudio[ext=m4a]/best...