gmpy2: GMP/MPFR/MPC for Python

2.3.0 · active · verified Mon Apr 13

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.

Warnings

Install

Imports

Quickstart

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.

import gmpy2
from gmpy2 import mpz, mpfr, get_context

# Arbitrary-precision integer arithmetic
a = mpz(12345678901234567890 ** 2)
b = mpz(5)
print(f"mpz square: {a}")
print(f"mpz division: {a / b}")

# Arbitrary-precision floating-point real arithmetic
# Use strings for exact representation to avoid Python float precision issues
pi_approx = mpfr('3.14159265358979323846264338327950288')
print(f"Default precision pi: {pi_approx}")

# Manage precision using a context
current_context = get_context()
original_precision = current_context.precision

with gmpy2.localcontext() as ctx:
    ctx.precision = 100 # Set precision to 100 bits
    pi_high_prec = gmpy2.const_pi()
    print(f"High precision pi (100 bits): {pi_high_prec}")

print(f"Original precision after context block: {current_context.precision == original_precision}")

# Example with rational numbers
r = gmpy2.mpq(1, 3) + gmpy2.mpq(1, 4)
print(f"mpq sum: {r}")

view raw JSON →