[Edu-sig] Re: rationals

Kirby Urner urnerk@qwest.net
Thu, 10 Oct 2002 14:38:25 -0700


>
>I have no implementation. :-)

You mean there's more to it than just imagining what goes
on at the command line?  :-D

>But it would look like this:
>
>   >>> a = 3/2r
>   >>> b = 1/2r
>   >>> a * b
>   (3/2r)
>   >>> float(a*b)
>   0.75
>   >>> a + 2
>   (5/2r)
>   >>> a / 2
>   3/4r
>   >>>

OK, this is clear.  Personally I like 3/2r better than 3r/2.
It's as if the r keeps the / from operating -- as long as we're
in lowest terms, e.g. I assume you'd go:

    >>> 4/8r
(1/2r)

The only thing that nags is using two symbols instead of one to
signify a type.  Complex (1j1) and float (1e1) get away with one
symbol, which is why 3r2 was somewhat appealing (but the r tends
to get lost).

>(I'm not sure about the parens, but complex uses them in a similar
>situation.)
>
> > Note:  I'm deviating from the policy that rat / int --> float
> > in the last line.  Not sure if this is a good idea.  Maybe:
> >
> >     int   / int   --> float     (float//float --> int)
> >     float / int   --> float     (int//int     --> int)
> >     rat   / int   --> rat   (?) (rat//rat     --> int)
> >     rat   / float --> float
> >     rat   / rat   --> rat
>
>Exactly.  int/rat should also be a rat.

Yes, in retrospect this is clear to me.


> > In other words, maybe it makes sense for / to coerce an int or
> > a long into a rat if the other arg is a rat.  This wouldn't
> > break code, as rat is a new type that couldn't get created by
> > old pre-rat code.
>
>Right.
>
> > Coercion:
> >
> > rat(3.1)    --> 31/10r   (?)
>
>I don't like this, but maybe it's okay.  It's up to the rat()
>constructor though, the float needn't know anything about this.

In J, there's number-naming using p and x where 1p2 means
1*math.pi**2 (translating to Python) and 1x3 means 1*math.e**3.
So 1p1 is just math.pi.  x: is the operator for converting to
rational (like rat(n)), and you get the following:

    x: 1p1     NB.  = rat(math.pi)
1285290289249r409120605684

    x: 1x1     NB.  = rat(math.e)
6157974361033r2265392166685

I find that interesting, even if Python chooses not to go there.

> > rat(2)      --> 2r
> > float(2/3r) --> 0.66666666666666663
>
>Right.
>
> > rat() or rational()  ?
>
>I think rat() is good -- after all I shortened 'dictionary' to 'dict'...

rat() sounds good.  I suppose fract() would be another option,
but of course math purists (and I suppose computer scientists)
prefer "rational numbers" to "fractions" as the name of the
number type.

Kirby