ErgoEmacsEmacsLispBlogEmacsLispBuy Tutorial

3.2 Floating Point Basics

Floating point numbers are useful for representing numbers that are not integral. The precise range of floating point numbers is machine-specific; it is the same as the range of the C data type double on the machine you are using.

The read-syntax for floating point numbers requires either a decimal point (with at least one digit following), an exponent, or both. For example, ‘1500.0’, ‘15e2’, ‘15.0e2’, ‘1.5e3’, and ‘.15e4’ are five ways of writing a floating point number whose value is 1500. They are all equivalent. You can also use a minus sign to write negative floating point numbers, as in ‘-1.0’.

Most modern computers support the IEEE floating point standard, which provides for 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. For practical purposes, there's no significant difference between different NaN values in Emacs Lisp, and there's no rule for precisely which NaN value should be used in a particular case, so Emacs Lisp doesn't try to distinguish them (but it does report the sign, if you print it). Here are the read syntaxes for these special floating point values:

positive infinity
1.0e+INF
negative infinity
-1.0e+INF
Not-a-number
0.0e+NaN’ or ‘-0.0e+NaN’.

To test whether a floating point value is a NaN, compare it with itself using =. That returns nil for a NaN, and t for any other floating point value.

The value -0.0 is distinguishable from ordinary zero in IEEE floating point, but Emacs Lisp equal and = consider them equal values.

You can use logb to extract the binary exponent of a floating point number (or estimate the logarithm of an integer):

— Function: logb number

This function returns the binary exponent of number. More precisely, the value is the logarithm of number base 2, rounded down to an integer.

          (logb 10)
               ⇒ 3
          (logb 10.0e20)
               ⇒ 69
— Variable: float-e

The mathematical constant e (2.71828…).

— Variable: float-pi

The mathematical constant pi (3.14159…).

blog comments powered by Disqus