Elisp: Arithmetic

By Xah Lee. Date: . Last updated: .

Basic Arithmetic Operations

;; addition
(+ 4 5 1) ; 10
;; Subtraction
(- 9 2) ; 7
(- 9 2 3) ; 4
;; Multiplication
(* 2 3) ; 6
(* 2 3 2) ; 12

Power

;; Power; Exponential
(expt 2 3) ; 8

Division, Quotient

;; Division

;; WARNING: 7 divided by 2 returns 3, not 3.5,
;; because the division function return a int when both operands are int.

;; integer part of quotient
(/ 7 2) ; 3

;; WARNING: 2. is still a int. 2.0 is a float.
(/ 7 2.) ; 3

;; int divide by float return float
(/ 7 2.0) ; 3.5

Modular Arithmetic (Remainder)

;; modular arithmetic, remainder
;; args must be integers
(% 7 4)
;; 3

;; HHHH------------------------------

;; modular arithmetic, remainder
;; args can be floating number
(mod 7 4)
;; 3

(mod 7.5 4)
;; 3.5

Truncate, Round, Ceiling, Floor

;; to int
(truncate 3.5)
;; 3

(round 3.5)
;; 4

(ceiling 3.5)
;; 4

(floor 3.5)
;; 3

Test If a Number is Integer or Float

;; test if a number is integer or float

(integerp 2) ; t
(integerp 2.) ; t
(integerp 2.0) ; nil

(floatp 2) ; nil
(floatp 2.) ; nil
(floatp 2.0) ; t

Absolute Value

;; abs
(abs -2)
;; 2

Reference

Emacs Lisp, Numbers