Previous Page
Next Page

15.5. The gmpy Module

The gmpy module ( wraps the GMP library ( to extend and accelerate Python's abilities for multiple-precision arithmetic, or arithmetic in which the precision of the numbers involved is bounded only by the amount of memory available. Python "out of the box" supplies multiple-precision arithmetic for integers through the built-in type long, covered in Chapter 4; gmpy supplies another integer-number type, named mpz, which affords even faster operations than Python's built-in long, and other functions and methods for a vast variety of fast number-theoretical computations (Fibonacci numbers, factorials, binomial coefficients, probabilistic determination of primality, etc.) and bit-string operations. gmpy also supplies a rational-number type (named mpq), a floating-point-number type with arbitrary precision (named mpf), and fast random-number generators.

gmpy's reference documentation is part of the gmpy-sources tarball, which you can download from; on the same page, you will find precompiled, ready-to-install downloads for Windows and Mac OS X 10.4 versions of Python (2.3 and 2.4 at the time of this writing). You need to download and unpack the sources package anyway, even if you're installing a precompiled version, because the sources package is the only one that includes the documentation (which you'll find in subdirectory doc once you have unpacked the tarball). Further, in subdirectory test there are over 1,000 unit tests to verify the complete correctness of your installation (run python test/, at a command prompt in the directory into which you've unpacked the tarball, to run all tests; it will take only a few seconds) and a few timing examples to show you the performance, on your specific machine, of gmpy types compared to Python's built-in ones. For example, on my laptop, by running python test/ I see that computing the 100,000th Fibonacci number (which starts with 259741 and has a total of 20,898 digits) takes about 1.5 seconds working on Python's built-in longs, 0.5 seconds working on gmpy.mpz instances, and less than 0.01 seconds by calling the gmpy.fib predefined function.

gmpy strives to provide heuristically useful conversions from both decimal.Decimal instances and floats, using a Stern-Brocot tree to build "sensible" rationals:

>>> import gmpy
>>> print gmpy.mpq(0.1)

In this example, gmpy manages to compensate for the float's "representation error" and emit the exact fraction that you presumably meant rather than the mathematically exact one, which tends to be less useful:

>>> print gmpy.mpq(int(0.1*2**55),2**55)

Previous Page
Next Page