abs
abs Function
Syntax:
abs number → absolute-value
Arguments and Values:
number—a number .
absolute-value—a non-negative real.
Description:
abs returns the absolute value of number.
If number is a real, the result is of the same type as number.
If number is a complex , the result is a positive real with the same magnitude as number. The result can be a float even if number’s components are rationals and an exact rational result would have been possible. Thus the result of (abs #c(3 4)) can be either 5 or 5.0, depending on the implementation.
Examples:
(abs 0) → 0
(abs 12/13) → 12/13
(abs -1.09) → 1.09
(abs #c(5.0 -5.0)) → 7.071068
(abs #c(5 5)) → 7.071068
(abs #c(3/5 4/5)) → 1 or approximately 1.0
(eql (abs -0.0) -0.0) → true
See Also:
Section 12.1.3.3 (Rule of Float Substitutability)
Notes:
If number is a complex , the result is equivalent to the following:
(sqrt (+ (expt (realpart number) 2) (expt (imagpart number) 2)))
An implementation should not use this formula directly for all complexes but should handle very large or very small components specially to avoid intermediate overflow or underflow.
Expanded Reference: abs
Absolute value of integers
abs returns the absolute value of a number. For real numbers, the result has the same type as the input.
(abs 0)
=> 0
(abs 42)
=> 42
(abs -42)
=> 42
Absolute value of rationals and floats
The result preserves the type of the argument.
(abs -12/13)
=> 12/13
(abs -1.09)
=> 1.09
(abs -3.5d0)
=> 3.5d0
Absolute value of complex numbers
For complex numbers, abs returns the magnitude (modulus), which is always a non-negative real.
(abs #c(3 4))
=> 5.0
(abs #c(5.0 -5.0))
=> 7.071068
(abs #c(0 1))
=> 1.0
Negative zero
The absolute value of negative zero is negative zero in IEEE floating-point arithmetic.
(eql (abs -0.0) -0.0)
=> NIL
(abs 0.0)
=> 0.0
Practical use: computing distance
abs is useful when computing the distance between two numbers on the number line.
(defun distance (a b)
(abs (- a b)))
(distance 3 7)
=> 4
(distance -5 5)
=> 10
(distance 2.5 2.5)
=> 0.0