Numbers and Math
Prerequisites: def and immutable values
Arithmetic
(println (+ 7 2) (- 7 2) (* 7 2))
(println (/ 7 2)) ; a ratio, not 3 or 3.5
(println (/ 8 2))
(println (/ 7.0 2))
(println (quot 7 2) (rem 7 2) (mod -7 2) (rem -7 2))
(println (inc 5) (dec 5))
(println (- 10)) ; negation
(println (Math/pow 2 10) (Math/sqrt 16))
9 5 14
7/2
4
3.5
3 1 1 -1
6 4
-10
1024.0 4.0
- Dividing two integers gives an exact ratio (
7/2) when the result isn't whole. Use a decimal (7.0) to get a floating-point result, orquotfor integer division. remkeeps the sign of the dividend;modkeeps the sign of the divisor.incanddecadd or subtract 1.- Java's
Mathclass is available asMath/pow,Math/sqrt, and so on.
Number types
(println (type 42) (type 3.14) (type 1/3))
(println (type 42N) (type 3.14M))
(println (+ 1/3 1/6))
(println (+ 0.1 0.2))
(println (+ 0.1M 0.2M))
(println (double 1/3))
(println (int 3.99) (long 3.99) (Math/round 3.5))
java.lang.Long java.lang.Double clojure.lang.Ratio
clojure.lang.BigInt java.math.BigDecimal
1/2
0.30000000000000004
0.3M
0.3333333333333333
3 3 4
| Literal | Type |
|---|---|
42 |
Long (64-bit integer) |
3.14 |
Double |
1/3 |
Ratio (exact fraction) |
42N |
BigInt (arbitrary size) |
3.14M |
BigDecimal (exact decimal) |
Overflow
(println Long/MAX_VALUE)
(println (+' Long/MAX_VALUE 1)) ; +' promotes to BigInt
(println (*' 99999999999 99999999999))
(println (try (+ Long/MAX_VALUE 1)
(catch ArithmeticException e (.getMessage e))))
9223372036854775807
9223372036854775808N
9999999999800000000001N
long overflow
Clojure's +, -, *, inc, and dec throw on long overflow
instead of silently wrapping around like Java. The primed versions
(+', *', inc', ...) switch to BigInt automatically. (try and
catch are explained in Level 2.)
Comparing numbers
(println (= 1 1) (= 1 1.0) (== 1 1.0))
(println (< 1 2) (>= 3 3) (not= 1 2))
(println (zero? 0) (pos? 5) (neg? -1) (even? 4) (odd? 4))
(println (min 3 1 2) (max 3 1 2) (abs -5))
true false true
true true true
true true true true false
1 3 5
= compares values and number categories, so (= 1 1.0) is false.
Use == to compare numbers of different types numerically.
Practice
A pizza costs 12.40 and is shared by 3 people. Print each share rounded to 2 decimal places, and how many whole pizzas 50 can buy.
Show solution
(def share (/ 12.40 3))
(println (format "%.2f" share))
(println (long (quot 50 12.40)))
4.13
4
format uses Java's format codes; %.2f rounds to two decimals.