Skip to content

Instantly share code, notes, and snippets.

@shirok
Created September 25, 2012 03:43
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save shirok/3779868 to your computer and use it in GitHub Desktop.
(define (rationalize3 x e)
(define (refine xn yn an) ; returns reverse continued fraction
(cond [(or (null? xn) (null? yn)) an]
[(= (car xn) (car yn))
(refine (cdr xn) (cdr yn) (cons (car xn) an))]
[else (cons (+ 1 (min (car xn) (car yn))) an)]))
(define (realize rcf) ; reverse continued fraction -> rational
(fold (^[a r] (+ a (/ r))) (car rcf) (cdr rcf)))
(if (< x 0)
(- (rationalize3 (- x) e))
(realize (refine (continued-fraction (exact (- x e)))
(continued-fraction (exact (+ x e)))
'()))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment