Skip to content

Instantly share code, notes, and snippets.

@tomjack tomjack/ratio.clj Secret
Created Oct 28, 2010

Embed
What would you like to do?
(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
You can’t perform that action at this time.