CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-gmpy2

Multiple-precision arithmetic library providing fast GMP, MPFR, and MPC interfaces for Python

Pending
Overview
Eval results
Files

data-types.mddocs/

Multiple-Precision Data Types

gmpy2 provides five main data types for different kinds of multiple-precision arithmetic. Each type integrates seamlessly with Python's numeric protocols while providing access to high-performance arbitrary-precision operations.

Capabilities

mpz - Multiple-Precision Integer

Immutable arbitrary-precision integers based on the GMP library. Supports all standard integer operations with unlimited precision.

class mpz:
    def __init__(self, x=0, base=10):
        """
        Create multiple-precision integer.
        
        Args:
            x: Initial value (int, str, bytes, or numeric type)
            base: Base for string conversion (2-62)
        """

    # Bit operations
    def bit_clear(self, index: int) -> 'mpz':
        """Clear bit at specified index, return new mpz."""
    
    def bit_count(self) -> int:
        """Count number of set bits (population count)."""
    
    def bit_flip(self, index: int) -> 'mpz':
        """Flip bit at specified index, return new mpz."""
    
    def bit_length(self) -> int:
        """Number of bits needed to represent the number."""
    
    def bit_scan0(self, start: int = 0) -> int:
        """Find first clear bit starting from position."""
    
    def bit_scan1(self, start: int = 0) -> int:
        """Find first set bit starting from position."""
    
    def bit_set(self, index: int) -> 'mpz':
        """Set bit at specified index, return new mpz."""
    
    def bit_test(self, index: int) -> bool:
        """Test if bit is set at specified index."""

    # Number theory methods
    def is_congruent(self, y, m) -> bool:
        """Test if self ≡ y (mod m)."""
    
    def is_divisible(self, y) -> bool:
        """Test if self is divisible by y."""
    
    def is_even(self) -> bool:
        """Test if number is even."""
    
    def is_odd(self) -> bool:
        """Test if number is odd."""
    
    def is_power(self) -> bool:
        """Test if number is a perfect power."""
    
    def is_prime(self, n: int = 25) -> bool:
        """
        Primality test using Miller-Rabin algorithm.
        
        Args:
            n: Number of test rounds (higher = more accurate)
        
        Returns:
            True if probably prime, False if composite
        """
    
    def is_probab_prime(self, n: int = 25) -> int:
        """
        Probabilistic primality test.
        
        Returns:
            0 if composite, 1 if probably prime, 2 if definitely prime
        """
    
    def is_square(self) -> bool:
        """Test if number is a perfect square."""

    # Conversion and representation
    def digits(self, base: int = 10) -> str:
        """Return string representation in specified base."""
    
    def num_digits(self, base: int = 10) -> int:
        """Count digits in specified base."""
    
    def to_bytes(self, length: int = 1, byteorder: str = 'big', signed: bool = False) -> bytes:
        """Convert to bytes representation."""
    
    @classmethod
    def from_bytes(cls, bytes_data: bytes, byteorder: str = 'big', signed: bool = False) -> 'mpz':
        """Create mpz from bytes representation."""

    # Rational interface compatibility
    def as_integer_ratio(self) -> tuple:
        """Return (numerator, denominator) tuple - (self, 1)."""
    
    @property
    def numerator(self) -> 'mpz':
        """Numerator (returns self)."""
    
    @property
    def denominator(self) -> 'mpz':
        """Denominator (returns 1)."""

    # Complex interface compatibility  
    @property
    def real(self) -> 'mpz':
        """Real part (returns self)."""
    
    @property
    def imag(self) -> 'mpz':
        """Imaginary part (returns 0)."""
    
    def conjugate(self) -> 'mpz':
        """Complex conjugate (returns self)."""

    # Standard numeric methods
    def __ceil__(self) -> 'mpz': ...
    def __floor__(self) -> 'mpz': ...
    def __round__(self, ndigits=None): ...
    def __trunc__(self) -> 'mpz': ...
    def __sizeof__(self) -> int: ...

