Skip to content

Instantly share code, notes, and snippets.

@mthomure
Created June 14, 2016 16:38
Show Gist options
  • Save mthomure/1402efbd2461445c51ad0ebbaa26454c to your computer and use it in GitHub Desktop.
Save mthomure/1402efbd2461445c51ad0ebbaa26454c to your computer and use it in GitHub Desktop.
Approximate comparison of floating-point numbers for clojure.data/diff.
(ns fuzzy-diff
"Approximate comparison of floating-point numbers for clojure.data/diff."
(:require [clojure.data :refer [Diff]]))
(def ^:dynamic *fuzz* 0)
(defn fuzzy-float-diff [a b]
(if (< (Math/abs (- a b)) *fuzz*) [nil nil a] [a b nil]))
(extend java.lang.Double
Diff
{:diff-similar fuzzy-float-diff})
(extend java.lang.Float
Diff
{:diff-similar fuzzy-float-diff})
;; examples:
;;
;; (require '[fuzzy-diff :refer [*fuzz*]])
;;
;; user> (diff {:a 1.2} {:a 1.200000001})
;; ({:a 1.2} {:a 1.200000001} nil)
;;
;; user> (binding [*fuzz* 1e-1]
;; (diff {:a 1.2} {:a 1.200000001}))
;; (nil nil {:a 1.2})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment