Skip to content

Instantly share code, notes, and snippets.

@shirok
Created Sep 25, 2012
Embed
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
a0
(let rec ([Qn (+ a0 (/ a1))]
[Qn-1 a0]
[an an])
(if (<= (abs (- Qn x)) e)
Qn
(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