0.8.0.4:
[sbcl.git] / src / code / float.lisp
1 ;;;; This file contains the definitions of float-specific number
2 ;;;; support (other than irrational stuff, which is in irrat.) There is
3 ;;;; code in here that assumes there are only two float formats: IEEE
4 ;;;; single and double. (LONG-FLOAT support has been added, but bugs
5 ;;;; may still remain due to old code which assumes this dichotomy.)
6
7 ;;;; This software is part of the SBCL system. See the README file for
8 ;;;; more information.
9 ;;;;
10 ;;;; This software is derived from the CMU CL system, which was
11 ;;;; written at Carnegie Mellon University and released into the
12 ;;;; public domain. The software is in the public domain and is
13 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
14 ;;;; files for more information.
15
16 (in-package "SB!KERNEL")
17 \f
18 ;;;; utilities
19
20 (eval-when (:compile-toplevel :load-toplevel :execute)
21
22 ;;; These functions let us create floats from bits with the
23 ;;; significand uniformly represented as an integer. This is less
24 ;;; efficient for double floats, but is more convenient when making
25 ;;; special values, etc.
26 (defun single-from-bits (sign exp sig)
27   (declare (type bit sign) (type (unsigned-byte 24) sig)
28            (type (unsigned-byte 8) exp))
29   (make-single-float
30    (dpb exp sb!vm:single-float-exponent-byte
31         (dpb sig sb!vm:single-float-significand-byte
32              (if (zerop sign) 0 -1)))))
33 (defun double-from-bits (sign exp sig)
34   (declare (type bit sign) (type (unsigned-byte 53) sig)
35            (type (unsigned-byte 11) exp))
36   (make-double-float (dpb exp sb!vm:double-float-exponent-byte
37                           (dpb (ash sig -32)
38                                sb!vm:double-float-significand-byte
39                                (if (zerop sign) 0 -1)))
40                      (ldb (byte 32 0) sig)))
41 #!+(and long-float x86)
42 (defun long-from-bits (sign exp sig)
43   (declare (type bit sign) (type (unsigned-byte 64) sig)
44            (type (unsigned-byte 15) exp))
45   (make-long-float (logior (ash sign 15) exp)
46                    (ldb (byte 32 32) sig)
47                    (ldb (byte 32 0) sig)))
48
49 ) ; EVAL-WHEN
50 \f
51 ;;;; float parameters
52
53 (defconstant least-positive-single-float (single-from-bits 0 0 1))
54 (defconstant least-positive-short-float least-positive-single-float)
55 (defconstant least-negative-single-float (single-from-bits 1 0 1))
56 (defconstant least-negative-short-float least-negative-single-float)
57 (defconstant least-positive-double-float (double-from-bits 0 0 1))
58 #!-long-float
59 (defconstant least-positive-long-float least-positive-double-float)
60 #!+(and long-float x86)
61 (defconstant least-positive-long-float (long-from-bits 0 0 1))
62 (defconstant least-negative-double-float (double-from-bits 1 0 1))
63 #!-long-float
64 (defconstant least-negative-long-float least-negative-double-float)
65 #!+(and long-float x86)
66 (defconstant least-negative-long-float (long-from-bits 1 0 1))
67
68 (defconstant least-positive-normalized-single-float
69   (single-from-bits 0 sb!vm:single-float-normal-exponent-min 0))
70 (defconstant least-positive-normalized-short-float
71   least-positive-normalized-single-float)
72 (defconstant least-negative-normalized-single-float
73   (single-from-bits 1 sb!vm:single-float-normal-exponent-min 0))
74 (defconstant least-negative-normalized-short-float
75   least-negative-normalized-single-float)
76 (defconstant least-positive-normalized-double-float
77   (double-from-bits 0 sb!vm:double-float-normal-exponent-min 0))
78 #!-long-float
79 (defconstant least-positive-normalized-long-float
80   least-positive-normalized-double-float)
81 #!+(and long-float x86)
82 (defconstant least-positive-normalized-long-float
83   (long-from-bits 0 sb!vm:long-float-normal-exponent-min
84                   (ash sb!vm:long-float-hidden-bit 32)))
85 (defconstant least-negative-normalized-double-float
86   (double-from-bits 1 sb!vm:double-float-normal-exponent-min 0))
87 #!-long-float
88 (defconstant least-negative-normalized-long-float
89   least-negative-normalized-double-float)
90 #!+(and long-float x86)
91 (defconstant least-negative-normalized-long-float
92   (long-from-bits 1 sb!vm:long-float-normal-exponent-min
93                   (ash sb!vm:long-float-hidden-bit 32)))
94
95 (defconstant most-positive-single-float
96   (single-from-bits 0 sb!vm:single-float-normal-exponent-max
97                     (ldb sb!vm:single-float-significand-byte -1)))
98 (defconstant most-positive-short-float most-positive-single-float)
99 (defconstant most-negative-single-float
100   (single-from-bits 1 sb!vm:single-float-normal-exponent-max
101                     (ldb sb!vm:single-float-significand-byte -1)))
102 (defconstant most-negative-short-float most-negative-single-float)
103 (defconstant most-positive-double-float
104   (double-from-bits 0 sb!vm:double-float-normal-exponent-max
105                     (ldb (byte sb!vm:double-float-digits 0) -1)))
106 #!-long-float
107 (defconstant most-positive-long-float most-positive-double-float)
108 #!+(and long-float x86)
109 (defconstant most-positive-long-float
110   (long-from-bits 0 sb!vm:long-float-normal-exponent-max
111                   (ldb (byte sb!vm:long-float-digits 0) -1)))
112 (defconstant most-negative-double-float
113   (double-from-bits 1 sb!vm:double-float-normal-exponent-max
114                     (ldb (byte sb!vm:double-float-digits 0) -1)))
115 #!-long-float
116 (defconstant most-negative-long-float most-negative-double-float)
117 #!+(and long-float x86)
118 (defconstant most-negative-long-float
119   (long-from-bits 1 sb!vm:long-float-normal-exponent-max
120                   (ldb (byte sb!vm:long-float-digits 0) -1)))
121
122 ;;; We don't want to do these DEFCONSTANTs at cross-compilation time,
123 ;;; because the cross-compilation host might not support floating
124 ;;; point infinities. Putting them inside a LET removes
125 ;;; toplevel-formness, so that any EVAL-WHEN trickiness in the
126 ;;; DEFCONSTANT forms is suppressed.
127 (let ()
128 (defconstant single-float-positive-infinity
129   (single-from-bits 0 (1+ sb!vm:single-float-normal-exponent-max) 0))
130 (defconstant short-float-positive-infinity single-float-positive-infinity)
131 (defconstant single-float-negative-infinity
132   (single-from-bits 1 (1+ sb!vm:single-float-normal-exponent-max) 0))
133 (defconstant short-float-negative-infinity single-float-negative-infinity)
134 (defconstant double-float-positive-infinity
135   (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0))
136 #!+(not long-float)
137 (defconstant long-float-positive-infinity double-float-positive-infinity)
138 #!+(and long-float x86)
139 (defconstant long-float-positive-infinity
140   (long-from-bits 0 (1+ sb!vm:long-float-normal-exponent-max)
141                   (ash sb!vm:long-float-hidden-bit 32)))
142 (defconstant double-float-negative-infinity
143   (double-from-bits 1 (1+ sb!vm:double-float-normal-exponent-max) 0))
144 #!+(not long-float)
145 (defconstant long-float-negative-infinity double-float-negative-infinity)
146 #!+(and long-float x86)
147 (defconstant long-float-negative-infinity
148   (long-from-bits 1 (1+ sb!vm:long-float-normal-exponent-max)
149                   (ash sb!vm:long-float-hidden-bit 32)))
150 ) ; LET-to-suppress-possible-EVAL-WHENs
151
152 (defconstant single-float-epsilon
153   (single-from-bits 0 (- sb!vm:single-float-bias
154                          (1- sb!vm:single-float-digits)) 1))
155 (defconstant short-float-epsilon single-float-epsilon)
156 (defconstant single-float-negative-epsilon
157   (single-from-bits 0 (- sb!vm:single-float-bias sb!vm:single-float-digits) 1))
158 (defconstant short-float-negative-epsilon single-float-negative-epsilon)
159 (defconstant double-float-epsilon
160   (double-from-bits 0 (- sb!vm:double-float-bias
161                          (1- sb!vm:double-float-digits)) 1))
162 #!-long-float
163 (defconstant long-float-epsilon double-float-epsilon)
164 #!+(and long-float x86)
165 (defconstant long-float-epsilon
166   (long-from-bits 0 (- sb!vm:long-float-bias (1- sb!vm:long-float-digits))
167                   (+ 1 (ash sb!vm:long-float-hidden-bit 32))))
168 (defconstant double-float-negative-epsilon
169   (double-from-bits 0 (- sb!vm:double-float-bias sb!vm:double-float-digits) 1))
170 #!-long-float
171 (defconstant long-float-negative-epsilon double-float-negative-epsilon)
172 #!+(and long-float x86)
173 (defconstant long-float-negative-epsilon
174   (long-from-bits 0 (- sb!vm:long-float-bias sb!vm:long-float-digits)
175                   (+ 1 (ash sb!vm:long-float-hidden-bit 32))))
176 \f
177 ;;;; float predicates and environment query
178
179 #!-sb-fluid
180 (declaim (maybe-inline float-denormalized-p float-infinity-p float-nan-p
181                        float-trapping-nan-p))
182
183 (defun float-denormalized-p (x)
184   #!+sb-doc
185   "Return true if the float X is denormalized."
186   (number-dispatch ((x float))
187     ((single-float)
188      (and (zerop (ldb sb!vm:single-float-exponent-byte (single-float-bits x)))
189           (not (zerop x))))
190     ((double-float)
191      (and (zerop (ldb sb!vm:double-float-exponent-byte
192                       (double-float-high-bits x)))
193           (not (zerop x))))
194     #!+(and long-float x86)
195     ((long-float)
196      (and (zerop (ldb sb!vm:long-float-exponent-byte (long-float-exp-bits x)))
197           (not (zerop x))))))
198
199 (defmacro !define-float-dispatching-function
200     (name doc single double #!+(and long-float x86) long)
201   `(defun ,name (x)
202     ,doc
203     (number-dispatch ((x float))
204      ((single-float)
205       (let ((bits (single-float-bits x)))
206         (and (> (ldb sb!vm:single-float-exponent-byte bits)
207                 sb!vm:single-float-normal-exponent-max)
208              ,single)))
209      ((double-float)
210       (let ((hi (double-float-high-bits x))
211             (lo (double-float-low-bits x)))
212         (declare (ignorable lo))
213         (and (> (ldb sb!vm:double-float-exponent-byte hi)
214                 sb!vm:double-float-normal-exponent-max)
215              ,double)))
216      #!+(and long-float x86)
217      ((long-float)
218       (let ((exp (long-float-exp-bits x))
219             (hi (long-float-high-bits x))
220             (lo (long-float-low-bits x)))
221         (declare (ignorable lo))
222         (and (> (ldb sb!vm:long-float-exponent-byte exp)
223                 sb!vm:long-float-normal-exponent-max)
224              ,long))))))
225
226 (!define-float-dispatching-function float-infinity-p
227   "Return true if the float X is an infinity (+ or -)."
228   (zerop (ldb sb!vm:single-float-significand-byte bits))
229   (and (zerop (ldb sb!vm:double-float-significand-byte hi))
230        (zerop lo))
231   #!+(and long-float x86)
232   (and (zerop (ldb sb!vm:long-float-significand-byte hi))
233        (zerop lo)))
234
235 (!define-float-dispatching-function float-nan-p
236   "Return true if the float X is a NaN (Not a Number)."
237   (not (zerop (ldb sb!vm:single-float-significand-byte bits)))
238   (or (not (zerop (ldb sb!vm:double-float-significand-byte hi)))
239       (not (zerop lo)))
240   #!+(and long-float x86)
241   (or (not (zerop (ldb sb!vm:long-float-significand-byte hi)))
242       (not (zerop lo))))
243
244 (!define-float-dispatching-function float-trapping-nan-p
245   "Return true if the float X is a trapping NaN (Not a Number)."
246   (zerop (logand (ldb sb!vm:single-float-significand-byte bits)
247                  sb!vm:single-float-trapping-nan-bit))
248   (zerop (logand (ldb sb!vm:double-float-significand-byte hi)
249                  sb!vm:double-float-trapping-nan-bit))
250   #!+(and long-float x86)
251   (zerop (logand (ldb sb!vm:long-float-significand-byte hi)
252                  sb!vm:long-float-trapping-nan-bit)))
253
254 ;;; If denormalized, use a subfunction from INTEGER-DECODE-FLOAT to find the
255 ;;; actual exponent (and hence how denormalized it is), otherwise we just
256 ;;; return the number of digits or 0.
257 #!-sb-fluid (declaim (maybe-inline float-precision))
258 (defun float-precision (f)
259   #!+sb-doc
260   "Return a non-negative number of significant digits in its float argument.
261   Will be less than FLOAT-DIGITS if denormalized or zero."
262   (macrolet ((frob (digits bias decode)
263                `(cond ((zerop f) 0)
264                       ((float-denormalized-p f)
265                        (multiple-value-bind (ignore exp) (,decode f)
266                          (declare (ignore ignore))
267                          (truly-the fixnum
268                                     (+ ,digits (1- ,digits) ,bias exp))))
269                       (t
270                        ,digits))))
271     (number-dispatch ((f float))
272       ((single-float)
273        (frob sb!vm:single-float-digits sb!vm:single-float-bias
274          integer-decode-single-denorm))
275       ((double-float)
276        (frob sb!vm:double-float-digits sb!vm:double-float-bias
277          integer-decode-double-denorm))
278       #!+long-float
279       ((long-float)
280        (frob sb!vm:long-float-digits sb!vm:long-float-bias
281          integer-decode-long-denorm)))))
282
283 (defun float-sign (float1 &optional (float2 (float 1 float1)))
284   #!+sb-doc
285   "Return a floating-point number that has the same sign as
286    FLOAT1 and, if FLOAT2 is given, has the same absolute value
287    as FLOAT2."
288   (declare (float float1 float2))
289   (* (if (etypecase float1
290            (single-float (minusp (single-float-bits float1)))
291            (double-float (minusp (double-float-high-bits float1)))
292            #!+long-float
293            (long-float (minusp (long-float-exp-bits float1))))
294          (float -1 float1)
295          (float 1 float1))
296      (abs float2)))
297
298 (defun float-format-digits (format)
299   (ecase format
300     ((short-float single-float) sb!vm:single-float-digits)
301     ((double-float #!-long-float long-float) sb!vm:double-float-digits)
302     #!+long-float
303     (long-float sb!vm:long-float-digits)))
304
305 #!-sb-fluid (declaim (inline float-digits float-radix))
306
307 (defun float-digits (f)
308   (number-dispatch ((f float))
309     ((single-float) sb!vm:single-float-digits)
310     ((double-float) sb!vm:double-float-digits)
311     #!+long-float
312     ((long-float) sb!vm:long-float-digits)))
313
314 (defun float-radix (x)
315   #!+sb-doc
316   "Return (as an integer) the radix b of its floating-point argument."
317   2)
318 \f
319 ;;;; INTEGER-DECODE-FLOAT and DECODE-FLOAT
320
321 #!-sb-fluid
322 (declaim (maybe-inline integer-decode-single-float
323                        integer-decode-double-float))
324
325 ;;; Handle the denormalized case of INTEGER-DECODE-FLOAT for SINGLE-FLOAT.
326 (defun integer-decode-single-denorm (x)
327   (declare (type single-float x))
328   (let* ((bits (single-float-bits (abs x)))
329          (sig (ash (ldb sb!vm:single-float-significand-byte bits) 1))
330          (extra-bias 0))
331     (declare (type (unsigned-byte 24) sig)
332              (type (integer 0 23) extra-bias))
333     (loop
334       (unless (zerop (logand sig sb!vm:single-float-hidden-bit))
335         (return))
336       (setq sig (ash sig 1))
337       (incf extra-bias))
338     (values sig
339             (- (- sb!vm:single-float-bias)
340                sb!vm:single-float-digits
341                extra-bias)
342             (if (minusp (float-sign x)) -1 1))))
343
344 ;;; Handle the single-float case of INTEGER-DECODE-FLOAT. If an infinity or
345 ;;; NaN, error. If a denorm, call i-d-s-DENORM to handle it.
346 (defun integer-decode-single-float (x)
347   (declare (single-float x))
348   (let* ((bits (single-float-bits (abs x)))
349          (exp (ldb sb!vm:single-float-exponent-byte bits))
350          (sig (ldb sb!vm:single-float-significand-byte bits))
351          (sign (if (minusp (float-sign x)) -1 1))
352          (biased (- exp sb!vm:single-float-bias sb!vm:single-float-digits)))
353     (declare (fixnum biased))
354     (unless (<= exp sb!vm:single-float-normal-exponent-max)
355       (error "can't decode NaN or infinity: ~S" x))
356     (cond ((and (zerop exp) (zerop sig))
357            (values 0 biased sign))
358           ((< exp sb!vm:single-float-normal-exponent-min)
359            (integer-decode-single-denorm x))
360           (t
361            (values (logior sig sb!vm:single-float-hidden-bit) biased sign)))))
362
363 ;;; like INTEGER-DECODE-SINGLE-DENORM, only doubly so
364 (defun integer-decode-double-denorm (x)
365   (declare (type double-float x))
366   (let* ((high-bits (double-float-high-bits (abs x)))
367          (sig-high (ldb sb!vm:double-float-significand-byte high-bits))
368          (low-bits (double-float-low-bits x))
369          (sign (if (minusp (float-sign x)) -1 1))
370          (biased (- (- sb!vm:double-float-bias) sb!vm:double-float-digits)))
371     (if (zerop sig-high)
372         (let ((sig low-bits)
373               (extra-bias (- sb!vm:double-float-digits 33))
374               (bit (ash 1 31)))
375           (declare (type (unsigned-byte 32) sig) (fixnum extra-bias))
376           (loop
377             (unless (zerop (logand sig bit)) (return))
378             (setq sig (ash sig 1))
379             (incf extra-bias))
380           (values (ash sig (- sb!vm:double-float-digits 32))
381                   (truly-the fixnum (- biased extra-bias))
382                   sign))
383         (let ((sig (ash sig-high 1))
384               (extra-bias 0))
385           (declare (type (unsigned-byte 32) sig) (fixnum extra-bias))
386           (loop
387             (unless (zerop (logand sig sb!vm:double-float-hidden-bit))
388               (return))
389             (setq sig (ash sig 1))
390             (incf extra-bias))
391           (values (logior (ash sig 32) (ash low-bits (1- extra-bias)))
392                   (truly-the fixnum (- biased extra-bias))
393                   sign)))))
394
395 ;;; like INTEGER-DECODE-SINGLE-FLOAT, only doubly so
396 (defun integer-decode-double-float (x)
397   (declare (double-float x))
398   (let* ((abs (abs x))
399          (hi (double-float-high-bits abs))
400          (lo (double-float-low-bits abs))
401          (exp (ldb sb!vm:double-float-exponent-byte hi))
402          (sig (ldb sb!vm:double-float-significand-byte hi))
403          (sign (if (minusp (float-sign x)) -1 1))
404          (biased (- exp sb!vm:double-float-bias sb!vm:double-float-digits)))
405     (declare (fixnum biased))
406     (unless (<= exp sb!vm:double-float-normal-exponent-max)
407       (error "Can't decode NaN or infinity: ~S." x))
408     (cond ((and (zerop exp) (zerop sig) (zerop lo))
409            (values 0 biased sign))
410           ((< exp sb!vm:double-float-normal-exponent-min)
411            (integer-decode-double-denorm x))
412           (t
413            (values
414             (logior (ash (logior (ldb sb!vm:double-float-significand-byte hi)
415                                  sb!vm:double-float-hidden-bit)
416                          32)
417                     lo)
418             biased sign)))))
419
420 #!+(and long-float x86)
421 (defun integer-decode-long-denorm (x)
422   (declare (type long-float x))
423   (let* ((high-bits (long-float-high-bits (abs x)))
424          (sig-high (ldb sb!vm:long-float-significand-byte high-bits))
425          (low-bits (long-float-low-bits x))
426          (sign (if (minusp (float-sign x)) -1 1))
427          (biased (- (- sb!vm:long-float-bias) sb!vm:long-float-digits)))
428     (if (zerop sig-high)
429         (let ((sig low-bits)
430               (extra-bias (- sb!vm:long-float-digits 33))
431               (bit (ash 1 31)))
432           (declare (type (unsigned-byte 32) sig) (fixnum extra-bias))
433           (loop
434             (unless (zerop (logand sig bit)) (return))
435             (setq sig (ash sig 1))
436             (incf extra-bias))
437           (values (ash sig (- sb!vm:long-float-digits 32))
438                   (truly-the fixnum (- biased extra-bias))
439                   sign))
440         (let ((sig (ash sig-high 1))
441               (extra-bias 0))
442           (declare (type (unsigned-byte 32) sig) (fixnum extra-bias))
443           (loop
444             (unless (zerop (logand sig sb!vm:long-float-hidden-bit))
445               (return))
446             (setq sig (ash sig 1))
447             (incf extra-bias))
448           (values (logior (ash sig 32) (ash low-bits (1- extra-bias)))
449                   (truly-the fixnum (- biased extra-bias))
450                   sign)))))
451
452 #!+(and long-float x86)
453 (defun integer-decode-long-float (x)
454   (declare (long-float x))
455   (let* ((hi (long-float-high-bits x))
456          (lo (long-float-low-bits x))
457          (exp-bits (long-float-exp-bits x))
458          (exp (ldb sb!vm:long-float-exponent-byte exp-bits))
459          (sign (if (minusp exp-bits) -1 1))
460          (biased (- exp sb!vm:long-float-bias sb!vm:long-float-digits)))
461     (declare (fixnum biased))
462     (unless (<= exp sb!vm:long-float-normal-exponent-max)
463       (error "can't decode NaN or infinity: ~S" x))
464     (cond ((and (zerop exp) (zerop hi) (zerop lo))
465            (values 0 biased sign))
466           ((< exp sb!vm:long-float-normal-exponent-min)
467            (integer-decode-long-denorm x))
468           (t
469            (values (logior (ash hi 32) lo) biased sign)))))
470
471 ;;; Dispatch to the correct type-specific i-d-f function.
472 (defun integer-decode-float (x)
473   #!+sb-doc
474   "Return three values:
475    1) an integer representation of the significand.
476    2) the exponent for the power of 2 that the significand must be multiplied
477       by to get the actual value. This differs from the DECODE-FLOAT exponent
478       by FLOAT-DIGITS, since the significand has been scaled to have all its
479       digits before the radix point.
480    3) -1 or 1 (i.e. the sign of the argument.)"
481   (number-dispatch ((x float))
482     ((single-float)
483      (integer-decode-single-float x))
484     ((double-float)
485      (integer-decode-double-float x))
486     #!+long-float
487     ((long-float)
488      (integer-decode-long-float x))))
489
490 #!-sb-fluid (declaim (maybe-inline decode-single-float decode-double-float))
491
492 ;;; Handle the denormalized case of DECODE-SINGLE-FLOAT. We call
493 ;;; INTEGER-DECODE-SINGLE-DENORM and then make the result into a float.
494 (defun decode-single-denorm (x)
495   (declare (type single-float x))
496   (multiple-value-bind (sig exp sign) (integer-decode-single-denorm x)
497     (values (make-single-float
498              (dpb sig sb!vm:single-float-significand-byte
499                   (dpb sb!vm:single-float-bias
500                        sb!vm:single-float-exponent-byte
501                        0)))
502             (truly-the fixnum (+ exp sb!vm:single-float-digits))
503             (float sign x))))
504
505 ;;; Handle the single-float case of DECODE-FLOAT. If an infinity or NaN,
506 ;;; error. If a denorm, call d-s-DENORM to handle it.
507 (defun decode-single-float (x)
508   (declare (single-float x))
509   (let* ((bits (single-float-bits (abs x)))
510          (exp (ldb sb!vm:single-float-exponent-byte bits))
511          (sign (float-sign x))
512          (biased (truly-the single-float-exponent
513                             (- exp sb!vm:single-float-bias))))
514     (unless (<= exp sb!vm:single-float-normal-exponent-max)
515       (error "can't decode NaN or infinity: ~S" x))
516     (cond ((zerop x)
517            (values 0.0f0 biased sign))
518           ((< exp sb!vm:single-float-normal-exponent-min)
519            (decode-single-denorm x))
520           (t
521            (values (make-single-float
522                     (dpb sb!vm:single-float-bias
523                          sb!vm:single-float-exponent-byte
524                          bits))
525                    biased sign)))))
526
527 ;;; like DECODE-SINGLE-DENORM, only doubly so
528 (defun decode-double-denorm (x)
529   (declare (double-float x))
530   (multiple-value-bind (sig exp sign) (integer-decode-double-denorm x)
531     (values (make-double-float
532              (dpb (logand (ash sig -32) (lognot sb!vm:double-float-hidden-bit))
533                   sb!vm:double-float-significand-byte
534                   (dpb sb!vm:double-float-bias
535                        sb!vm:double-float-exponent-byte 0))
536              (ldb (byte 32 0) sig))
537             (truly-the fixnum (+ exp sb!vm:double-float-digits))
538             (float sign x))))
539
540 ;;; like DECODE-SINGLE-FLOAT, only doubly so
541 (defun decode-double-float (x)
542   (declare (double-float x))
543   (let* ((abs (abs x))
544          (hi (double-float-high-bits abs))
545          (lo (double-float-low-bits abs))
546          (exp (ldb sb!vm:double-float-exponent-byte hi))
547          (sign (float-sign x))
548          (biased (truly-the double-float-exponent
549                             (- exp sb!vm:double-float-bias))))
550     (unless (<= exp sb!vm:double-float-normal-exponent-max)
551       (error "can't decode NaN or infinity: ~S" x))
552     (cond ((zerop x)
553            (values 0.0d0 biased sign))
554           ((< exp sb!vm:double-float-normal-exponent-min)
555            (decode-double-denorm x))
556           (t
557            (values (make-double-float
558                     (dpb sb!vm:double-float-bias
559                          sb!vm:double-float-exponent-byte hi)
560                     lo)
561                    biased sign)))))
562
563 #!+(and long-float x86)
564 (defun decode-long-denorm (x)
565   (declare (long-float x))
566   (multiple-value-bind (sig exp sign) (integer-decode-long-denorm x)
567     (values (make-long-float sb!vm:long-float-bias (ash sig -32)
568                              (ldb (byte 32 0) sig))
569             (truly-the fixnum (+ exp sb!vm:long-float-digits))
570             (float sign x))))
571
572 #!+(and long-float x86)
573 (defun decode-long-float (x)
574   (declare (long-float x))
575   (let* ((hi (long-float-high-bits x))
576          (lo (long-float-low-bits x))
577          (exp-bits (long-float-exp-bits x))
578          (exp (ldb sb!vm:long-float-exponent-byte exp-bits))
579          (sign (if (minusp exp-bits) -1l0 1l0))
580          (biased (truly-the long-float-exponent
581                             (- exp sb!vm:long-float-bias))))
582     (unless (<= exp sb!vm:long-float-normal-exponent-max)
583       (error "can't decode NaN or infinity: ~S" x))
584     (cond ((zerop x)
585            (values 0.0l0 biased sign))
586           ((< exp sb!vm:long-float-normal-exponent-min)
587            (decode-long-denorm x))
588           (t
589            (values (make-long-float
590                     (dpb sb!vm:long-float-bias sb!vm:long-float-exponent-byte
591                          exp-bits)
592                     hi
593                     lo)
594                    biased sign)))))
595
596 ;;; Dispatch to the appropriate type-specific function.
597 (defun decode-float (f)
598   #!+sb-doc
599   "Return three values:
600    1) a floating-point number representing the significand. This is always
601       between 0.5 (inclusive) and 1.0 (exclusive).
602    2) an integer representing the exponent.
603    3) -1.0 or 1.0 (i.e. the sign of the argument.)"
604   (number-dispatch ((f float))
605     ((single-float)
606      (decode-single-float f))
607     ((double-float)
608      (decode-double-float f))
609     #!+long-float
610     ((long-float)
611      (decode-long-float f))))
612 \f
613 ;;;; SCALE-FLOAT
614
615 #!-sb-fluid (declaim (maybe-inline scale-single-float scale-double-float))
616
617 ;;; Handle float scaling where the X is denormalized or the result is
618 ;;; denormalized or underflows to 0.
619 (defun scale-float-maybe-underflow (x exp)
620   (multiple-value-bind (sig old-exp) (integer-decode-float x)
621     (let* ((digits (float-digits x))
622            (new-exp (+ exp old-exp digits
623                        (etypecase x
624                          (single-float sb!vm:single-float-bias)
625                          (double-float sb!vm:double-float-bias))))
626            (sign (if (minusp (float-sign x)) 1 0)))
627       (cond
628        ((< new-exp
629            (etypecase x
630              (single-float sb!vm:single-float-normal-exponent-min)
631              (double-float sb!vm:double-float-normal-exponent-min)))
632         (when (sb!vm:current-float-trap :inexact)
633           (error 'floating-point-inexact :operation 'scale-float
634                  :operands (list x exp)))
635         (when (sb!vm:current-float-trap :underflow)
636           (error 'floating-point-underflow :operation 'scale-float
637                  :operands (list x exp)))
638         (let ((shift (1- new-exp)))
639           (if (< shift (- (1- digits)))
640               (float-sign x 0.0)
641               (etypecase x
642                 (single-float (single-from-bits sign 0 (ash sig shift)))
643                 (double-float (double-from-bits sign 0 (ash sig shift)))))))
644        (t
645         (etypecase x
646           (single-float (single-from-bits sign new-exp sig))
647           (double-float (double-from-bits sign new-exp sig))))))))
648
649 ;;; Called when scaling a float overflows, or the original float was a
650 ;;; NaN or infinity. If overflow errors are trapped, then error,
651 ;;; otherwise return the appropriate infinity. If a NaN, signal or not
652 ;;; as appropriate.
653 (defun scale-float-maybe-overflow (x exp)
654   (cond
655    ((float-infinity-p x)
656     ;; Infinity is infinity, no matter how small...
657     x)
658    ((float-nan-p x)
659     (when (and (float-trapping-nan-p x)
660                (sb!vm:current-float-trap :invalid))
661       (error 'floating-point-invalid-operation :operation 'scale-float
662              :operands (list x exp)))
663     x)
664    (t
665     (when (sb!vm:current-float-trap :overflow)
666       (error 'floating-point-overflow :operation 'scale-float
667              :operands (list x exp)))
668     (when (sb!vm:current-float-trap :inexact)
669       (error 'floating-point-inexact :operation 'scale-float
670              :operands (list x exp)))
671     (* (float-sign x)
672        (etypecase x
673          (single-float single-float-positive-infinity)
674          (double-float double-float-positive-infinity))))))
675
676 ;;; Scale a single or double float, calling the correct over/underflow
677 ;;; functions.
678 (defun scale-single-float (x exp)
679   (declare (single-float x) (fixnum exp))
680   (let* ((bits (single-float-bits x))
681          (old-exp (ldb sb!vm:single-float-exponent-byte bits))
682          (new-exp (+ old-exp exp)))
683     (cond
684      ((zerop x) x)
685      ((or (< old-exp sb!vm:single-float-normal-exponent-min)
686           (< new-exp sb!vm:single-float-normal-exponent-min))
687       (scale-float-maybe-underflow x exp))
688      ((or (> old-exp sb!vm:single-float-normal-exponent-max)
689           (> new-exp sb!vm:single-float-normal-exponent-max))
690       (scale-float-maybe-overflow x exp))
691      (t
692       (make-single-float (dpb new-exp
693                               sb!vm:single-float-exponent-byte
694                               bits))))))
695 (defun scale-double-float (x exp)
696   (declare (double-float x) (fixnum exp))
697   (let* ((hi (double-float-high-bits x))
698          (lo (double-float-low-bits x))
699          (old-exp (ldb sb!vm:double-float-exponent-byte hi))
700          (new-exp (+ old-exp exp)))
701     (cond
702      ((zerop x) x)
703      ((or (< old-exp sb!vm:double-float-normal-exponent-min)
704           (< new-exp sb!vm:double-float-normal-exponent-min))
705       (scale-float-maybe-underflow x exp))
706      ((or (> old-exp sb!vm:double-float-normal-exponent-max)
707           (> new-exp sb!vm:double-float-normal-exponent-max))
708       (scale-float-maybe-overflow x exp))
709      (t
710       (make-double-float (dpb new-exp sb!vm:double-float-exponent-byte hi)
711                          lo)))))
712
713 #!+(and x86 long-float)
714 (defun scale-long-float (x exp)
715   (declare (long-float x) (fixnum exp))
716   (scale-float x exp))
717
718 ;;; Dispatch to the correct type-specific scale-float function.
719 (defun scale-float (f ex)
720   #!+sb-doc
721   "Return the value (* f (expt (float 2 f) ex)), but with no unnecessary loss
722   of precision or overflow."
723   (number-dispatch ((f float))
724     ((single-float)
725      (scale-single-float f ex))
726     ((double-float)
727      (scale-double-float f ex))
728     #!+long-float
729     ((long-float)
730      (scale-long-float f ex))))
731 \f
732 ;;;; converting to/from floats
733
734 (defun float (number &optional (other () otherp))
735   #!+sb-doc
736   "Converts any REAL to a float. If OTHER is not provided, it returns a
737   SINGLE-FLOAT if NUMBER is not already a FLOAT. If OTHER is provided, the
738   result is the same float format as OTHER."
739   (if otherp
740       (number-dispatch ((number real) (other float))
741         (((foreach rational single-float double-float #!+long-float long-float)
742           (foreach single-float double-float #!+long-float long-float))
743          (coerce number '(dispatch-type other))))
744       (if (floatp number)
745           number
746           (coerce number 'single-float))))
747
748 (macrolet ((frob (name type)
749              `(defun ,name (x)
750                 (number-dispatch ((x real))
751                   (((foreach single-float double-float #!+long-float long-float
752                              fixnum))
753                    (coerce x ',type))
754                   ((bignum)
755                    (bignum-to-float x ',type))
756                   ((ratio)
757                    (float-ratio x ',type))))))
758   (frob %single-float single-float)
759   (frob %double-float double-float)
760   #!+long-float
761   (frob %long-float long-float))
762
763 ;;; Convert a ratio to a float. We avoid any rounding error by doing an
764 ;;; integer division. Accuracy is important to preserve read/print
765 ;;; consistency, since this is ultimately how the reader reads a float. We
766 ;;; scale the numerator by a power of two until the division results in the
767 ;;; desired number of fraction bits, then do round-to-nearest.
768 (defun float-ratio (x format)
769   (let* ((signed-num (numerator x))
770          (plusp (plusp signed-num))
771          (num (if plusp signed-num (- signed-num)))
772          (den (denominator x))
773          (digits (float-format-digits format))
774          (scale 0))
775     (declare (fixnum digits scale))
776     ;; Strip any trailing zeros from the denominator and move it into the scale
777     ;; factor (to minimize the size of the operands.)
778     (let ((den-twos (1- (integer-length (logxor den (1- den))))))
779       (declare (fixnum den-twos))
780       (decf scale den-twos)
781       (setq den (ash den (- den-twos))))
782     ;; Guess how much we need to scale by from the magnitudes of the numerator
783     ;; and denominator. We want one extra bit for a guard bit.
784     (let* ((num-len (integer-length num))
785            (den-len (integer-length den))
786            (delta (- den-len num-len))
787            (shift (1+ (the fixnum (+ delta digits))))
788            (shifted-num (ash num shift)))
789       (declare (fixnum delta shift))
790       (decf scale delta)
791       (labels ((float-and-scale (bits)
792                  (let* ((bits (ash bits -1))
793                         (len (integer-length bits)))
794                    (cond ((> len digits)
795                           (aver (= len (the fixnum (1+ digits))))
796                           (scale-float (floatit (ash bits -1)) (1+ scale)))
797                          (t
798                           (scale-float (floatit bits) scale)))))
799                (floatit (bits)
800                  (let ((sign (if plusp 0 1)))
801                    (case format
802                      (single-float
803                       (single-from-bits sign sb!vm:single-float-bias bits))
804                      (double-float
805                       (double-from-bits sign sb!vm:double-float-bias bits))
806                      #!+long-float
807                      (long-float
808                       (long-from-bits sign sb!vm:long-float-bias bits))))))
809         (loop
810           (multiple-value-bind (fraction-and-guard rem)
811               (truncate shifted-num den)
812             (let ((extra (- (integer-length fraction-and-guard) digits)))
813               (declare (fixnum extra))
814               (cond ((/= extra 1)
815                      (aver (> extra 1)))
816                     ((oddp fraction-and-guard)
817                      (return
818                       (if (zerop rem)
819                           (float-and-scale
820                            (if (zerop (logand fraction-and-guard 2))
821                                fraction-and-guard
822                                (1+ fraction-and-guard)))
823                           (float-and-scale (1+ fraction-and-guard)))))
824                     (t
825                      (return (float-and-scale fraction-and-guard)))))
826             (setq shifted-num (ash shifted-num -1))
827             (incf scale)))))))
828
829 #|
830 These might be useful if we ever have a machine without float/integer
831 conversion hardware. For now, we'll use special ops that
832 uninterruptibly frob the rounding modes & do ieee round-to-integer.
833
834 ;;; The compiler compiles a call to this when we are doing %UNARY-TRUNCATE
835 ;;; and the result is known to be a fixnum. We can avoid some generic
836 ;;; arithmetic in this case.
837 (defun %unary-truncate-single-float/fixnum (x)
838   (declare (single-float x) (values fixnum))
839   (locally (declare (optimize (speed 3) (safety 0)))
840     (let* ((bits (single-float-bits x))
841            (exp (ldb sb!vm:single-float-exponent-byte bits))
842            (frac (logior (ldb sb!vm:single-float-significand-byte bits)
843                          sb!vm:single-float-hidden-bit))
844            (shift (- exp sb!vm:single-float-digits sb!vm:single-float-bias)))
845       (when (> exp sb!vm:single-float-normal-exponent-max)
846         (error 'floating-point-invalid-operation :operator 'truncate
847                :operands (list x)))
848       (if (<= shift (- sb!vm:single-float-digits))
849           0
850           (let ((res (ash frac shift)))
851             (declare (type (unsigned-byte 31) res))
852             (if (minusp bits)
853                 (- res)
854                 res))))))
855
856 ;;; Double-float version of this operation (see above single op).
857 (defun %unary-truncate-double-float/fixnum (x)
858   (declare (double-float x) (values fixnum))
859   (locally (declare (optimize (speed 3) (safety 0)))
860     (let* ((hi-bits (double-float-high-bits x))
861            (exp (ldb sb!vm:double-float-exponent-byte hi-bits))
862            (frac (logior (ldb sb!vm:double-float-significand-byte hi-bits)
863                          sb!vm:double-float-hidden-bit))
864            (shift (- exp (- sb!vm:double-float-digits sb!vm:n-word-bits)
865                      sb!vm:double-float-bias)))
866       (when (> exp sb!vm:double-float-normal-exponent-max)
867         (error 'floating-point-invalid-operation :operator 'truncate
868                :operands (list x)))
869       (if (<= shift (- sb!vm:n-word-bits sb!vm:double-float-digits))
870           0
871           (let* ((res-hi (ash frac shift))
872                  (res (if (plusp shift)
873                           (logior res-hi
874                                   (the fixnum
875                                        (ash (double-float-low-bits x)
876                                             (- shift sb!vm:n-word-bits))))
877                           res-hi)))
878             (declare (type (unsigned-byte 31) res-hi res))
879             (if (minusp hi-bits)
880                 (- res)
881                 res))))))
882 |#
883
884 ;;; This function is called when we are doing a truncate without any funky
885 ;;; divisor, i.e. converting a float or ratio to an integer. Note that we do
886 ;;; *not* return the second value of truncate, so it must be computed by the
887 ;;; caller if needed.
888 ;;;
889 ;;; In the float case, we pick off small arguments so that compiler can use
890 ;;; special-case operations. We use an exclusive test, since (due to round-off
891 ;;; error), (float most-positive-fixnum) may be greater than
892 ;;; most-positive-fixnum.
893 (defun %unary-truncate (number)
894   (number-dispatch ((number real))
895     ((integer) number)
896     ((ratio) (values (truncate (numerator number) (denominator number))))
897     (((foreach single-float double-float #!+long-float long-float))
898      (if (< (float most-negative-fixnum number)
899             number
900             (float most-positive-fixnum number))
901          (truly-the fixnum (%unary-truncate number))
902          (multiple-value-bind (bits exp) (integer-decode-float number)
903            (let ((res (ash bits exp)))
904              (if (minusp number)
905                  (- res)
906                  res)))))))
907
908 ;;; Similar to %UNARY-TRUNCATE, but rounds to the nearest integer. If we
909 ;;; can't use the round primitive, then we do our own round-to-nearest on the
910 ;;; result of i-d-f. [Note that this rounding will really only happen with
911 ;;; double floats, since the whole single-float fraction will fit in a fixnum,
912 ;;; so all single-floats larger than most-positive-fixnum can be precisely
913 ;;; represented by an integer.]
914 (defun %unary-round (number)
915   (number-dispatch ((number real))
916     ((integer) number)
917     ((ratio) (values (round (numerator number) (denominator number))))
918     (((foreach single-float double-float #!+long-float long-float))
919      (if (< (float most-negative-fixnum number)
920             number
921             (float most-positive-fixnum number))
922          (truly-the fixnum (%unary-round number))
923          (multiple-value-bind (bits exp) (integer-decode-float number)
924            (let* ((shifted (ash bits exp))
925                   (rounded (if (and (minusp exp)
926                                     (oddp shifted)
927                                     (eql (logand bits
928                                                  (lognot (ash -1 (- exp))))
929                                          (ash 1 (- -1 exp))))
930                                (1+ shifted)
931                                shifted)))
932              (if (minusp number)
933                  (- rounded)
934                  rounded)))))))
935
936 (defun rational (x)
937   #!+sb-doc
938   "RATIONAL produces a rational number for any real numeric argument. This is
939   more efficient than RATIONALIZE, but it assumes that floating-point is
940   completely accurate, giving a result that isn't as pretty."
941   (number-dispatch ((x real))
942     (((foreach single-float double-float #!+long-float long-float))
943      (multiple-value-bind (bits exp) (integer-decode-float x)
944        (if (eql bits 0)
945            0
946            (let* ((int (if (minusp x) (- bits) bits))
947                   (digits (float-digits x))
948                   (ex (+ exp digits)))
949              (if (minusp ex)
950                  (integer-/-integer int (ash 1 (+ digits (- ex))))
951                  (integer-/-integer (ash int ex) (ash 1 digits)))))))
952     ((rational) x)))
953
954 (defun rationalize (x)
955   #!+sb-doc
956   "Converts any REAL to a RATIONAL. Floats are converted to a simple rational
957   representation exploiting the assumption that floats are only accurate to
958   their precision. RATIONALIZE (and also RATIONAL) preserve the invariant:
959       (= x (float (rationalize x) x))"
960   (number-dispatch ((x real))
961     (((foreach single-float double-float #!+long-float long-float))
962      ;; Thanks to Kim Fateman, who stole this function rationalize-float from
963      ;; macsyma's rational. Macsyma'a rationalize was written by the legendary
964      ;; Gosper (rwg). Guy Steele said about Gosper, "He has been called the
965      ;; only living 17th century mathematician and is also the best pdp-10
966      ;; hacker I know." So, if you can understand or debug this code you win
967      ;; big.
968      (cond ((minusp x) (- (rationalize (- x))))
969            ((zerop x) 0)
970            (t
971             (let ((eps (etypecase x
972                            (single-float single-float-epsilon)
973                            (double-float double-float-epsilon)
974                            #!+long-float
975                            (long-float long-float-epsilon)))
976                   (y ())
977                   (a ()))
978               (do ((xx x (setq y (/ (float 1.0 x) (- xx (float a x)))))
979                    (num (setq a (truncate x))
980                         (+ (* (setq a (truncate y)) num) onum))
981                    (den 1 (+ (* a den) oden))
982                    (onum 1 num)
983                    (oden 0 den))
984                   ((and (not (zerop den))
985                         (not (> (abs (/ (- x (/ (float num x)
986                                                 (float den x)))
987                                         x))
988                                 eps)))
989                    (integer-/-integer num den))
990                 (declare ((dispatch-type x) xx)))))))
991     ((rational) x)))