how to convert a float into a ratio?

Discussion of Common Lisp

how to convert a float into a ratio?

Postby gigg » Fri Jul 25, 2014 1:54 am

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.
Last edited by gigg on Sat Jul 26, 2014 12:01 am, edited 1 time in total.
gigg
 
Posts: 2
Joined: Sat Jun 21, 2014 11:42 am

Re: how to convert a float into a ratio?

Postby logxor » Fri Jul 25, 2014 8:52 pm

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
logxor
 
Posts: 16
Joined: Tue May 27, 2014 10:56 am
Location: Portland, OR

Re: how to convert a float into a ratio?

Postby gigg » Sat Jul 26, 2014 12:16 am

That was helpful. Many thanks.
gigg
 
Posts: 2
Joined: Sat Jun 21, 2014 11:42 am


Return to Common Lisp

Who is online

Users browsing this forum: No registered users and 2 guests

cron