Hello friends. I am struggling a little with Clojure and math 😛
I am doing something so simple like the product of 155.39 and 100, that everybody know than is 15539, but Clojure is doing things like:
(* 155.39 100)
=> 15538.999999999998
;; floating point
(* 155.39 100.0)
;; => 15538.999999999998
(format "%f" (* 155.39 100.0))
;; => "15539.000000"
;; decomposed
(+ (* 0.39 100.0) (* 155.0 100.0))
;; => 15539.0
;; bigdec
(* (bigdec 155.39) (bigdec 100.0))
;; => 15539.000M
;; ratio
(* 15539/100 100)
;; => 15539NI fixed basically doing the last one:
(* (rationalize 155.39) 100)
Thanks @tsulej
I did it in python and you right:
Also C and any other language which implements IEEE 754 standard. https://en.wikipedia.org/wiki/IEEE_754
The reason is simple, you can't represent every real number in floating point representation. This is not a Clojure thing but general true about floating point arithmetic and the result of your calculation will be the same in Python, R, JavaScript, etc.
You can try to round it and print it nicely (if the case is the aesthetics), you can reach for bigdec (slow) or ratios (slow).
But my advice is: ignore and live with it.
Anybody has an idea on why on how to solve it?