Skip to content

Instantly share code, notes, and snippets.

@shirok
Created September 25, 2012 03:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shirok/3779862 to your computer and use it in GitHub Desktop.
Save shirok/3779862 to your computer and use it in GitHub Desktop.
(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