On Fri, Aug 20, 2010 at 14:26, bufo <ferna...@gmail.com> wrote: > I am currently learning clojure by reading The Joy of Clojure and I > have 2 questions on float opertions: > > - why does (+ 4.2 8.4) return 12.600000000000001 and (+ 1.5 2.6) 4.1? > Since 4.2, 8.4 and (+ 4.2 8.4) are java Doubles why does it not behave > as expected? What does clojure do in the background? > > - I also have a question regarding float precison in big operations, > consider the following code: > (defn ope [a b] (+ a (* b (Math/sqrt b)))) > > (reduce ope (range 1000000)) > 3.999995000001039E14 > > vs > > (loop [i 1 x 0] > (if (> i 1000000) > x > (recur (inc i) (ope x i)))) > 4.000005000001039E14 (which is what we get if we do a for loop in > java) >
What you are seeing here is floating point working as designed. "What Every Computer Scientist Should Know About Floating-Point Arithmetic" http://docs.sun.com/source/806-3568/ncg_goldberg.html If you need exact answers, use rational numbers. BigDecimals and BigIntegers may also be of interest depending on your application. // ben -- 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