Rationals and Linear Programming in Python

Alex Martelli aleax at aleax.it
Sun May 12 14:36:42 EDT 2002


Paul Rubin wrote:

> gmpy supports rationals.  Just say q = gmpy.mpq(1) to initialize q to 1/1.
> Any arithmetic you do on it after that (except with floating point
> operands) will give rational results.

Actually, the "except floating point operands" is not necessary in
recent-ish gmpy's:

>>> import gmpy
>>> print gmpy.version()
0.9.0c
>>> print gmpy.mpq(1)+1/3.
4/3

I.e., float is promoted to mpq by coercion (building an mpq from a float
uses a heuristically-reasonable approximation, of course, or else 1/3.
would not translate to mpq(1, 3) but to some complicated fraction;-).

You need to explicitly convert with float() if you want float to be
used:

>>> print float(gmpy.mpq(1)+1/3.)
1.33333333333
>>>


Alex




More information about the Python-list mailing list