xmpz - Mutable Multiple-Precision Integer

Mutable version of mpz that allows in-place modifications. Useful for performance-critical code where creating new objects would be expensive.

class xmpz(mpz):
    def __init__(self, x=0, base=10):
        """Create mutable multiple-precision integer."""

    # Mutable-specific methods
    def copy(self) -> 'xmpz':
        """Create mutable copy."""
    
    def make_mpz(self) -> mpz:
        """Convert to immutable mpz."""

    # Bit iteration
    def iter_bits(self, start: int = 0, stop: int = -1):
        """Iterator over bit positions that are set."""
    
    def iter_clear(self, start: int = 0, stop: int = -1):
        """Iterator over bit positions that are clear."""
    
    def iter_set(self, start: int = 0, stop: int = -1):
        """Iterator over bit positions that are set."""

    # Low-level limb access
    def num_limbs(self) -> int:
        """Number of limbs used internally."""
    
    def limbs_read(self):
        """Read-only access to internal limbs."""
    
    def limbs_write(self, n: int):
        """Writable access to n limbs."""
    
    def limbs_modify(self, n: int):
        """Modify n limbs."""
    
    def limbs_finish(self, n: int):
        """Finish limb modification."""

mpq - Multiple-Precision Rational

Rational numbers with arbitrary-precision numerator and denominator. Automatically reduces fractions to lowest terms.

class mpq:
    def __init__(self, x=0, y=1):
        """
        Create multiple-precision rational number.
        
        Args:
            x: Numerator (or single value to convert)
            y: Denominator (ignored if x is already rational-like)
        """

    # Properties
    @property
    def numerator(self) -> mpz:
        """Numerator as mpz."""
    
    @property
    def denominator(self) -> mpz:
        """Denominator as mpz."""
    
    @property
    def real(self) -> 'mpq':
        """Real part (returns self)."""
    
    @property
    def imag(self) -> mpz:
        """Imaginary part (returns 0)."""

    # Conversion methods
    def digits(self, base: int = 10, prec: int = 0) -> str:
        """String representation in specified base."""
    
    def as_integer_ratio(self) -> tuple:
        """Return (numerator, denominator) as tuple of ints."""
    
    @classmethod
    def from_float(cls, x: float) -> 'mpq':
        """Create rational from float value."""
    
    @classmethod  
    def from_decimal(cls, x) -> 'mpq':
        """Create rational from decimal.Decimal value."""

    # Numeric methods
    def __ceil__(self): ...
    def __floor__(self): ...
    def __round__(self, ndigits=None): ...
    def __trunc__(self): ...
    def __sizeof__(self) -> int: ...
    def conjugate(self) -> 'mpq': ...

mpfr - Multiple-Precision Floating Point

High-precision floating-point numbers based on the MPFR library with configurable precision and correct rounding.

class mpfr:
    def __init__(self, x=0.0, precision=None):
        """
        Create multiple-precision floating-point number.
        
        Args:
            x: Initial value
            precision: Precision in bits (None = use context precision)
        """

    # Properties
    @property
    def precision(self) -> int:
        """Precision in bits."""
    
    @property
    def rc(self) -> int:
        """Return code from last operation."""
    
    @property
    def real(self) -> 'mpfr':
        """Real part (returns self)."""
    
    @property
    def imag(self) -> 'mpfr':
        """Imaginary part (returns mpfr(0))."""

    # Predicates
    def is_finite(self) -> bool:
        """Test if number is finite (not infinity or NaN)."""
    
    def is_infinite(self) -> bool:
        """Test if number is infinite."""
    
    def is_integer(self) -> bool:
        """Test if number represents an integer value."""
    
    def is_nan(self) -> bool:
        """Test if number is NaN (Not a Number)."""
    
    def is_regular(self) -> bool:
        """Test if number is regular (not zero, infinity, or NaN)."""
    
    def is_signed(self) -> bool:
        """Test if number is negative (including -0)."""
    
    def is_zero(self) -> bool:
        """Test if number is zero."""

    # Conversion methods
    def digits(self, base: int = 10, prec: int = 0) -> str:
        """String representation in specified base."""
    
    def as_integer_ratio(self) -> tuple:
        """Return (numerator, denominator) as tuple."""
    
    def as_mantissa_exp(self) -> tuple:
        """Return (mantissa, exponent) representation."""
    
    def as_simple_fraction(self, max_denominator=None):
        """Convert to simple fraction representation."""

    # Numeric methods
    def __ceil__(self): ...
    def __floor__(self): ...
    def __round__(self, ndigits=None): ...
    def __trunc__(self): ...
    def __sizeof__(self) -> int: ...
    def conjugate(self) -> 'mpfr': ...

