qd-io.lisp 15.6 KB
Newer Older
Raymond Toy's avatar
Raymond Toy committed
1
2
;;;; -*- Mode: lisp -*-
;;;;
3
;;;; Copyright (c) 2007, 2008, 2011 Raymond Toy
Raymond Toy's avatar
Raymond Toy committed
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
;;;;
;;;; Permission is hereby granted, free of charge, to any person
;;;; obtaining a copy of this software and associated documentation
;;;; files (the "Software"), to deal in the Software without
;;;; restriction, including without limitation the rights to use,
;;;; copy, modify, merge, publish, distribute, sublicense, and/or sell
;;;; copies of the Software, and to permit persons to whom the
;;;; Software is furnished to do so, subject to the following
;;;; conditions:
;;;;
;;;; The above copyright notice and this permission notice shall be
;;;; included in all copies or substantial portions of the Software.
;;;;
;;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
;;;; OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
;;;; OTHER DEALINGS IN THE SOFTWARE.

26
(in-package #:octi)
27

28
29
30
31
32
;; Smallest exponent for a double-float.
(eval-when (:compile-toplevel :load-toplevel :execute)
(defconstant +double-float-min-e+
  -1073)

Raymond Toy's avatar
Raymond Toy committed
33
(defparameter +digits+
34
35
36
  "0123456789")
) ; eval-when

37
38
39
40
41
42
43
44
45
46
47
(defun qd-to-digits (v &optional position relativep)
  ;; V is the number to be printed.  If RELATIVEP is NIL, POSITION is
  ;; the number of digits to the left of the decimal point where we
  ;; want to stop printing.  If RELATIVEP is non-NIL, POSITION is the
  ;; total number of digits we want printed.
  ;;
  ;; Two values are returned: k, and the digit string, without a
  ;; decimal point.  k is the index into the string, before which the
  ;; decimal point would go.
  (let ((print-base 10)			; B
	(float-radix 2)			; b
48
49
	(float-digits (cl:* 4 53)) ; p
	(min-e +double-float-min-e+))
50
51
52
53
54
55
56
57
58
59
60
    (multiple-value-bind (f e)
	(integer-decode-qd v)
      (let ( ;; FIXME: these even tests assume normal IEEE rounding
	    ;; mode.  I wonder if we should cater for non-normal?
	    (high-ok (evenp f))
	    (low-ok (evenp f))
	    (result (make-array 50 :element-type 'base-char
				:fill-pointer 0 :adjustable t)))
	(labels ((scale (r s m+ m-)
		   ;; Keep increasing k until it's big enough
		   (do ((k 0 (1+ k))
61
62
			(s s (cl:* s print-base)))
		       ((not (let ((test (cl:+ r m+)))
63
64
65
66
			       (or (> test s)
				   (and high-ok (= test s)))))
			;; k is too big.  Decrease until
			(do ((k k (1- k))
67
68
69
70
			     (r r (cl:* r print-base))
			     (m+ m+ (cl:* m+ print-base))
			     (m- m- (cl:* m- print-base)))
			    ((not (let ((test (cl:* (cl:+ r m+) print-base)))
71
72
73
74
75
76
				    (or (< test s)
					(and (not high-ok) (= test s)))))
			     ;; k is correct.  Generate the digits.
			     (values k (generate r s m+ m-)))))))
		 (generate (r s m+ m-)
		   (multiple-value-bind (d r)
77
78
79
		       (truncate (cl:* r print-base) s)
		     (let ((m+ (cl:* m+ print-base))
			   (m- (cl:* m- print-base)))
80
		       (let ((tc1 (or (< r m-) (and low-ok (= r m-))))
81
			     (tc2 (let ((test (cl:+ r m+)))
82
83
84
85
				    (or (> test s)
					(and high-ok (= test s))))))
			 (cond
			   ((and (not tc1) (not tc2))
86
			    (vector-push-extend (char +digits+ d) result)
87
88
89
90
91
92
			    ;; FIXME sucky tail recursion.  This whole
			    ;; kaboodle should be DO*/LOOPified.
			    (generate r s m+ m-))
			   ;; pedantically keeping all the conditions
			   ;; in so that we can move them around.
			   ((and (not tc1) tc2)
93
			    (vector-push-extend (char +digits+ (1+ d)) result)
94
95
			    result)
			   ((and tc1 (not tc2))
96
			    (vector-push-extend (char +digits+ d) result)
97
98
			    result)
			   ((and tc1 tc2)
99
100
			    (vector-push-extend (char +digits+
						      (if (< (cl:* r 2) s) d (1+ d)))
101
102
103
104
105
						result)
			    result)))))))
	  (let (r s m+ m-)
	    (if (>= e 0)
		(let* ((be (expt float-radix e))
106
		       (be1 (cl:* be float-radix)))
107
108
		  (if (/= f (expt float-radix (1-
					       float-digits)))
109
		      (setf r (cl:* f be 2)
110
111
112
			    s 2
			    m+ be
			    m- be)
113
114
		      (setf r (cl:* f be1 2)
			    s (cl:* float-radix 2)
115
116
117
118
119
			    m+ be1
			    m- be)))
		(if (or (= e min-e) 
			(/= f (expt float-radix (1-
						 float-digits))))
120
121
		    (setf r (cl:* f 2)
			  s (cl:* (expt float-radix (cl:- e)) 2)
122
123
			  m+ 1
			  m- 1)
124
125
		    (setf r (cl:* f float-radix 2)
			  s (cl:* (expt float-radix (cl:- 1 e)) 2)
126
127
128
129
130
131
132
			  m+ float-radix
			  m- 1)))
	    (when position
	      (when relativep
		;;(aver (> position 0))
		(do ((k 0 (1+ k))
		     ;; running out of letters here
133
134
		     (l 1 (cl:* l print-base)))
		    ((>= (cl:* s l) (cl:+ r m+))
135
		     ;; k is now \hat{k}
136
		     (if (< (cl:+ r (cl:* s (cl:/ (expt print-base (cl:- k
137
							     position)) 2)))
138
139
140
141
			    (cl:* s (expt print-base k)))
			 (setf position (cl:- k position))
			 (setf position (cl:- k position 1))))))
	      (let ((low (max m- (cl:/ (cl:* s (expt print-base
142
					       position)) 2)))
143
		    (high (max m+ (cl:/ (cl:* s (expt print-base
144
145
146
147
148
149
150
151
152
153
						position)) 2))))
		(when (<= m- low)
		  (setf m- low)
		  (setf low-ok t))
		(when (<= m+ high)
		  (setf m+ high)
		  (setf high-ok t))))
	    (scale r s m+ m-)))))))

(defun qd-print-exponent (x exp stream)
Raymond Toy's avatar
Raymond Toy committed
154
  (declare (ignore x))
155
156
157
  (let ((*print-radix* nil))
    (format stream "q~D" exp)))

toy's avatar
toy committed
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
(defun qd-to-string (x &optional width fdigits scale fmin)
  (setf x (abs-qd x))
  (cond ((zerop-qd x)
	 ;;zero is a special case which float-string cannot handle
	 (if fdigits
	     (let ((s (make-string (1+ fdigits) :initial-element #\0)))
	       (setf (schar s 0) #\.)
	       (values s (length s) t (zerop fdigits) 0))
	     (values "." 1 t t 0)))
	(t
	 (multiple-value-bind (e string)
	     (if fdigits
		 (qd-to-digits x (min (- (+ fdigits (or scale 0)))
					  (- (or fmin 0))))
		 (if (and width (> width 1))
		     (let ((w (multiple-value-list
			       (qd-to-digits x
					     (max 0
						  (+ (1- width)
						     (if (and scale (minusp scale))
							 scale 0)))
					     t)))
			   (f (multiple-value-list
			       (qd-to-digits x (- (+ (or fmin 0)
						     (if scale scale 0)))))))
		       (cond
			 ((>= (length (cadr w)) (length (cadr f)))
			  (values-list w))
			 (t (values-list f))))
		     (qd-to-digits x)))
	   (let ((e (+ e (or scale 0)))
		 (stream (make-string-output-stream)))
	     (if (plusp e)
		 (progn
		   (write-string string stream :end (min (length string)
							 e))
		   (dotimes (i (- e (length string)))
		     (write-char #\0 stream))
		   (write-char #\. stream)
		   (write-string string stream :start (min (length string)
							   e))
		   (when fdigits
		     (dotimes (i (- fdigits
				    (- (length string) 
				       (min (length string) e))))
		       (write-char #\0 stream))))
		 (progn
		   (write-string "." stream)
		   (dotimes (i (- e))
		     (write-char #\0 stream))
		   ;; If we're out of room (because fdigits is too
		   ;; small), don't print out our string.  This fixes
		   ;; things like (format nil "~,2f" 0.001).  We should
		   ;; print ".00", not ".001".
		   (when (or (null fdigits)
			     (plusp (+ e fdigits)))
		     (write-string string stream))
		   (when fdigits
		     (dotimes (i (+ fdigits e (- (length string))))
		       (write-char #\0 stream)))))
	     (let ((string (get-output-stream-string stream)))
	       (values string (length string)
		       (char= (char string 0) #\.)
		       (char= (char string (1- (length string))) #\.)
		       (position #\. string))))))))


225
(defun qd-output-aux (x &optional (stream *standard-output*))
226
  (if (zerop-qd x)
227
228
229
230
      (write-string (if (minusp (float-sign (qd-0 x)))
			"-0.0q0"
			"0.0q0")
		    stream)
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
      (multiple-value-bind (e string)
	  (qd-to-digits x)
	(when (minusp (float-sign (qd-0 x)))
	  (write-char #\- stream))
	(cond ((< -3 e 8)
	       ;; Free format
	       (cond ((plusp e)
		      (write-string string stream :end (min (length string) e))
		      (dotimes (i (cl:- e (length string)))
			(write-char #\0 stream))
		      (write-char #\. stream)
		      (write-string string stream :start (min (length string) e))
		      (when (<= (length string) e)
			(write-char #\0 stream))
		      (qd-print-exponent x 0 stream))
		     (t
		      (write-string "0." stream)
		      (dotimes (i (cl:- e))
			(write-char #\0 stream))
		      (write-string string stream)
		      (qd-print-exponent x 0 stream))))
	      (t
	       ;; Exponential format
	       (write-string string stream :end 1)
	       (write-char #\. stream)
	       (write-string string stream :start 1)
	       ;; CLHS 22.1.3.1.3 says at least one digit must be printed
	       ;; after the decimal point.
	       (when (= (length string) 1)
		 (write-char #\0 stream))
	       (qd-print-exponent x (1- e) stream))))))
262
263

;; Function that can be used with FORMAT ~/
264
#-cmu
265
266
267
(defun qd-format (stream arg colon-p at-sign-p &rest par)
  ;; We should do something with colon-p and at-sign-p
  (declare (ignore colon-p at-sign-p par))
268
  (write-string "#q" stream)
269
270
  (qd-output-aux arg stream))

271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
#+cmu
(defun qd-output-infinity (x stream)
  (cond (*read-eval*
	 (write-string "#." stream))
	(*print-readably*
	 (error 'print-not-readable :object x))
	(t
	 (write-string "#<" stream)))
  (write-string "QD:+QUAD-DOUBLE-FLOAT" stream)
  (write-string (if (plusp (qd-0 x))
		    "-POSITIVE-"
		    "-NEGATIVE-")
		stream)
  (write-string "INFINITY+" stream)
  (unless *read-eval*
    (write-string ">" stream)))

288
289
290
291
292
293
294
#+cmu
(defun qd-output-nan (x stream)
  (print-unreadable-object (x stream)
    (write-string "QUAD-DOUBLE-FLOAT" stream)
    (write-string (if (float-trapping-nan-p (qd-0 x)) " Trapping" " Quiet") stream)
    (write-string " NaN" stream)))

295
296
297
298
299
300
#+cmu
(defun qd-format (stream arg colon-p at-sign-p &rest par)
  (declare (type %quad-double arg)
	   (stream stream))
  ;; We should do something with colon-p and at-sign-p
  (declare (ignore colon-p at-sign-p par))
301
  (cond ((float-infinity-p (qd-0 arg))
302
	 (qd-output-infinity arg stream))
303
304
	((ext:float-nan-p (qd-0 arg))
	 (qd-output-nan arg stream))
305
	(t
306
	 (write-string "#q" stream)
307
308
	 (qd-output-aux arg stream))))

309
310
;; This version has problems with roundoff.
#+nil
311
312
313
314
(defun make-float (sign int-part frac-part scale exp)
  (declare (type (member -1 1) sign)
	   (type unsigned-byte int-part frac-part)
	   (fixnum scale exp))
315
  ;;#+(or)
316
317
318
319
320
321
322
323
324
  (progn
    (format t "sign      = ~A~%" sign)
    (format t "int-part  = ~A~%" int-part)
    (format t "frac-part = ~A~%" frac-part)
    (format t "scale     = ~A~%" scale)
    (format t "exp       = ~A~%" exp))
  (let ((int (cl:+ (cl:* int-part (expt 10 scale))
		   frac-part))
	(power (cl:- exp scale)))
325
    ;;#+(or)
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
    (format t "~A * ~A * 10^(~A)~%" sign int power)
    (let* ((len (integer-length int)))
      #+(or)
      (format t "len = ~A~%" len)
      (cond ((<= len 53)
	     (let ((xx (make-qd-d (float int 1d0)))
		   (yy (npow (make-qd-d 10d0)
			     power)))
	       #+(or)
	       (progn
		 (format t "int = ~A~%" int)
		 (format t "fl  = ~A~%" (float int 1w0))
		 (format t "s   = ~A~%" sign)
		 (format t "sint = ~A~%" (cl:* sign  (float int 1w0)))
		 (format t "~A~%" xx)
		 (format t "npow = ~A~%" yy))
	       (if (minusp sign)
		   (neg-qd (mul-qd xx yy))
		   (mul-qd xx yy))))
	    (t
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
	     (let* 
		 ((q0 (ldb (byte 53 (cl:- len 53)) int))
		  (q1 (ldb (byte 53 (cl:- len (* 2 53))) int))
		  (q2 (ldb (byte 53 (cl:- len (* 3 53))) int))
		  (q3 (ldb (byte 53 (cl:- len (* 4 53))) int))
		  (q4 (ldb (byte 53 (cl:- len (* 5 53))) int))
		  (xx (multiple-value-call #'%make-qd-d
			(renorm-5 (scale-float (float q0 1d0)
					       (cl:- len 53))
				  (scale-float (float q1 1d0)
					       (cl:- len (* 2 53)))
				  (scale-float (float q2 1d0)
					       (cl:- len (* 3 53)))
				  (scale-float (float q3 1d0)
					       (cl:- len (* 4 53)))
				  (scale-float (float q4 1d0)
					       (cl:- len (* 5 53))))))
		  (yy (npow (make-qd-d 10d0)
			    power)))
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
	       #+(or)
	       (progn
		 (format t "xx = ~A~%" xx)
		 #+(or)
		 (format t "   = ~/qd::qd-format/~%" xx)
		 (format t "yy = ~A~%" yy)
		 #+(or)
		 (format t "   = ~/qd::qd-format/~%" yy)
		 (format t "q0 = ~X (~A)~%" q0
			 (scale-float (float q0 1d0)
				      (cl:- len 53)))
		 (format t "q1 = ~X (~A)~%" q1
			 (scale-float (float q1 1d0)
				      (cl:- len (* 2 53))))
		 #+(or)
380
		 (format t "~/octi::qd-format/~%" (mul-qd xx yy)))
381
382
383
384
	       (if (minusp sign)
		   (neg-qd (mul-qd xx yy))
		   (mul-qd xx yy))))))))

Raymond Toy's avatar
Raymond Toy committed
385
386
387
388
;; This is a slightly modified version of Richard Fateman's code to
;; convert bignums to qd.  This supports converting rationals to qd
;; too.
(defun rational-to-qd (rat)
Raymond Toy's avatar
Raymond Toy committed
389
  "Convert a rational number RAT to a %QUAD-DOUBLE number"
Raymond Toy's avatar
Raymond Toy committed
390
391
392
393
394
395
396
397
398
399
400
401
  (declare (rational rat))
  (let* ((p (coerce rat 'double-float))
	 (ans (make-qd-d p))
	 (remainder rat))
    (declare (double-float p)
	     (rational remainder)
	     (type %quad-double ans))
    (dotimes (k 3 ans)
      (decf remainder (rational p))
      (setf p (coerce remainder 'double-float))
      (setf ans (add-qd-d ans p)))))

402
403
404
405
(defun make-float (sign int-part frac-part scale exp)
  (declare (type (member -1 1) sign)
	   (type unsigned-byte int-part frac-part)
	   (fixnum scale exp))
406
407
408
409
410
  (let ((qd (rational-to-qd (* (+ int-part (/ frac-part (expt 10 scale)))
			       (expt 10 exp)))))
    (if (minusp sign)
	(neg-qd qd)
	qd)))
411

412
;; This seems to work, but really needs to be rewritten!
413
(defun read-qd (stream)
Raymond Toy's avatar
Raymond Toy committed
414
415
416
  "Read a %QUAD-DOUBLE number from the stream STREAM.  The format of the number
should be like a float, but with extra significant digits allowed.  An exponent
marker of Q is allowed."
417
  (labels ((read-digits (s)
418
419
420
	     ;; Read a sequence of digits and return the decimal
	     ;; value, the character that terminated the sequence, and
	     ;; how many characters were read.
421
422
423
424
425
426
427
428
429
430
	     (let ((val 0)
		   (ch nil)
		   (count 0))
	       (loop
		   (setf ch (peek-char nil s nil :eof))
		   (cond ((eq ch :eof)
			  (return))
			 ((digit-char-p ch)
			  (read-char s)
			  (incf count)
431
432
			  (setf val (cl:+ (digit-char-p ch)
				       (cl:* 10 val))))
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
			 (t
			  (return))))
	       (values ch val count)))
	   (read-sign (s)
	     (let ((maybe-sign (peek-char t s nil :eof)))
	       (cond ((eql maybe-sign #\-)
		      (read-char s)
		      -1
		      )
		     ((eql maybe-sign #\+)
		      (read-char s)
		      +1)
		     ((and (characterp maybe-sign)
			   (digit-char-p maybe-sign))
		      +1)
		     ((eql maybe-sign #\.)
		      +1)
		     (t
		      maybe-sign))))
	   (read-exp (s)
	     (let ((exp-sign (read-sign s)))
	       (when (eq :eof exp-sign)
		 (return-from read-exp 0))
	       (when (eq :eof (peek-char t s nil :eof))
		 (error "Sign of exponent, but no value"))
	       (multiple-value-bind (char expo)
		   (read-digits s)
		 (declare (ignore char))
461
		 (cl:* exp-sign expo)))))
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
    (let ((sign (read-sign stream))
	  (int-part 0)
	  (frac-part 0)
	  (exp 0)
	  (scale 0))
      (when (eq :eof (peek-char t stream nil :eof))
	(error "Sign, but no value"))
      (multiple-value-bind (char int)
	  (read-digits stream)
	(setf int-part int)
	(cond ((eql :eof char)
	       )
	      ((eql char #\.)
	       (read-char stream)
	       (multiple-value-bind (char val scale-val)
		   (read-digits stream)
		 (declare (ignore char))
		 (setf frac-part val)
		 (setf scale scale-val)
		 (let ((next (peek-char nil stream nil :eof)))
		   (when (equalp next #\q)
		     (read-char stream)
		     (let ((exp-sign (read-sign stream)))
		       (setf exp (read-exp stream))
486
		       (setf exp (cl:* exp exp-sign)))))))
487
488
489
490
491
492
493
	      ((equalp char #\q)
	       (read-char stream)
	       (setf exp (read-exp stream))
	       ))
	(make-float sign int-part frac-part scale exp)))))

(defun qd-reader (stream subchar arg)
Raymond Toy's avatar
Raymond Toy committed
494
  (declare (ignore subchar arg))
495
496
  (read-qd stream))

497
498
499
500
(defun qd-from-string (string)
  (cl::with-input-from-string (s string)
    (read-qd s)))

Raymond Toy's avatar
Raymond Toy committed
501
#+nil
502
503
(set-dispatch-macro-character #\# #\Q #'qd-reader)