[plt-scheme] fractions and decimals

From: Neil W. Van Dyke (neil at neilvandyke.org)
Date: Sun Jan 19 17:13:17 EST 2003

> I'm playing with the new "test suite" feature, and was surprised to
> discover that (cube 1/2) is NOT 0.125 (although it DOES match 1/8).
> On further investigation, I found that (equal? 0.125 1/8) returns true
> in Beginner mode, but #f in R5RS and textual mzscheme.  Whazzap?

Scheme has a notion of "exactness" of numbers:

    http://download.plt-scheme.org/doc/r5rs/r5rs-Z-H-9.html#%_sec_6.2.2

If I understand correctly... the decimal-point literal "0.125" is
assumed "inexact" by default (I think for historical/performance
reasons, so that an implementation can use inexact native floating-point
numbers and operations unless the programmer directs otherwise).  The
ratio literal "1/8" is assumed "exact":

    (exact? 0.125) => #f
    (exact? 1/8)   => #t

You can use the "#e" prefix for expressing exact constants as
decimal-point literals, and you can use the "inexact->exact" procedure
to create an exact value from an inexact one:

    (equal?                   0.125  1/8) => #f
    (equal?                 #e0.125  1/8) => #t
    (equal? (inexact->exact   0.125) 1/8) => #t

If your computations don't require exactness, you can use "#e" and
"inexact->exact" with impunity.  You may still have difficulty testing
the equality of two rational numbers, due to floating-point lossiness.
(I defer to the mathematician on any philosophical implications.)

-- 
                                             http://www.neilvandyke.org/


Posted on the users mailing list.