[Edu-sig] Re: rationals

Kirby Urner urnerk@qwest.net
Sat, 12 Oct 2002 07:54:20 -0700


At 06:24 AM 10/12/2002 -0400, Lloyd Hugh Allen wrote:

>re: int/int --> float
>Wha? But the definition of rational is the set of numbers that can be
>represented as int/int! I understand the speediness argument, but
>please, let us not go float unless we coerce there!

An argument for int/int --> float is that this keeps preserves
closure between existing Python types and doesn't stick a big
"under construction sign" in the language for many versions to
come.  Then rationals can be added without disruption, as it'd
take new syntax (e.g. 1r/3) to invoke them, leaving older code
to run as it always has.

Given that you can go either way with int/int, I think the above
argument maybe tilts the balance in favor of int/int --> float.

Kirby

PS:

The idea of storing prime factors internally is not practical, as
nobody knows how to get the prime factors of really big integers
quickly, whereas rational arithmetic (including reducing to lowest
terms), *is* possible with these same big integers.  Requiring an
internal dict of primes would put a ceiling on rationals that
doesn't really need to be there.

The beauty of Euclid's Algorithm is it finds the gcd *without*
needing a prime factorization -- which is why it should be taught
earlier, so kids don't get the impression that those "factor trees"
are necessary when finding the gcd of two composites.

NOTE:

Althought it's true the pure Scheme supports int/int -> rational,
PLT Scheme goes with int/int -> float in many of its teaching
modes (this is a language where there *is* one of those
"environment switches" such as some have proposed for Python).

Examples:

Welcome to DrScheme, version 201.
Language: Advanced Student.
 > (/ 3 4)
0.75

Welcome to DrScheme, version 201.
Language: Textual (MzScheme, includes R5RS).
 > (/ 3 4)
3/4

Also, in J (evolved from APL), int/int --> float is the norm:

    3 % 4  NB.  % is the div operator
0.75

but make either argument rational, leaving the other int, and you
get a rational result:

   3x % 2
3r2
    3 % 2x
3r2

This latter mode could be true for Python too.

   >>> 3 / 4
0.75
   >>> 3r / 4
3/4r

The alternative you propose would look like this (I presume):

   >>> 3 / 4
3/4r
   >>> 3. / 4
0.75
   >>> 3 / 4.
0.75

Basically, it boils down to whether we have to use a . (dot) or an r
to coerce a float or rational result respectively.

Kirby