Reputation: 11
I'm learning how to use the antik package in Common Lisp.
I have set (setf *read-default-float-format* 'double-float)
in my .sbclrc
and I'm using emacs + sly. Is there a way to have less digits in the output of calculations while keeping the precision? I would like to have something like the output of Octave which returns exp(1.0) as 2.7183
Thank you.
Upvotes: 1
Views: 103
Reputation: 529
Building on Renzo's answer, you can probably define a method on print-object
to change the default behavior:
(defmethod print-object ((f double-float) stream)
(format stream "~,4f" f))
Read more about print-object
here: http://www.lispworks.com/documentation/HyperSpec/Body/f_pr_obj.htm
Upvotes: 1
Reputation:
Lisp implementations typically go to some lengths to be correct, and in particular they try to make it be the case that if you print something and read it back you get something which is 'the same' where that is possible. In particular Lisp people think it's nice that
(defun test-rp-consistency (&optional (proto 1.0d0))
(let ((r (random proto)))
(= (read-from-string (with-output-to-string (s)
(print r s)))
r)))
is true.
However, if you don't care about that and want output that is prettier but wrong, then you can do that too. As an example, like this:
(defvar *bad-float-print-pprint-dispatch* (copy-pprint-dispatch))
(defun print-float-badly (to f)
(if *print-readably*
;; At least make some effort to be correct
(prin1 f to)
(format to "~4,2F" f)))
(set-pprint-dispatch 'float 'print-float-badly 0 *bad-float-print-pprint-dispatch*)
(defmacro with-bad-float-printing (&body forms)
`(let ((*print-pprint-dispatch* *bad-float-print-pprint-dispatch*))
,@forms))
Obviously if simply make *print-pprint-dispatch*
be *bad-float-print-pprint-dispatch*
with setf
you will get bad float printing globally.
Upvotes: 3
Reputation: 27424
You can use format
together with the "f" (fixed format floating point) specification (manual). For instance, to limit the number of digits after the decimal point to 4:
CL-USER> (format t "~,4f" (exp 1.0))
2.7183
NIL
format
is really powerful and flexible. A very good introduction can be found in this book.
Upvotes: 1