# Rationals?

Josiah Carlson jcarlson at uci.edu
Thu Nov 18 17:59:36 CET 2004

```bokr at oz.net (Bengt Richter) wrote:
>
> On Wed, 17 Nov 2004 19:47:27 -0800, Josiah Carlson <jcarlson at uci.edu> wrote:
>
> >
> >Mike Meyer <mwm at mired.org> wrote:
> >>
> >> With the decimals and the unification of int and long coming, it's natural
> >> (for me, anyway) to wonder how much interest there is in a rational type.
> >> There are two PEPs (239 and 240), and the Guido rejects them as no one
> >> seems interested in doing the work, but points out that the python
> >> distribution comes with examples/Demo/classes/Rat.py.
> >>
> >> I propose - in the spirit of "batteries included" - that Rat.py be
> >> cleaned up some (mostly to take advantage of the union of ints and
> >> longs) and moved into the standard library.
> >>
> >> Any good reasons not to do this?
> >
> >Update the PEP, do the work, and offer a good rational number object (if
> >you are interested in doing such). I have personally written at least
> >two different rational classes, and I am aware of at least 3 others
> >(though I can't remember their names).
> >
> >If it is implemented in Python; stay away from the binary GCD algorithm,
> >Euclid's is faster.
> >
> I just looked at Rat.py in the demos, and I am wondering why floating point
> is at all included. IMO rationals should be exact, and unless you define
> what exact value you would like to have a floating point value represent (e.g.,
> all available bits, or some rounding specification) you don't have a way
> to make an exact rational. With longs there is no legal floating point double
> number whose value can't be represented exactly as a rational, so there's no
> problem except deciding. Likewise any floating point string literal can be
> converted exactly, e.g., '123.4e-5' => Rat(1234, 1000000) etc., which I think
> can be handy. BTW, IIRC complex is implemented strictly with floating point pairs,
> so that doesn't seem satisfactory, unless a new complex class is implemented using
> rational pairs. Otherwise I'd say leave complex out.
>
> Obviously fractional powers can produce non-rational results, so that poses
> a design problem if you want to handle them at all.
>
> Anyway, am I the only one who thinks that rational should be exact?

I'm a big fan of being exact whenever possible (hence the symbolic
maximum and minimum values PEP...which strangely enough, a friend that I
introduced to Python commented out of the blue that a symbolic infinity
/should/ be in Python, but I digress).  Every rational class I've
written used longs, and I am of the opinion that any reasonable rational
class /would/ use longs.

The moment one cannot help but return a float, return a float (like
sqrt(1/2)).

It does look like gmpy does the right thing in most cases, though I am
uncertain as to its suitability for Python stdlib inclusion.

- Josiah

```