Lossless Number Conversion

mensanator at aol.com mensanator at aol.com
Sun Aug 28 21:07:48 EDT 2005


Chris Spencer wrote:
> Is there any library for Python that implements a kind of universal
> number object. Something that, if you divide two integers, generates a
> ratio instead of a float, or if you take the square root of a negative,
> generates a complex number instead of raising an exception? Lisp has
> something like this, and it makes number crunching much more convenient.
>
> Chris

The GMPY module has unlimited precision rationals:

>>> from gmpy import *

>>> r = mpq(1,1)            # create the rational 1/1
>>> for i in range(2,50):
	r = r + mpq(1,i)    # add the rational 1/i to the running sum
	print r


3/2
11/6
25/12
137/60
49/20
363/140
761/280
7129/2520
7381/2520
83711/27720
86021/27720
1145993/360360
1171733/360360
1195757/360360
2436559/720720
42142223/12252240
14274301/4084080
275295799/77597520
55835135/15519504
18858053/5173168
19093197/5173168
444316699/118982864
1347822955/356948592
34052522467/8923714800
34395742267/8923714800
312536252003/80313433200
315404588903/80313433200
9227046511387/2329089562800
9304682830147/2329089562800
290774257297357/72201776446800
586061125622639/144403552893600

So you can keep absolute precision all the way to the end
of the calculation. And you can always convert it to a float
by dividing the numerator by the denominator:

>>> print mpf(r.numer())/mpf(r.denom())
4.47920533832942505756047179296




More information about the Python-list mailing list