views:

44

answers:

3

I'm just starting to learn Lisp and was wondering how to display a rational as a decimal number with lots of digits.

If I use (float x), where x is a rational then it displays about 8 digits or so. But I want to display hundreds of digits.

+2  A: 

You will have to implement an algorithm to basically do the long division and calculate the digits yourself. There is no native datatype capable of holding hundreds of decimal digits.

jdmichal
+1  A: 

You can use CLISP, an implementation of Common Lisp. As an extension it provides floats with settable precision. See: http://clisp.cons.org/beta/impnotes/num-concepts.html#lfd

There are also systems like Maxima and Axiom that run on top of Common Lisp. These also can compute with high precision reals.

The Common Lisp standard though doesn't provide that.

Rainer Joswig
Another popular implementation: Dave Gillespie's Calc implements arbitrary-precision floating-point in Elisp (which itself doesn't even have bigints!).
Ken
+1  A: 

There may be implementations on which (format nil "~,100F" x) does what you want. But on most this first converts to a float, then computes digits, which loses precision.

It's not too hard to program your own. The idea is to compute the parts before and after the decimal point as integers separately. Here's my proposal:

(defun number->string-with-fixed-decimal-places (x width &optional stream)
  "Print an approximation of <x> with <width> digits after the decimal point."
  (multiple-value-bind (int dec) (truncate x)
    (let ((dec-shifted (truncate (* (abs dec) (expt 10 width)))))
      (format stream "~d.~v,vd" int width #\0 dec-shifted))))
Gilles