Page 1 of 1

how to convert a float into a ratio?

Posted: Fri Jul 25, 2014 1:54 am
by gigg
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

Code: Select all

(* 1.95 3)
result: 5.8500004

But I need 5.85 or 117/20.

How can I do this?

Thank you.

Re: how to convert a float into a ratio?

Posted: Fri Jul 25, 2014 8:52 pm
by logxor
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:

Code: Select all

? (* 1.95d0 3)
5.85d0
? (rationalize *)
117/20

Re: how to convert a float into a ratio?

Posted: Sat Jul 26, 2014 12:16 am
by gigg
That was helpful. Many thanks.