Multiple-precision arithmetic library providing fast GMP, MPFR, and MPC interfaces for Python
—
gmpy2 provides various utility functions for version information, binary serialization, floating-point system configuration, and performance optimization. These functions support debugging, serialization, and system integration.
Functions for retrieving version information about gmpy2 and underlying libraries.
def version():
"""
Get gmpy2 version string.
Returns:
str: gmpy2 version (e.g., "2.2.1")
"""
def mp_version():
"""
Get GMP library version string.
Returns:
str: GMP version information
"""
def mpfr_version():
"""
Get MPFR library version string.
Returns:
str: MPFR version information
"""
def mpc_version():
"""
Get MPC library version string.
Returns:
str: MPC version information
"""
def mp_limbsize():
"""
Get GMP limb size in bits.
Returns:
int: Number of bits per GMP limb (typically 32 or 64)
Note:
Limb size affects performance and internal representation
"""
def license():
"""
Get license information for gmpy2.
Returns:
str: License text and information
"""Functions for converting gmpy2 objects to and from binary format for storage and transmission.
def to_binary(x):
"""
Convert gmpy2 object to binary format.
Args:
x: gmpy2 object (mpz, mpq, mpfr, mpc)
Returns:
bytes: Binary representation of the object
Note:
Binary format preserves full precision and is platform-independent
"""
def from_binary(s):
"""
Create gmpy2 object from binary format.
Args:
s: Binary data (bytes or str)
Returns:
gmpy2 object of appropriate type
Raises:
ValueError: If binary data is invalid or corrupted
"""
def pack(x, precision, emin, emax):
"""
Pack floating-point number to binary with specified format.
Args:
x: Floating-point value (mpfr)
precision: Precision in bits
emin: Minimum exponent
emax: Maximum exponent
Returns:
bytes: Packed binary representation
Note:
Useful for creating custom floating-point formats
"""
def unpack(s, precision, emin, emax):
"""
Unpack floating-point number from binary format.
Args:
s: Binary data (bytes)
precision: Precise in bits used for packing
emin: Minimum exponent used for packing
emax: Maximum exponent used for packing
Returns:
mpfr: Unpacked floating-point value
Raises:
ValueError: If binary data doesn't match specified format
"""Functions for importing from older gmpy binary formats.
def mpz_from_old_binary(s):
"""
Import mpz from old binary format.
Args:
s: Old format binary data
Returns:
mpz: Converted integer
"""
def mpq_from_old_binary(s):
"""
Import mpq from old binary format.
Args:
s: Old format binary data
Returns:
mpq: Converted rational number
"""
def mpfr_from_old_binary(s):
"""
Import mpfr from old binary format.
Args:
s: Old format binary data
Returns:
mpfr: Converted floating-point number
"""Functions for querying and configuring MPFR system limits and behavior.
def get_max_precision():
"""
Get maximum allowed precision for MPFR operations.
Returns:
int: Maximum precision in bits
Note:
System-dependent limit, typically very large
"""
def get_emax_max():
"""
Get maximum allowed exponent value.
Returns:
int: Maximum exponent for MPFR numbers
"""
def get_emin_min():
"""
Get minimum allowed exponent value.
Returns:
int: Minimum exponent for MPFR numbers
"""
def free_cache():
"""
Free internal MPFR caches to release memory.
Note:
Call this to free memory used by MPFR's internal caches
Useful for long-running programs to manage memory usage
"""Advanced floating-point manipulation and analysis functions.
def can_round(x, err, rnd1, rnd2, prec):
"""
Test if rounding is deterministic given error bounds.
Args:
x: Value to test (mpfr)
err: Error bound
rnd1: First rounding mode
rnd2: Second rounding mode
prec: Target precision
Returns:
bool: True if both rounding modes yield same result
Note:
Useful for determining if a computed result can be rounded safely
"""
def check_range(x):
"""
Check and adjust value to fit in current context range.
Args:
x: Floating-point value (mpfr)
Returns:
mpfr: Value adjusted for current context emin/emax if needed
"""
def next_above(x):
"""
Get next representable value above x.
Args:
x: Floating-point value (mpfr)
Returns:
mpfr: Smallest representable value > x
"""
def next_below(x):
"""
Get next representable value below x.
Args:
x: Floating-point value (mpfr)
Returns:
mpfr: Largest representable value < x
"""
def next_toward(x, y):
"""
Get next representable value toward y.
Args:
x: Starting value (mpfr)
y: Direction value (mpfr)
Returns:
mpfr: Next representable value in direction of y
"""
def reldiff(x, y):
"""
Compute relative difference between two values.
Args:
x, y: Floating-point values (mpfr)
Returns:
mpfr: Relative difference |x-y|/max(|x|,|y|)
"""
def get_exp(x):
"""
Get exponent of floating-point number.
Args:
x: Floating-point value (mpfr)
Returns:
int: Exponent of x
"""
def set_exp(x, exp):
"""
Set exponent of floating-point number.
Args:
x: Floating-point value (mpfr)
exp: New exponent value
Returns:
mpfr: Value with modified exponent
"""
def set_sign(x, sign):
"""
Set sign of floating-point number.
Args:
x: Floating-point value (mpfr)
sign: Sign (positive/negative indicator)
Returns:
mpfr: Value with specified sign
"""def f2q(x, max_denominator=None):
"""
Convert float to rational with optional denominator limit.
Args:
x: Floating-point value
max_denominator: Maximum allowed denominator (None for no limit)
Returns:
mpq: Rational approximation of x
Note:
Provides controlled conversion from float to exact rational
"""def prev_prime(x):
"""
Find previous prime number less than x (requires GMP 6.3.0+).
Args:
x: Starting value
Returns:
mpz: Previous prime before x
Note:
Counterpart to next_prime(), available in newer GMP versions
"""def is_lessgreater(x, y):
"""
Test if x < y or x > y (not equal, not unordered).
Args:
x, y: Numeric values
Returns:
bool: True if x != y and neither is NaN
"""
def is_unordered(x, y):
"""
Test if comparison is unordered (involves NaN).
Args:
x, y: Numeric values
Returns:
bool: True if either x or y is NaN
"""import gmpy2
# Get version information
print(f"gmpy2 version: {gmpy2.version()}")
print(f"GMP version: {gmpy2.mp_version()}")
print(f"MPFR version: {gmpy2.mpfr_version()}")
print(f"MPC version: {gmpy2.mpc_version()}")
print(f"GMP limb size: {gmpy2.mp_limbsize()} bits")
# Display license information
print("License:")
print(gmpy2.license())import gmpy2
# Create various gmpy2 objects
integer = gmpy2.mpz("123456789012345678901234567890")
rational = gmpy2.mpq(22, 7)
real = gmpy2.mpfr("3.14159265358979323846264338327950288419716939937510")
complex_num = gmpy2.mpc("1.5+2.5j")
# Convert to binary format
print("Binary serialization:")
for name, obj in [("Integer", integer), ("Rational", rational),
("Real", real), ("Complex", complex_num)]:
binary_data = gmpy2.to_binary(obj)
print(f"{name}: {len(binary_data)} bytes")
# Deserialize back
restored = gmpy2.from_binary(binary_data)
print(f" Original: {obj}")
print(f" Restored: {restored}")
print(f" Equal: {obj == restored}")import gmpy2
# Query system limits
print("MPFR system limits:")
print(f"Maximum precision: {gmpy2.get_max_precision()} bits")
print(f"Maximum exponent: {gmpy2.get_emax_max()}")
print(f"Minimum exponent: {gmpy2.get_emin_min()}")
# Test precision limits
try:
with gmpy2.local_context(precision=gmpy2.get_max_precision()):
x = gmpy2.mpfr("1.5")
print(f"Using maximum precision: {x.precision} bits")
except:
print("Maximum precision too large for this system")
# Memory management
print("Freeing MPFR caches...")
gmpy2.free_cache()import gmpy2
with gmpy2.local_context(precision=100):
x = gmpy2.mpfr("1.5")
# Examine representable values
above = gmpy2.next_above(x)
below = gmpy2.next_below(x)
print(f"Value: {x}")
print(f"Next above: {above}")
print(f"Next below: {below}")
print(f"Difference above: {above - x}")
print(f"Difference below: {x - below}")
# Get/set exponent
exp = gmpy2.get_exp(x)
print(f"Exponent: {exp}")
# Relative difference
y = gmpy2.mpfr("1.50000000000001")
rel_diff = gmpy2.reldiff(x, y)
print(f"Relative difference: {rel_diff}")import gmpy2
# Convert floats to rationals with denominator limits
test_values = [3.14159, 2.71828, 1.41421]
print("Float to rational conversion:")
for val in test_values:
# Unlimited denominator
exact = gmpy2.f2q(val)
# Limited denominator
approx_100 = gmpy2.f2q(val, max_denominator=100)
approx_1000 = gmpy2.f2q(val, max_denominator=1000)
print(f"\nFloat: {val}")
print(f" Exact: {exact}")
print(f" Max denom 100: {approx_100} = {float(approx_100)}")
print(f" Max denom 1000: {approx_1000} = {float(approx_1000)}")import gmpy2
with gmpy2.local_context(precision=50):
# Test if rounding is deterministic
x = gmpy2.mpfr("1.23456789")
error = gmpy2.mpfr("1e-10") # Small error bound
target_precision = 30
# Test different rounding mode pairs
rounding_pairs = [
(gmpy2.RoundToNearest, gmpy2.RoundUp),
(gmpy2.RoundDown, gmpy2.RoundUp),
(gmpy2.RoundToZero, gmpy2.RoundToNearest)
]
for rnd1, rnd2 in rounding_pairs:
deterministic = gmpy2.can_round(x, error, rnd1, rnd2, target_precision)
print(f"Rounding modes {rnd1} vs {rnd2}: {'deterministic' if deterministic else 'not deterministic'}")import gmpy2
# Create special values
x = gmpy2.mpfr("1.5")
y = gmpy2.nan()
z = gmpy2.inf()
# Test predicates
print("Special value predicates:")
print(f"is_lessgreater(1.5, 2.0): {gmpy2.is_lessgreater(x, gmpy2.mpfr('2.0'))}")
print(f"is_lessgreater(1.5, NaN): {gmpy2.is_lessgreater(x, y)}") # False
print(f"is_unordered(1.5, NaN): {gmpy2.is_unordered(x, y)}") # True
print(f"is_unordered(1.5, inf): {gmpy2.is_unordered(x, z)}") # FalseInstall with Tessl CLI
npx tessl i tessl/pypi-gmpy2