I am trying to learn Clojure and tried defining this simple function:
user=> (defn triple [arg] (* 3 arg))
#'user/triple
user=> (triple 1)
3
user=> (triple 1.01)
3.0300000000000002
Can anyone explain why there is a 2 at the end of the result here?
Due to the representation of floating point numbers on computers, operations on these numbers are not precise. It applies both to JVM and physical machines. See Floating point inaccuracy examples for a longer discussion. There's also a comprehensive article What Every Computer Scientist Should Know About Floating-Point Arithmetic linked in the answers to that question.
It's due to floating point inaccuracy, which affects all languages with floating point representations. There are some values that cannot be accurately represented with floating point numbers.
Fortunately, Clojure also has support for high precision numerics, so you can do:
(defn triple [arg] (* 3 arg))
(triple 1.01M)
=> 3.03M
Note the use of "M" at the end of numeric constants to indicate that you want to use high precision numbers. In this case java.math.BigDecimal numbers are used by Clojure under the hood.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With