gmpy2 is an optimized, C-coded Python extension module that provides an interface to the GMP (GNU Multiple Precision Arithmetic Library), MPFR (Multiple-Precision Floating-point Reliable Library), and MPC (Multiple Precision Complex Library). It enables fast arbitrary-precision integer, rational, real, and complex arithmetic in Python. The current stable version is 2.3.0, and it is actively maintained with regular updates to support newer Python versions and fix bugs.
pip install gmpy2Verified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates basic arbitrary-precision integer (mpz), real (mpfr), and rational (mpq) arithmetic. It also shows how to manage floating-point precision using `gmpy2.get_context()` and `gmpy2.localcontext()` to control precision settings. Constants should ideally be passed as strings to `mpfr` to ensure full arbitrary precision from the start, avoiding Python's native float limitations.
Upgrade Python to 3.11 or newer before updating gmpy2 past version 2.3.0.
Ensure GMP, MPFR, and MPC development libraries are installed on your system if pre-compiled wheels are not available.
Carefully manage the precision and scale of numbers. Monitor memory usage and CPU time for performance-critical sections. Consider using `xmpz` for mutable integer operations if appropriate.
For temporary or localized changes to context settings, use `with gmpy2.localcontext() as ctx:`, which creates a thread-local copy and restores the previous context upon exiting the `with` block. Alternatively, explicitly create and activate contexts with `gmpy2.set_context(new_context)` and `gmpy2.get_context().copy()`.
Replace all instances of `gmpy.mpf` with `gmpy2.mpfr`.
Install gmpy2 using pip: `pip install gmpy2`
Install the Build Tools for Visual Studio from Microsoft's website. Alternatively, download a pre-compiled wheel (.whl file) for your specific Python version and architecture from a reputable source (e.g., Gohlke's Python Extension Packages for Windows) and install it using pip: `pip install path/to/gmpy2‑X.Y.Z‑cpXX‑cpXXm‑win_amd64.whl`
Upgrade gmpy2 to a version that officially supports your specific Python interpreter version. If a newer version is not available on PyPI, consider using a pre-compiled wheel if one exists for your Python version, or use a compatible older Python version. `pip install --upgrade gmpy2`