Skip to content

Instantly share code, notes, and snippets.

@shirok
Created September 25, 2012 03:39
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/3779852 to your computer and use it in GitHub Desktop.
Save shirok/3779852 to your computer and use it in GitHub Desktop.
(define (rationalize1 x e)
(define (refine lo hi)
(let* ([M (/ (+ (numerator lo) (numerator hi))
(+ (denominator lo) (denominator hi)))]
[delta (abs (- x M))])
(cond
[(<= delta e) M] ;; found
[(< M x) (refine M hi)]
[else (refine lo M)])))
(if (< (abs (- x (round x))) e)
(round->exact x)
(refine (floor->exact x) (ceiling->exact x))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment