'Absolute value of a number in Clojure
How can the absolute number of a value be calculated in Clojure?
(abs 1) => 1
(abs -1) => 1
(abs 0) => 0
Solution 1:[1]
As of Clojure 1.11, it is simply (abs -1) in both Clojure and Clojurescript.
In versions before, for double, float, long and int you can use the java.lang.Math method abs (Math/abs -1)
Take care it won't work for decimals, ratio's, bigint(eger)s and other Clojure numeric types. The official clojure contrib math library that tries guarantee working correctly with all of these is clojure.math.numeric-tower
Solution 2:[2]
you could always do
(defn abs [n] (max n (- n)))
Solution 3:[3]
The deprecated clojure.contrib.math provides an abs function.
The source is:
(defn abs "(abs n) is the absolute value of n" [n]
(cond
(not (number? n)) (throw (IllegalArgumentException.
"abs requires a number"))
(neg? n) (- n)
:else n))
As @NielsK points out in the comments, clojure.math.numeric-tower is the successor project.
Solution 4:[4]
abs is now available in the core clojure library since Clojure 1.11 release.
Docs for abs https://clojure.github.io/clojure/branch-master/clojure.core-api.html#clojure.core/abs
Usage: (abs a)
Returns the absolute value of a.
If a is Long/MIN_VALUE => Long/MIN_VALUE
If a is a double and zero => +0.0
If a is a double and ##Inf or ##-Inf => ##Inf
If a is a double and ##NaN => ##NaN
Added in Clojure version 1.11
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Shlomi |
| Solution 3 | |
| Solution 4 | oxalorg |
