Skip to content

Instantly share code, notes, and snippets.

Created Sep 25, 2012
What would you like to do?
(define (rationalize2 x e)
(define (next an Qn-1 Qn-2)
(/ (+ (* an (numerator Qn-1)) (numerator Qn-2))
(+ (* an (denominator Qn-1)) (denominator Qn-2))))
(if (< x 0)
(- (rationalize2 (- x) e))
(match (continued-fraction (exact x))
[(a0) a0] ;integer
[(a0 a1 . an)
(if (<= (- x a0) e) ;integer is close enough
(let rec ([Qn (+ a0 (/ a1))]
[Qn-1 a0]
[an an])
(if (<= (abs (- Qn x)) e)
(rec (next (car an) Qn Qn-1) Qn (cdr an)))))])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment