Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 38 ยท Syntax and Evaluation

Numbers and Arithmetic

Explore Common Lisp's numeric tower: unbounded integers, exact ratios, single and double floats, complex numbers, rounding functions, and numeric predicates.

Common Lisp has one of the richest number systems of any language. Integers never overflow, division can give exact fractions, and complex numbers are built in. This lesson tours the numeric tower, shows the arithmetic and rounding functions, and warns about the places where floats and exact numbers mix.

Integers: no overflow

Integers in Common Lisp are as large as your memory allows. Small ones (fixnums) are fast; large ones (bignums) are handled automatically.

LISP
(expt 2 100)
;; => 1267650600228229401496703205376

(* 99999999999 99999999999)
;; => 9999999999800000000001

(defun fact (n) (if (< n 2) 1 (* n (fact (- n 1)))))
(fact 25)
;; => 15511210043330985984000000

There is no Integer.MAX_VALUE to hit. Write numbers in other bases with #b1010 (10), #o17 (15) and #xFF (255).

Ratios: exact fractions

Dividing integers gives an exact ratio whenever the result is not a whole number.

LISP
(/ 1 3)          ; => 1/3
(/ 6 3)          ; => 2     (whole numbers collapse)
(+ 1/3 2/3)      ; => 1
(* 2/3 3/4)      ; => 1/2
(numerator 6/4)  ; => 3
(denominator 6/4); => 2

Ratios are always reduced to lowest terms and are exact: (+ 1/10 2/10) is exactly 3/10, with none of the 0.30000000000000004 surprises of binary floats. Use them for money-like math and exact algorithms.

Floats

Floating-point numbers have a type name that shows their precision: single-float and double-float.

LISP
1.5        ; single-float by default (read as 1.5)
1.5d0      ; double-float
1.5e3      ; single-float, 1500.0
1.5d3      ; double-float, 1500.0d0
(float 1/3)       ; => 0.33333334     (single)
(float 1/3 1d0)   ; => 0.3333333333333333d0
pi                ; => 3.141592653589793d0   (SBCL: a double)

The suffix d0 marks a double-float. If you print doubles, SBCL shows d0. In many programs you want doubles everywhere: write 1.0d0 or set *read-default-float-format* to 'double-float.

Contagion

When you mix types, the result is the "widest": integer < ratio < single-float < double-float < complex.

LISP
(+ 1 1/2)      ; => 3/2
(+ 1 0.5)      ; => 1.5
(+ 1/2 0.5)    ; => 1.0
(+ 1.5 1.5d0)  ; => 3.0d0

Once a float enters a calculation, exactness is gone.

Complex numbers

LISP
#C(1 2)              ; the complex number 1 + 2i
(* #C(0 1) #C(0 1))  ; => -1        i times i
(sqrt -4)            ; => #C(0.0 2.0)
(realpart #C(3 4))   ; => 3
(abs #C(3 4))        ; => 5.0

You rarely need them, but they just work, including in sqrt, expt and trig functions.

Arithmetic functions

LISP
(+ 1 2 3)       ; => 6    any number of arguments
(- 10)          ; => -10  one argument negates
(- 10 3 2)      ; => 5
(* 2 3 4)       ; => 24
(/ 12 2 3)      ; => 2
(/ 2)           ; => 1/2  one argument is the reciprocal
(1+ 5)          ; => 6
(1- 5)          ; => 4
(incf x)        ; macro: x := x + 1
(decf x 3)      ; macro: x := x - 3
(expt 2 10)     ; => 1024
(sqrt 16)       ; => 4.0
(abs -7)        ; => 7
(min 3 1 2)     ; => 1
(max 3 1 2)     ; => 3
(gcd 12 18)     ; => 6
(lcm 4 6)       ; => 12

Notice (sqrt 16) returns the float 4.0, and (isqrt 17) returns the integer 4 (the integer square root).

Rounding and division with multiple values

Four functions divide and round: floor, ceiling, truncate, round. Each returns two values: the quotient and the remainder.

LISP
(floor 7 2)      ; => 3, 1        toward negative infinity
(ceiling 7 2)    ; => 4, -1       toward positive infinity
(truncate -7 2)  ; => -3, -1      toward zero
(floor -7 2)     ; => -4, 1
(round 7 2)      ; => 4, -1       to nearest; ties go to the even number
(round 5 2)      ; => 2, 1
(round 2.5)      ; => 2, 0.5
(round 3.5)      ; => 4, -0.5

The REPL shows both values. In code, you usually use just the first, or capture both with multiple-value-bind (covered in Functions and Parameters).

mod and rem are the remainders matching floor and truncate:

LISP
(mod 7 3)     ; => 1
(mod -7 3)    ; => 2     sign follows the divisor
(rem -7 3)    ; => -1    sign follows the dividend

If you convert JavaScript or C habits: (mod -7 3) is 2, not -1.

Predicates and comparison

LISP
(= 3 3.0)         ; => T     numeric equality ignores type
(eql 3 3.0)       ; => NIL   different types
(< 1 2 3)         ; => T     chains: 1 < 2 < 3
(zerop 0)         ; => T
(plusp 5)         ; => T
(evenp 4)         ; => T
(oddp 4)          ; => NIL
(integerp 3)      ; => T
(rationalp 1/2)   ; => T
(floatp 1.0)      ; => T
(numberp "3")     ; => NIL

Use = for comparing numbers and eql/equal for general values (see Conditionals and Equality).

Parsing and random numbers

LISP
(parse-integer "42")        ; => 42, 2
(parse-integer "  42  ")    ; => 42, 6    (surrounding spaces are fine)
(random 10)                 ; => an integer 0..9
(random 1.0)                ; => a float between 0.0 and 1.0
(setf *random-state* (make-random-state t)) ; seed freshly (SBCL seeds the same each run otherwise)

SBCL starts each process with the same random state, so a fresh script prints the same "random" numbers every time. Seed with (make-random-state t) when you want variety.

A stand-in for ratios and rounding

Real Common Lisp does exact ratios and bignums natively. JavaScript can imitate both with BigInt and a small class. This is a stand-in that shows how exact fractions and floor/truncate behave; it is not Lisp code.

JS Stand-in: ratios, bignums and rounding

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does (/ 6 4) return?

    Integer division returns an exact reduced ratio unless the result is a whole number.
  2. 2. What is (floor -7 2)?

    floor rounds toward negative infinity: quotient -4, remainder 1 (since -4*2 + 1 = -7).
  3. 3. What is the difference between = and eql for 3 and 3.0?

    = compares numeric value; eql also requires the same type.
  4. 4. How large can an integer get?

    Common Lisp integers switch to bignums automatically.
  5. 5. What type does (+ 1/2 0.5) give?

    Float contagion: mixing a ratio with a float yields a float (1.0).

Summary

  • Integers are unbounded; division of integers gives exact ratios.
  • Floats come as single and double (1.5d0); mixing with floats makes results float.
  • floor, ceiling, truncate, round return quotient and remainder; mod and rem differ for negatives.
  • = compares values across types; eql also compares types.
  • SBCL's random starts from the same state each run unless you seed it.

Next: Symbols, Variables and Scope