Created
September 25, 2012 03:42
-
-
Save shirok/3779862 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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