Next: Numeric Conversions, Previous: Predicates on Numbers, Up: Numbers [Contents][Index]
To test numbers for numerical equality, you should normally use
=
, not eq
. There can be many distinct floating point
number objects with the same numeric value. If you use eq
to
compare them, then you test whether two values are the same
object. By contrast, =
compares only the numeric values
of the objects.
At present, each integer value has a unique Lisp object in SXEmacs Lisp.
Therefore, eq
is equivalent to =
where integers are
concerned. It is sometimes convenient to use eq
for comparing an
unknown value with an integer, because eq
does not report an
error if the unknown value is not a number—it accepts arguments of any
type. By contrast, =
signals an error if the arguments are not
numbers or markers. However, it is a good idea to use =
if you
can, even for comparing integers, just in case we change the
representation of integers in a future SXEmacs version.
There is another wrinkle: because floating point arithmetic is not exact, it is often a bad idea to check for equality of two floating point values. Usually it is better to test for approximate equality. Here’s a function to do this:
(defconst fuzz-factor 1.0e-6) (defun approx-equal (x y) (or (and (= x 0) (= y 0)) (< (/ (abs (- x y)) (max (abs x) (abs y))) fuzz-factor)))
Common Lisp note: Comparing numbers in Common Lisp always requires
=
because Common Lisp implements multi-word integers, and two distinct integer objects can have the same numeric value. SXEmacs Lisp can have just one integer object for any given value because it has a limited range of integer values.
In addition to numbers, all of the following functions also accept characters and markers as arguments, and treat them as their number equivalents.
This function returns t
if all of its arguments are numerically
equal, nil
otherwise.
(= 5) ⇒ t (= 5 6) ⇒ nil (= 5 5.0) ⇒ t (= 5 5 6) ⇒ nil
This function returns t
if no two arguments are numerically
equal, nil
otherwise.
(/= 5 6) ⇒ t (/= 5 5 6) ⇒ nil (/= 5 6 1) ⇒ t
This function returns t
if the sequence of its arguments is
monotonically increasing, nil
otherwise.
(< 5 6) ⇒ t (< 5 6 6) ⇒ nil (< 5 6 7) ⇒ t
This function returns t
if the sequence of its arguments is
monotonically nondecreasing, nil
otherwise.
(<= 5 6) ⇒ t (<= 5 6 6) ⇒ t (<= 5 6 5) ⇒ nil
This function returns t
if the sequence of its arguments is
monotonically decreasing, nil
otherwise.
This function returns t
if the sequence of its arguments is
monotonically nonincreasing, nil
otherwise.
This function returns the largest of its arguments.
(max 20) ⇒ 20 (max 1 2.5) ⇒ 2.5 (max 1 3 2.5) ⇒ 3
This function returns the smallest of its arguments.
(min -4 1) ⇒ -4
Next: Numeric Conversions, Previous: Predicates on Numbers, Up: Numbers [Contents][Index]