# A rational proposal

Mike Meyer mwm at mired.org
Sat Dec 18 19:40:04 CET 2004

```"John Roth" <newsgroups at jhrothjr.com> writes:

> "Mike Meyer" <mwm at mired.org> wrote in message
> news:864qik472n.fsf at guru.mired.org...
>> PEP: XXX
>> Title: A rational number module for Python
>> The ``Rational`` class shall define all the standard mathematical
>> operations: addition, subtraction, multiplication, division, modulo
>> and power.  It will also provide the methods:
>>
>> - max(*args): return the largest of a list of numbers and self.
>> - min(*args): return the smallest of a list of numbers and self.
>
> max() and min() are already part of the standard library.
> Providing them as instance methods is quite irregular.

They don't handle decimals or rationals. This is following the lead of
the decimal package.

>> - decimal(): return the decimal approximation to the rational in the
>>             current context.
>
> This ought to be the responsibility of the decimal() constructor.
> I can see including it here to avoid adding it to the decimal()
> constructor, but IMO it's bad design.

Good point. Currently, objects now how to convert themselves to int,
float and complex. Should Rational now how to convert itself to
Decimal (and conversely, decimal now how to convert itself to
Rational)?

>> - inv(): Return the inverse of self.
> I presume this means that if the rational is x/y, then it
> returns y/x?

Is this better wording:
- inv(): Return self to the power -1.

>> Rationals will mix with all other numeric types.  When combined with an
>> integer type, that integer will be converted to a rational before the
>> operation.  When combined with a floating type - either complex or
>> float - the rational will be converted to a floating approximation
>> before the operation, and a float or complex will be returned.  The
>> reason for this is that floating point numbers - including complex -
>> are already imprecise.  To convert them to rational would give an
>> incorrect impression that the results of the operation are
>> precise.  Decimals will be converted to rationals before the
>> operation.  [Open question: is this the right thing to do?]
>
> I'd prefer to have rationals converted to decimals before
> the operation, for the same reason that they're converted
> to floats. Decimals also have limited precision.

precision. But they represent their values exactly, whereas 1E73 isn't
a 1 followed by 73 zeros when converted to an int. On the other hand,
every decimal has a rational equivalent, but not vice versa.

Thanks,
<mike
--
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/