This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

how to convert a float into a ratio?

3 posts · 3788 views

Hello,

I'm a Common Lisp-Newbie, sorry for my question:

When I multiply a float with an integer, I don't get the correct result:

For example
(* 1.95 3)
result: 5.8500004

But I need 5.85 or 117/20.

How can I do this?

Thank you.

Last edited by gigg on , edited 1 time in total.

Re: how to convert a float into a ratio?

That result is correct, within the constraints of single-precision floating point. Floats, in binary, have only so many bits to represent a given decimal fraction. By default, Common Lisp reads SINGLE-FLOAT format when you type floats. If you want DOUBLE-FLOAT format, then either set *READ-DEFAULT-FLOAT-FORMAT* or use an exponent marker when specifying the float, like this:
? (* 1.95d0 3)
5.85d0
? (rationalize *)
117/20

Re: how to convert a float into a ratio?

That was helpful. Many thanks.