Float to rational convert

Discussion of Common Lisp
Post Reply
GG_Chris
Posts: 2
Joined: Wed Jun 02, 2010 3:00 am

Float to rational convert

Post by GG_Chris » Wed Jun 02, 2010 3:06 am

hi everyone. i have a problem, and i cannot solve it. I'm trying to convert from a float number, to a rational one, in common lisp.
An example would be this one:
(float-to-rational 1.2)
12/10
and:
(rational-to-float 3/2)
1.5

I tried to write a function, but i still cannot do it. I want to say that i'm a little newbie in LISP programming. Can anyone help me with this? :D
Thanks a lot, i appreciate :D

ramarren
Posts: 613
Joined: Sun Jun 29, 2008 4:02 am
Location: Warsaw, Poland
Contact:

Re: Float to rational convert

Post by ramarren » Wed Jun 02, 2010 4:12 am

Common Lisp already has functions for this conversion: RATIONAL and RATIONALIZE.

GG_Chris
Posts: 2
Joined: Wed Jun 02, 2010 3:00 am

Re: Float to rational convert

Post by GG_Chris » Wed Jun 02, 2010 5:10 am

Ramarren wrote:Common Lisp already has functions for this conversion: RATIONAL and RATIONALIZE.
when i try to use the RATIONALIZE function, i receive an error:
> (rationalize -11/100)
Error: The function RATIONALIZE is not defined.
and the RATIONAL function has another output, not a good one. Example:
> (rational 1.1)
2476979795053773/2251799813685248
I want to obtain something like 11/10
I'm using XLISP - STAT 3.52.20
Is there another way to use these functions?

ramarren
Posts: 613
Joined: Sun Jun 29, 2008 4:02 am
Location: Warsaw, Poland
Contact:

Re: Float to rational convert

Post by ramarren » Wed Jun 02, 2010 5:24 am

XLISP is not standard Common Lisp. I don't think anyone on this forum uses XLISP. I would suggest you switch to an ANSI compliant Common Lisp implementation like SBCL. If XLISP is a requirement by your school or employer then you should probably direct your questions to them, or possibly search for XLISP specific forum of mailing list.

That said, the output you presented is a perfectly good one. A rational number 11/10 does not have a binary floating point representation, and can only be approximated. When it is converted back this approximation becomes apparent. RATIONALIZE in Common Lisp tries to revert that approximation, but I believe that the algorithm for that is fairly complex and requires good understanding of how floating point numbers work.

Post Reply