jiggpig
jiggpig

Reputation: 53

How to display rationals as long lists of digits in Lisp?

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.

Upvotes: 5

Views: 340

Answers (3)

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))))

Upvotes: 1

Rainer Joswig
Rainer Joswig

Reputation: 139321

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.

Upvotes: 2

jdmichal
jdmichal

Reputation: 11162

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.

Upvotes: 2

Related Questions