-
-
Save tomjack/abd1d5806736a8a60fa1 to your computer and use it in GitHub Desktop.
This file contains 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
(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