mod

added
1.0

ns
clojure.core

type
function

(mod num div)

Modulus of num and div. Truncates toward negative infinity.

                user=> (mod 10 5)
0

user=> (mod 10 6)
4

user=> (mod 10 10)
0

user=> (mod 10 -1)
0

;; The mod function is defined as the amount by which a number exceeds the
;; largest integer multiple of the divisor that is not greater than that number.
;; The largest integer multiple of 5 not greater than -2 is 5 * -1 = -5.
;; The amount by which -2 exceeds -5 is 3. 
;;
user=> (mod -2  5) 
3
            
                ;; Per rem docs: https://clojuredocs.org/clojure.core/rem#example-542692c8c026201cdc3269e1

;; rem and mod are commonly used to get the remainder.
;; mod means Gaussian mod, so the result is always
;; non-negative.  Don't confuse it with ANSI C's %
;; operator, which despite being pronounced
;; 'mod' actually implements rem, i.e. -10 % 3 = -1.

user=> (mod -10 3)
2

user=> (rem -10 3)
-1
            
                ;; It works for float / double numbers, too, where it is defined as
;; (- n (* (Math/floor (/ n d)) d))

user=> (mod 1.5 1)
;;=> 0.5

user=> (mod 475.095 7)
;;=> 6.095000000000027

user=> (mod 1024.8402 5.12)
;;=> 0.8402000000000953

user=> (mod -1024.8402 5.12)
;;=> 4.279799999999905

user=> (let [n 1024.8402
             d 5.12
             q (Math/floor (/ n d))
             r (mod n d)]
         (->> (* q d) (+ r) (- n)))
;;=> 0.0