elisp: Float Basics
3.2 Floating-Point Basics
=========================
Floating-point numbers are useful for representing numbers that are not
integral. The range of floating-point numbers is the same as the range
of the C data type ‘double’ on the machine you are using. On all
computers currently supported by Emacs, this is double-precision IEEE
floating point.
The read syntax for floating-point numbers requires either a decimal
point, an exponent, or both. Optional signs (‘+’ or ‘-’) precede the
number and its exponent. For example, ‘1500.0’, ‘+15e2’, ‘15.0e+2’,
‘+1500000e-3’, and ‘.15e4’ are five ways of writing a floating-point
number whose value is 1500. They are all equivalent. Like Common Lisp,
Emacs Lisp requires at least one digit after any decimal point in a
floating-point number; ‘1500.’ is an integer, not a floating-point
number.
Emacs Lisp treats ‘-0.0’ as numerically equal to ordinary zero with
respect to ‘equal’ and ‘=’. This follows the IEEE floating-point
standard, which says ‘-0.0’ and ‘0.0’ are numerically equal even though
other operations can distinguish them.
The IEEE floating-point standard supports positive infinity and
negative infinity as floating-point values. It also provides for a
class of values called NaN, or “not a number”; numerical functions
return such values in cases where there is no correct answer. For
example, ‘(/ 0.0 0.0)’ returns a NaN. Although NaN values carry a sign,
for practical purposes there is no other significant difference between
different NaN values in Emacs Lisp.
Here are read syntaxes for these special floating-point values:
infinity
‘1.0e+INF’ and ‘-1.0e+INF’
not-a-number
‘0.0e+NaN’ and ‘-0.0e+NaN’
The following functions are specialized for handling floating-point
numbers:
-- Function: isnan x
This predicate returns ‘t’ if its floating-point argument is a NaN,
‘nil’ otherwise.
-- Function: frexp x
This function returns a cons cell ‘(S . E)’, where S and E are
respectively the significand and exponent of the floating-point
number X.
If X is finite, then S is a floating-point number between 0.5
(inclusive) and 1.0 (exclusive), E is an integer, and X = S * 2**E.
If X is zero or infinity, then S is the same as X. If X is a NaN,
then S is also a NaN. If X is zero, then E is 0.
-- Function: ldexp s e
Given a numeric significand S and an integer exponent E, this
function returns the floating point number S * 2**E.
-- Function: copysign x1 x2
This function copies the sign of X2 to the value of X1, and returns
the result. X1 and X2 must be floating point.
-- Function: logb x
This function returns the binary exponent of X. More precisely,
the value is the logarithm base 2 of |x|, rounded down to an
integer.
(logb 10)
⇒ 3
(logb 10.0e20)
⇒ 69