mathematics

Luis Cerritos 2024-07-23T23:46:52.246699Z

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

genmeblog 2024-07-24T08:37:06.318029Z

;; 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)
;; => 15539N

Luis Cerritos 2024-07-24T15:24:10.351039Z

I fixed basically doing the last one: (* (rationalize 155.39) 100)

👍 1
Luis Cerritos 2024-07-24T17:42:31.584889Z

Thanks @tsulej

Luis Cerritos 2024-07-24T17:44:43.415029Z

I did it in python and you right:

genmeblog 2024-07-24T18:44:45.805069Z

Also C and any other language which implements IEEE 754 standard. https://en.wikipedia.org/wiki/IEEE_754

1
genmeblog 2024-07-24T18:45:49.302919Z

https://www.programiz.com/online-compiler/6AByQfccGs8Kk

1
genmeblog 2024-07-24T05:40:27.705679Z

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.

genmeblog 2024-07-24T05:42:43.960609Z

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).

genmeblog 2024-07-24T05:43:01.421389Z

But my advice is: ignore and live with it.

Luis Cerritos 2024-07-23T23:48:14.142269Z

Anybody has an idea on why on how to solve it?