mpc - Multiple-Precision Complex

Complex numbers with arbitrary-precision real and imaginary parts based on the MPC library.

class mpc:
    def __init__(self, real=0, imag=0, precision=None):
        """
        Create multiple-precision complex number.
        
        Args:
            real: Real part
            imag: Imaginary part
            precision: Precision in bits (tuple for separate real/imag precision)
        """

    # Properties
    @property
    def precision(self) -> tuple:
        """Precision in bits as (real_precision, imag_precision)."""
    
    @property
    def rc(self) -> int:
        """Return code from last operation."""
    
    @property
    def real(self) -> mpfr:
        """Real part as mpfr."""
    
    @property
    def imag(self) -> mpfr:
        """Imaginary part as mpfr."""

    # Predicates
    def is_finite(self) -> bool:
        """Test if both real and imaginary parts are finite."""
    
    def is_infinite(self) -> bool:
        """Test if either part is infinite."""
    
    def is_nan(self) -> bool:
        """Test if either part is NaN."""
    
    def is_zero(self) -> bool:
        """Test if number is zero."""

    # Complex operations
    def conjugate(self) -> 'mpc':
        """Return complex conjugate."""

    # Conversion methods
    def digits(self, base: int = 10, prec: int = 0) -> str:
        """String representation in specified base."""
    
    def __complex__(self) -> complex:
        """Convert to Python complex (may lose precision)."""

    # Numeric methods
    def __sizeof__(self) -> int: ...

Usage Examples

Basic Operations

import gmpy2

# Integer arithmetic
a = gmpy2.mpz("12345678901234567890")
b = gmpy2.mpz("98765432109876543210")
print(a + b)  # Arbitrary precision addition

# Rational arithmetic
x = gmpy2.mpq(22, 7)  # 22/7 approximation of pi
y = gmpy2.mpq(355, 113)  # Better approximation
print(x * y)  # Exact rational multiplication

# High-precision floating-point
with gmpy2.local_context(precision=100):
    z = gmpy2.mpfr("1.23456789012345678901234567890")
    print(gmpy2.sqrt(z))  # 100-bit precision square root

# Complex numbers
c = gmpy2.mpc("3.14159+2.71828j")
print(c.conjugate())  # Complex conjugate

Type Conversion

# Convert between types
integer = gmpy2.mpz(42)
rational = gmpy2.mpq(integer)  # 42/1
real = gmpy2.mpfr(rational)    # 42.0
complex_num = gmpy2.mpc(real)  # 42.0+0.0j

# From Python types
from fractions import Fraction
from decimal import Decimal

rat_from_frac = gmpy2.mpq(Fraction(22, 7))
rat_from_dec = gmpy2.mpq.from_decimal(Decimal("3.14159"))

Install with Tessl CLI

npx tessl i tessl/pypi-gmpy2

docs

arithmetic.md

bit-operations.md

context.md

data-types.md

index.md

math-functions.md

number-theory.md

random.md

utilities.md

tile.json