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
;; rem and mod are commonly used to get the remainder. ;; mod means Knuth's mod, Don't confuse it with ANSI C's % ;; operator, which despite being pronounced ;; 'mod' actually implements rem, i.e. -10 % 3 = -1. ;; mod has sign of divisor. ;; Absolute value depends on dividend and divisor having ;; same sign or not. user=> (mod -10 3) 2 user=> (rem -10 3) -1 user=> (mod 10 -3) -2 user=> (mod -10 -3) -1 user=> (mod 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
If no denominators are supplied, returns 1/numerator, else returns numerator divided by all of the...
The difference between rem and mod can be remembered by noting that mod always returns a value between 0 and div.
I am confused by the comment about the definition on lines 13+ of the example - which is not accurate when invoking mod when 'num' is positive and 'div' negative. Applying the definition to
(mod 10 -3)we have
So unless I misunderstood, the definition should be changed to something like:
"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, except when the number is positive and the divisor negative, in which case the result is the amount by which the number exceeds the smallest multiple that is not smaller than the number."
Or, change the implementation to something similar to:
(defn mod-2 [num div] (let [m (rem num div)] (if (or (zero? m) (= (pos? num) (pos? div))) m (if (pos? div) (+ m div) m))))
to fit the current definition.