Skip to content

Instantly share code, notes, and snippets.

@tomjack
Created October 28, 2010 03:50
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 tomjack/abd1d5806736a8a60fa1 to your computer and use it in GitHub Desktop.
Save tomjack/abd1d5806736a8a60fa1 to your computer and use it in GitHub Desktop.
(ns scratch.ratio
(:refer-clojure :exclude (rationalize)))
(defn approx-fraction [x denom]
(/ (Math/round (* x denom))
denom))
(defn approximations [x]
(map #(approx-fraction x %)
(next (range))))
(defn rationalize [x max-error]
(first (drop-while #(> (Math/abs (- % x)) max-error)
(approximations x))))
(comment
scratch.ratio> (rationalize (double (/ 1 35)) 0.00000001)
1/35
scratch.ratio> (rationalize (double (/ 1 355)) 0.00000001)
1/355
scratch.ratio> (rationalize (double (/ 1 3553)) 0.00000001)
1/3553
scratch.ratio> (rationalize (double (/ 1 35535)) 0.00000001)
1/35523
scratch.ratio> (rationalize (double (/ 1 35535)) 0.000000001)
1/35534
scratch.ratio> (rationalize (double (/ 1 35535)) 0.0000000001)
1/35535
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment