Hi, I'm doing a little write-up on Java basics and comparing some of them to Clojure (things like mutable shared state, side effects and so on). When I came to "numbers" I was surprised by some of the things I found in Clojure.
(== (double 0.5) (float 0.5)) ;; -> true (== (double 0.2) (float 0.2)) ;; -> false The docs (https://clojure.github.io/clojure/clojure.core-api.html#clojure.core/==) say, that `==` compares the numbers type-independently. But why are the two __representations__ (types?) of the numerical value `0.2` different then? I understand that `(float 0.2)` gets _converted_ to `double` and this conversion is done like this (just the way Java does it -- should be `f2d` in byte code). (double (float 0.2)) ;; -> 0.20000000298023224 So that's not equal to `(double 0.2)`. But why not convert `float` to `double` like this: (defn to-double [f] (Double. (str f))) Here we're not converting the (inexact) `float` approximation of `0.2` to `double` but we use what human readers perceive as the (exact) _numerical value_. This would parallel the way `BigDecimal` literals work in Clojure: 0.3M ;; -> 0.3M (BigDecimal. 0.3) ;; -> 0.299999999999999988897769753748434595763683319091796875M (BigDecimal. (str 0.3)) ;; -> 0.3M When we use numbers in sets and maps, more questions come up: (into #{} [0.5 (float 0.5)]) ;; -> #{0.5} (into #{} [0.2 (float 0.2)]) ;; -> #{0.2 0.2} First it seems that `==` is used to check for equality, but I think it's not the case. (= 0.5 (float 0.5)) ;; -> true Ahh -- seems that `(float 0.5)` gets converted to `double` before comparing via `=`. Getting `#{0.2 0.2}` is bad: we won't be able to read this set literal back in. #{0.2 0.2} ;; -> java.lang.IllegalArgumentException: Duplicate key: 0.2 So my question is: does anyone know about tutorials, docs etc. on clojure.org or elsewhere where I can find advices/best practice/a "clojure specifications" (like the JLS does it for Java) on this topic. Henrik -- You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en --- You received this message because you are subscribed to the Google Groups "Clojure" group. To unsubscribe from this group and stop receiving emails from it, send an email to clojure+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.