Drew Noakes
Drew Noakes

Reputation: 310792

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

Upvotes: 48

Views: 26551

Answers (4)

NielsK
NielsK

Reputation: 6956

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

Upvotes: 58

oxalorg
oxalorg

Reputation: 2798

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

Upvotes: 3

Shlomi
Shlomi

Reputation: 4748

you could always do

(defn abs [n] (max n (- n)))

Upvotes: 39

Drew Noakes
Drew Noakes

Reputation: 310792

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.

Upvotes: 12

Related Questions