Welcome to gmpy2’s documentation!
gmpy2 is a C-coded Python extension module that supports multiple-precision arithmetic. It is the successor to the original gmpy module (supported only the GMP library). gmpy2 adds support for the MPFR (correctly rounded real floating-point arithmetic) and MPC (correctly rounded complex floating-point arithmetic) libraries.
The following libraries are supported:
GMP for integer and rational arithmetic (https://gmplib.org)
MPFR (https://www.mpfr.org)
Generalized Lucas sequences and primality tests are based on the following code:
mpz_lucas: https://sourceforge.net/projects/mpzlucas/
Contents
Overview
The mpz
and mpq
types support arbitrary precision integers and rationals
via the GMP library. These types should be drop-in replacements for Python’s
int
’s and Fraction
’s, but are significantly faster for large
values. The cutover point for performance varies, but can be as low as 20 to
40 digits. All the special integer functions in the GMP are supported.
Warning
gmpy2 can crash the Python interpreter in case of memory allocation failure. To mitigate this feature of memory management in the GMP library, you should estimate the size of all results and prevent calculations that can exaust available memory.
The mpfr
and mpc
types provide support for correctly rounded multiple
precision real and complex arithmetic via the MPFR and MPC libraries. The
context
type is used to control precision, rounding modes, and exceptional
conditions. For example, division by zero can either return an Infinity or
raise an exception. It is possible to specify different precision and rounding
modes for both the real and imaginary components of an mpc
. The default
precision is 53 bits — just same as for Python’s float
and complex
types.
Operator overloading is fully supported. Coversion from native Python types is optimized for performance.
Installation
gmpy2 requires CPython 3.7 or above. Pre-compiled binary wheels are available on PyPI. You can install latest release with pip:
pip install gmpy2
or some specific version with:
pip install gmpy2==2.1.5
From Sources
If pre-compiled binary wheels aren’t available for your platform, the pip will fallback to installation from sources. In this case you will need to have required libraries (GMP, MPFR and MPC) already installed on your system, along with the include files for those libraries. On Debian you can install them systed-wide with:
sudo apt install libgmp-dev libmpfr-dev libmpc-dev
Tip
On Windows we recommend using MSYS2 to build the gmpy2 from sources. To install required dependencies before, run:
pacman -S gcc gmp-devel mpfr-devel mpc-devel python-setuptools python-pip
If you are a developer or like to get the latest updates as they come, be sure to install from the git repository and include required extra dependencies, for example the optional “tests” list, which include packages required for testing:
git clone git://github.com/aleaxit/gmpy.git
cd gmpy
pip install -e .[tests]
Next you may want to run full set of unit tests to make sure everything works:
pytest test/
Tutorial
Start by importing the contents of the package with:
>>> from gmpy2 import *
Note
The use of from gmpy2 import *
is not recommended in real code. The
names in gmpy2 have been chosen to avoid conflict with Python’s builtin
names but gmpy2 does use names that may conflict with other modules or
variable names. In normal usage you’ll probably only want to import the
classes and functions that you actually need.
Lets look first on some examples of arbitrary precision arithmetic with integer and rational types:
>>> mpz(99) * 43
mpz(4257)
>>> pow(mpz(99), 37, 59)
mpz(18)
>>> isqrt(99)
mpz(9)
>>> isqrt_rem(99)
(mpz(9), mpz(18))
>>> gcd(123, 27)
mpz(3)
>>> lcm(123, 27)
mpz(1107)
>>> (mpz(123) + 12) / 5
mpfr('27.0')
>>> (mpz(123) + 12) // 5
mpz(27)
>>> (mpz(123) + 12) / 5.0
mpfr('27.0')
>>> mpz('123') + 1
mpz(124)
>>> 10 - mpz(1)
mpz(9)
>>> is_prime(17)
True
>>> mpz('1_000_000')
mpz(1000000)
>>> mpq(3, 7)/7
mpq(3,49)
>>> mpq(45, 3) * mpq(11, 8)
mpq(165,8)
>>> mpq(1, 7) * 11
mpq(11,7)
But gmpy2 also supports correctly rounded multiple precision real and complex arithmetic. The following example shows how to control precision settings and rounding modes:
>>> mpfr('1.2')
mpfr('1.2')
>>> mpfr(float('1.2'))
mpfr('1.2')
>>> ctx = get_context()
>>> ctx.precision
53
>>> ctx.precision = 100
>>> mpfr('1.2')
mpfr('1.2000000000000000000000000000006',100)
>>> mpfr(float('1.2'))
mpfr('1.1999999999999999555910790149937',100)
>>> ctx.precision = 53
>>> ctx.round = RoundUp
>>> const_pi()
mpfr('3.1415926535897936')
>>> ctx.round = RoundToNearest
>>> const_pi()
mpfr('3.1415926535897931')
You have seen, that if the precision is changed, then mpfr(float('1.2'))
differs from mpfr('1.2')
. To take advantage of the higher precision
provided by the mpfr
type, always pass constants as strings.
Floating point contexts also are used to control exceptional conditions. For example, division by zero can either return a floating-point positive infinity (default) or raise an exception.
>>> ctx.divzero
False
>>> mpfr(1)/0
mpfr('inf')
>>> ctx.trap_divzero = True
>>> mpfr(1)/0
Traceback (most recent call last):
...
gmpy2.DivisionByZeroError: division by zero
>>> ctx.divzero
True
Exceptions are normally raised in Python when the result of a real operation is
not defined over the reals; for example, math.sqrt(-2)
will raise a
ValueError
exception. The default context in gmpy2 implements similar
behavior, but by setting allow_complex
flag, complex results
will be returned.
>>> sqrt(mpfr(-2))
mpfr('nan')
>>> ctx.allow_complex = True
>>> sqrt(mpfr(-2))
mpc('0.0+1.4142135623730951j')
Contexts can also be used as context managers in conjunction with Python’s
with
statement to temporarily change the current context settings
for a block of code.
>>> print(const_pi())
3.1415926535897931
>>> with context(precision=100) as ctx:
... print(const_pi())
... ctx.precision += 20
... print(const_pi())
...
3.1415926535897932384626433832793
3.1415926535897932384626433832795028847
>>> print(const_pi())
3.1415926535897931
It’s possible to set different precision settings for real and imaginary components.
>>> ctx = get_context()
>>> ctx.real_prec = 60
>>> ctx.imag_prec = 70
>>> sqrt(mpc('1+2j'))
mpc('1.272019649514068965+0.78615137775742328606947j',(60,70))
All gmpy2 numeric types support Python’s “new style” string formatting
available in formatted string literals or with
str.format()
; see Format Specification Mini-Language for a description
of the standard formatting syntax. The precision value optionally can be
followed by the rounding mode type (‘U’ to round toward plus infinity, ‘D’ to
round toward minus infinity, ‘Y’ to round away from zero, ‘Z’ to round toward
zero and ‘N’ - round to the nearest value.
>>> a = mpfr("1.23456")
>>> "{0:15.3f}".format(a)
' 1.235'
>>> "{0:15.3Uf}".format(a)
' 1.235'
>>> "{0:15.3Df}".format(a)
' 1.234'
>>> "{0:.3Df}".format(a)
'1.234'
>>> "{0:+.3Df}".format(a)
'+1.234'
Integers
mpz type
- class gmpy2.mpz(n=0, /)
- class gmpy2.mpz(s, /, base=0)
Return an immutable integer constructed from a numeric value n (truncating n to its integer part) or a string s made of digits in the given base. Every input, that is accepted by the
int
type constructor is also accepted.The base may vary from 2 to 62, or if base is 0, then binary, octal, or hexadecimal strings are recognized by leading ‘0b’, ‘0o’, or ‘0x’ characters (case is ignored), otherwise the string is assumed to be decimal. For bases up to 36, digits case is ignored. For bases 37 to 62, upper-case letter represent the usual 10..35 range, while lower-case letter represent 36..61. Optionally the string can be preceded by ‘+’ or ‘-’. White space and underscore is simply ignored.
- __format__(fmt) str
Return a Python string by formatting
mpz
‘x’ using the format string ‘fmt’. A valid format string consists of:optional alignment code:
‘<’ -> left shifted in field ‘>’ -> right shifted in field ‘^’ -> centered in field
optional leading sign code:
‘+’ -> always display leading sign ‘-’ -> only display minus sign ‘ ‘ -> minus for negative values, space for positive values
optional base indicator
‘#’ -> precede binary, octal, or hex with 0b, 0o or 0x
optional width
optional conversion code:
‘d’ -> decimal format ‘b’ -> binary format ‘o’ -> octal format ‘x’ -> hex format ‘X’ -> upper-case hex format
The default format is ‘d’.
- as_integer_ratio() tuple[mpz, mpz]
Return a pair of integers, whose ratio is exactly equal to the original number. The ratio is in lowest terms and has a positive denominator.
- bit_length() int
Return the number of significant bits in the radix-2 representation of x. Note: mpz(0).bit_length() returns 0.
- bit_scan0(n=0, /) int | None
Return the index of the first 0-bit of x with index >= n. n >= 0. If there are no more 0-bits in x at or above index n (which can only happen for x<0, assuming an infinitely long 2’s complement format), then
None
is returned.
- bit_scan1(n=0, /) int | None
Return the index of the first 1-bit of x with index >= n. n >= 0. If there are no more 1-bits in x at or above index n (which can only happen for x>=0, assuming an infinitely long 2’s complement format), then
None
is returned.
- conjugate() mpz
Return the conjugate of x (which is just a new reference to x since x is not a complex number).
- digits(base=10, /) str
Return Python string representing x in the given base. Values for base can range between 2 to 62. A leading ‘-’ is present if x<0 but no leading ‘+’ is present if x>=0.
- from_bytes(bytes, byteorder='big', *, signed=False) mpz
Return the integer represented by the given array of bytes.
- bytes
Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes.
bytes
andbytearray
are examples of built-in objects that support the buffer protocol.- byteorder
The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use
sys.byteorder
as the byte order value.- signed
Indicates whether two’s complement is used to represent the integer.
- is_power() bool
Return
True
if x is a perfect power (there exists a y and an n > 1, such that x=y**n), else returnFalse
.
- is_prime(n=25, /) bool
Return
True
if x is probably prime, elseFalse
if x is definitely composite. x is checked for small divisors and up to n Miller-Rabin tests are performed.
- is_probab_prime(n=25, /) int
Return 2 if x is definitely prime, 1 if x is probably prime, or return 0 if x is definitely non-prime. x is checked for small divisors and up to n Miller-Rabin tests are performed. Reasonable values of n are between 15 and 50.
- num_digits(base=10, /) int
Return length of string representing the absolute value of x in the given base. Values for base can range between 2 and 62. The value returned may be 1 too large.
- to_bytes(length=1, byteorder='big', *, signed=False) bytes
Return an array of bytes representing an integer.
- length
Length of bytes object to use. An
OverflowError
is raised if the integer is not representable with the given number of bytes.- byteorder
The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use
sys.byteorder
as the byte order value.- signed
Determines whether two’s complement is used to represent the integer. If signed is
False
and a negative integer is given, anOverflowError
is raised.
- denominator
the denominator of a rational number in lowest terms
- imag
the imaginary part of a complex number
- numerator
the numerator of a rational number in lowest terms
- real
the real part of a complex number
mpz Functions
- gmpy2.bit_length(x, /) int
Return the number of significant bits in the radix-2 representation of x. Note: bit_length(0) returns 0.
- gmpy2.bit_scan0(x, n=0, /) int | None
Return the index of the first 0-bit of x with index >= n. n >= 0. If there are no more 0-bits in x at or above index n (which can only happen for x<0, assuming an infinitely long 2’s complement format), then
None
is returned.
- gmpy2.bit_scan1(x, n=0, /) int | None
Return the index of the first 1-bit of x with index >= n. n >= 0. If there are no more 1-bits in x at or above index n (which can only happen for x>=0, assuming an infinitely long 2’s complement format), then
None
is returned.
- gmpy2.c_div(x, y, /) mpz
Return the quotient of x divided by y. The quotient is rounded towards +Inf (ceiling rounding). x and y must be integers.
- gmpy2.c_div_2exp(x, n, /) mpz
Returns the quotient of x divided by 2**n. The quotient is rounded towards +Inf (ceiling rounding). x must be an integer. n must be >0.
- gmpy2.c_divmod(x, y, /) tuple[mpz, mpz]
Return the quotient and remainder of x divided by y. The quotient is rounded towards +Inf (ceiling rounding) and the remainder will have the opposite sign of y. x and y must be integers.
- gmpy2.c_divmod_2exp(x, n, /) tuple[mpz, mpz]
Return the quotient and remainder of x divided by 2**n. The quotient is rounded towards +Inf (ceiling rounding) and the remainder will be negative. x must be an integer. n must be >0.
- gmpy2.c_mod(x, y, /) mpz
Return the remainder of x divided by y. The remainder will have the opposite sign of y. x and y must be integers.
- gmpy2.c_mod_2exp(x, n, /) mpz
Return the remainder of x divided by 2**n. The remainder will be negative. x must be an integer. n must be >0.
- gmpy2.comb(n, k, /) mpz
Return the number of combinations of ‘n things, taking k at a time’. k >= 0. Same as bincoef(n, k)
- gmpy2.divexact(x, y, /) mpz
Return the quotient of x divided by y. Faster than standard division but requires the remainder is zero!
- gmpy2.divm(a, b, m, /) mpz
Return x such that b*x == a mod m. Raises a
ZeroDivisionError
exception if no such value x exists.
- gmpy2.double_fac(n, /) mpz
Return the exact double factorial (n!!) of n. The double factorial is defined as n*(n-2)*(n-4)…
- gmpy2.f_div(x, y, /) mpz
Return the quotient of x divided by y. The quotient is rounded towards -Inf (floor rounding). x and y must be integers.
- gmpy2.f_div_2exp(x, n, /) mpz
Return the quotient of x divided by 2**n. The quotient is rounded towards -Inf (floor rounding). x must be an integer. n must be >0.
- gmpy2.f_divmod(x, y, /) tuple[mpz, mpz]
Return the quotient and remainder of x divided by y. The quotient is rounded towards -Inf (floor rounding) and the remainder will have the same sign as y. x and y must be integers.
- gmpy2.f_divmod_2exp(x, n, /) tuple[mpz, mpz]
Return quotient and remainder after dividing x by 2**n. The quotient is rounded towards -Inf (floor rounding) and the remainder will be positive. x must be an integer. n must be >0.
- gmpy2.f_mod(x, y, /) mpz
Return the remainder of x divided by y. The remainder will have the same sign as y. x and y must be integers.
- gmpy2.f_mod_2exp(x, n, /) mpz
Return remainder of x divided by 2**n. The remainder will be positive. x must be an integer. n must be >0.
- gmpy2.fac(n, /) mpz
Return the exact factorial of n.
See factorial(n) to get the floating-point approximation.
- gmpy2.gcdext(a, b, /) tuple[mpz, mpz, mpz]
Return a 3-element tuple (g,s,t) such that g == gcd(a,b) and g == a*s + b*t.
- gmpy2.hamdist(x, y, /) int
Return the Hamming distance (number of bit-positions where the bits differ) between integers x and y.
- gmpy2.invert(x, m, /) mpz
Return y such that x*y == 1 modulo m. Raises
ZeroDivisionError
if no inverse exists.
- gmpy2.iroot(x, n, /) tuple[mpz, bool]
Return the integer n-th root of x and boolean value that is
True
iff the root is exact. x >= 0. n > 0.
- gmpy2.iroot_rem(x, n, /) tuple[mpz, mpz]
Return a 2-element tuple (y,r), such that y is the integer n-th root of x and x=y**n + r. x >= 0. n > 0.
- gmpy2.is_congruent(x, y, m, /) bool
Returns
True
if x is congruent to y modulo m, else returnFalse
.
- gmpy2.is_power(x, /) bool
Return
True
if x is a perfect power (there exists a y and an n > 1, such that x=y**n), else returnFalse
.
- gmpy2.is_prime(x, n=25, /) bool
Return
True
if x is probably prime, elseFalse
if x is definitely composite. x is checked for small divisors and up to n Miller-Rabin tests are performed.
- gmpy2.is_probab_prime(x, n=25, /) int
Return 2 if x is definitely prime, 1 if x is probably prime, or return 0 if x is definitely non-prime. x is checked for small divisors and up to n Miller-Rabin tests are performed. Reasonable values of n are between 15 and 50.
- gmpy2.isqrt_rem(x, /)
Return a 2-element tuple (s,t) such that s=isqrt(x) and t=x-s*s. x >=0.
- gmpy2.mpz_random(random_state, int, /) mpz
Return uniformly distributed random integer between 0 and n-1.
- gmpy2.mpz_rrandomb(random_state, bit_count, /) mpz
Return a random integer between 0 and 2**bit_count-1 with long sequences of zeros and one in its binary representation.
- gmpy2.mpz_urandomb(random_state, bit_count, /) mpz
Return uniformly distributed random integer between 0 and 2**bit_count-1.
- gmpy2.multi_fac(n, m, /) mpz
Return the exact m-multi factorial of n. The m-multifactorial is defined as n*(n-m)*(n-2m)…
- gmpy2.num_digits(x, base=10, /) int
Return length of string representing the absolute value of x in the given base. Values for base can range between 2 and 62. The value returned may be 1 too large.
- gmpy2.pack(lst, n, /) mpz
Pack a list of integers lst into a single
mpz
by concatenating each integer element of lst after padding to length n bits. Raises an error if any integer is negative or greater than n bits in length.
- gmpy2.popcount(x, /) int
Return the number of 1-bits set in x. If x<0, the number of 1-bits is infinite so -1 is returned in that case.
- gmpy2.powmod(x, y, m, /) mpz
Return (x**y) mod m. Same as the three argument version of Python’s built-in
pow
, but converts all three arguments tompz
.
- gmpy2.powmod_exp_list(base, exp_lst, mod, /) list[mpz, ...]
Returns list(powmod(base, i, mod) for i in exp_lst). Will always release the GIL. (Experimental in gmpy2 2.1.x).
- gmpy2.powmod_base_list(base_lst, exp, mod, /) list[mpz, ...]
Returns list(powmod(i, exp, mod) for i in base_lst). Will always release the GIL. (Experimental in gmpy2 2.1.x).
- gmpy2.powmod_sec(x, y, m, /) mpz
Return (x**y) mod m. Calculates x ** y (mod m) but using a constant time algorithm to reduce the risk of side channel attacks. y must be an integer >0. m must be an odd integer.
- gmpy2.prev_prime(x, /) mpz
Return the previous probable prime number < x. Only present when compiled with GMP 6.3.0 or later.
- gmpy2.primorial(n, /) mpz
Return the product of all positive prime numbers less than or equal to n.
- gmpy2.remove(x, f, /) tuple[mpz, mpz]
Return a 2-element tuple (y,m) such that x=y*(f**m) and f does not divide y. Remove the factor f from x as many times as possible. m is the multiplicity f in x. f > 1.
- gmpy2.t_div(x, y, /) mpz
Return the quotient of x divided by y. The quotient is rounded towards 0. x and y must be integers.
- gmpy2.t_div_2exp(x, n, /) mpz
Return the quotient of x divided by 2**n. The quotient is rounded towards zero (truncation). n must be >0.
- gmpy2.t_divmod(x, y, /) tuple[mpz, mpz]
Return the quotient and remainder of x divided by y. The quotient is rounded towards zero (truncation) and the remainder will have the same sign as x. x and y must be integers.
- gmpy2.t_divmod_2exp(x, n, /) tuple[mpz, mpz]
Return the quotient and remainder of x divided by 2**n. The quotient is rounded towards zero (truncation) and the remainder will have the same sign as x. x must be an integer. n must be >0.
- gmpy2.t_mod(x, y, /) mpz
Return the remainder of x divided by y. The remainder will have the same sign as x. x and y must be integers.
Integers (Advanced topics)
gmpy2 provides access to an experimental integer type called xmpz
. The
xmpz
type is a mutable integer type. In-place operations (+=, //=,
etc.) modify the original object and do not create a new object. Instances of
xmpz
cannot be used as dictionary keys.
>>> from gmpy2 import xmpz
>>> a = xmpz(123)
>>> b = a
>>> a += 1
>>> a
xmpz(124)
>>> b
xmpz(124)
The ability to change an xmpz
object in-place allows for efficient and
rapid bit manipulation.
Individual bits can be set or cleared:
>>> a[10]=1
>>> a
xmpz(1148)
Slice notation is supported. The bits referenced by a slice can be either ‘read from’ or ‘written to’. To clear a slice of bits, use a source value of 0. In 2s-complement format, 0 is represented by an arbitrary number of 0-bits. To set a slice of bits, use a source value of ~0. The tilde operator inverts, or complements the bits in an integer. (~0 is -1 so you can also use -1.) In 2s-complement format, -1 is represented by an arbitrary number of 1-bits.
If a value for stop is specified in a slice assignment and the actual
bit-length of the xmpz
is less than stop, then the destination
xmpz
is logically padded with 0-bits to length stop.
>>> a=xmpz(0)
>>> a[8:16] = ~0
>>> bin(a)
'0b1111111100000000'
>>> a[4:12] = ~a[4:12]
>>> bin(a)
'0b1111000011110000'
Bits can be reversed:
>>> a = xmpz(1148)
>>> bin(a)
'0b10001111100'
>>> a[::] = a[::-1]
>>> bin(a)
'0b111110001'
The iter_bits()
method returns a generator that returns True or
False for each bit position. The methods iter_clear()
, and
iter_set()
return generators that return the bit positions that are
1 or 0. The methods support arguments start and stop that define the
beginning and ending bit positions that are used. To mimic the behavior of
slices. the bit positions checked include start but the last position checked
is stop - 1.
>>> a=xmpz(117)
>>> bin(a)
'0b1110101'
>>> list(a.iter_bits())
[True, False, True, False, True, True, True]
>>> list(a.iter_clear())
[1, 3]
>>> list(a.iter_set())
[0, 2, 4, 5, 6]
>>> list(a.iter_bits(stop=12))
[True, False, True, False, True, True, True, False, False, False, False, False]
The following program uses the Sieve of Eratosthenes to generate a list of prime numbers.
import time
import gmpy2
def sieve(limit=1000000):
'''Returns a generator that yields the prime numbers up to limit.'''
# Increment by 1 to account for the fact that slices do not include
# the last index value but we do want to include the last value for
# calculating a list of primes.
sieve_limit = gmpy2.isqrt(limit) + 1
limit += 1
# Mark bit positions 0 and 1 as not prime.
bitmap = gmpy2.xmpz(3)
# Process 2 separately. This allows us to use p+p for the step size
# when sieving the remaining primes.
bitmap[4 : limit : 2] = -1
# Sieve the remaining primes.
for p in bitmap.iter_clear(3, sieve_limit):
bitmap[p*p : limit : p+p] = -1
return bitmap.iter_clear(2, limit)
if __name__ == "__main__":
start = time.time()
result = list(sieve())
print(time.time() - start)
print(len(result))
The xmpz type
- class gmpy2.xmpz(n=0, /)
- class gmpy2.xmpz(s, /, base=0)
Return a mutable integer constructed from a numeric value n or a string s made of digits in the given base. Every input, that is accepted by the
mpz
type constructor is also accepted.Note: This type can be faster when used for augmented assignment (+=, -=, etc), but
xmpz
objects cannot be used as dictionary keys.- __format__(fmt) str
Return a Python string by formatting
mpz
‘x’ using the format string ‘fmt’. A valid format string consists of:optional alignment code:
‘<’ -> left shifted in field ‘>’ -> right shifted in field ‘^’ -> centered in field
optional leading sign code:
‘+’ -> always display leading sign ‘-’ -> only display minus sign ‘ ‘ -> minus for negative values, space for positive values
optional base indicator
‘#’ -> precede binary, octal, or hex with 0b, 0o or 0x
optional width
optional conversion code:
‘d’ -> decimal format ‘b’ -> binary format ‘o’ -> octal format ‘x’ -> hex format ‘X’ -> upper-case hex format
The default format is ‘d’.
- bit_length() int
Return the number of significant bits in the radix-2 representation of x. Note: mpz(0).bit_length() returns 0.
- bit_scan0(n=0, /) int | None
Return the index of the first 0-bit of x with index >= n. n >= 0. If there are no more 0-bits in x at or above index n (which can only happen for x<0, assuming an infinitely long 2’s complement format), then
None
is returned.
- bit_scan1(n=0, /) int | None
Return the index of the first 1-bit of x with index >= n. n >= 0. If there are no more 1-bits in x at or above index n (which can only happen for x>=0, assuming an infinitely long 2’s complement format), then
None
is returned.
- conjugate() mpz
Return the conjugate of x (which is just a new reference to x since x is not a complex number).
- digits(base=10, /) str
Return Python string representing x in the given base. Values for base can range between 2 to 62. A leading ‘-’ is present if x<0 but no leading ‘+’ is present if x>=0.
- iter_bits(start=0, stop=-1) collections.abc.Iterator
Return
True
orFalse
for each bit position in x beginning at ‘start’. If a positive value is specified for ‘stop’, iteration is continued until ‘stop’ is reached. If a negative value is specified, iteration is continued until the last 1-bit. Note: the value of the underlyingxmpz
object can change during iteration.
- iter_clear(start=0, stop=-1) collections.abc.Iterator
Return every bit position that is clear in x, beginning at ‘start’. If a positive value is specified for ‘stop’, iteration is continued until ‘stop’ is reached. If a negative value is specified, iteration is continued until the last 1-bit. Note: the value of the underlying
xmpz
object can change during iteration.
- iter_set(start=0, stop=-1) collections.abc.Iterator
Return an iterator yielding the bit position for every bit that is set in x, beginning at ‘start’. If a positive value is specified for ‘stop’, iteration is continued until ‘stop’ is reached. To match the behavior of slicing, ‘stop’ is not included. If a negative value is specified, iteration is continued until the last 1-bit. Note: the value of the underlying
xmpz
object can change during iteration.
- limbs_finish(n, /) None
Must be called after writing to the address returned by x.limbs_write(n) or x.limbs_modify(n) to update the limbs of x.
- limbs_modify(n, /) int
Returns the address of a mutable buffer representing the limbs of x, resized so that it may hold at least n limbs. Must be followed by a call to x.limbs_finish(n) after writing to the returned address in order for the changes to take effect.
- limbs_write(n, /) int
Returns the address of a mutable buffer representing the limbs of x, resized so that it may hold at least n limbs. Must be followed by a call to x.limbs_finish(n) after writing to the returned address in order for the changes to take effect. WARNING: this operation is destructive and may destroy the old value of x.
- make_mpz() mpz
Return an
mpz
by converting x as quickly as possible.NOTE: Optimized for speed so the original
xmpz
value is set to 0!
- num_digits(base=10, /) int
Return length of string representing the absolute value of x in the given base. Values for base can range between 2 and 62. The value returned may be 1 too large.
- denominator
the denominator of a rational number in lowest terms
- numerator
the numerator of a rational number in lowest terms
- real
the real part of a complex number
Advanced Number Theory Functions
The following functions are based on mpz_lucas.c and mpz_prp.c by David Cleaver.
A good reference for probable prime testing is http://www.pseudoprime.com/pseudo.html
- gmpy2.is_bpsw_prp(n, /) bool
Return
True
if n is a Baillie-Pomerance-Selfridge-Wagstaff probable prime. A BPSW probable prime passes theis_strong_prp()
test with base 2 and theis_selfridge_prp()
test.
- gmpy2.is_euler_prp(n, a, /) bool
Return
True
if n is an Euler (also known as Solovay-Strassen) probable prime to the base a. Assuming:gcd(n,a) == 1 n is odd
Then an Euler probable prime requires:
a**((n-1)/2) == (a/n) (mod n)
where (a/n) is the Jacobi symbol.
- gmpy2.is_extra_strong_lucas_prp(n, p, /) bool
Return
True
if n is an extra strong Lucas probable prime with parameters (p,1). Assuming:n is odd D = p*p - 4, D != 0 gcd(n, 2*D) == 1 n = s*(2**r) + Jacobi(D,n), s odd
Then an extra strong Lucas probable prime requires:
lucasu(p,1,s) == 0 (mod n) and lucasv(p,1,s) == +/-2 (mod n) or lucasv(p,1,s*(2**t)) == 0 (mod n) for some t, 0 <= t < r
- gmpy2.is_fermat_prp(n, a, /) bool
Return
True
if n is a Fermat probable prime to the base a. Assuming:gcd(n,a) == 1
Then a Fermat probable prime requires:
a**(n-1) == 1 (mod n)
- gmpy2.is_fibonacci_prp(n, p, q, /) bool
Return
True
if n is a Fibonacci probable prime with parameters (p,q). Assuming:n is odd p > 0, q = +/-1 p*p - 4*q != 0
Then a Fibonacci probable prime requires:
lucasv(p,q,n) == p (mod n).
- gmpy2.is_lucas_prp(n, p, q, /) bool
Return
True
if n is a Lucas probable prime with parameters (p,q). Assuming:n is odd D = p*p - 4*q, D != 0 gcd(n, 2*q*D) == 1
Then a Lucas probable prime requires:
lucasu(p,q,n - Jacobi(D,n)) == 0 (mod n)
- gmpy2.is_selfridge_prp(n, /) bool
Return
True
if n is a Lucas probable prime with Selfidge parameters (p,q). The Selfridge parameters are chosen by finding the first element D in the sequence {5, -7, 9, -11, 13, …} such that Jacobi(D,n) == -1. Then let p=1 and q = (1-D)/4. Then perform a Lucas probable prime test.
- gmpy2.is_strong_bpsw_prp(n, /) bool
Return
True
if n is a strong Baillie-Pomerance-Selfridge-Wagstaff probable prime. A strong BPSW probable prime passes theis_strong_prp()
test with base and theis_strong_selfridge_prp()
test.
- gmpy2.is_strong_lucas_prp(n, p, q, /) bool
Return
True
if n is a strong Lucas probable prime with parameters (p,q). Assuming:n is odd D = p*p - 4*q, D != 0 gcd(n, 2*q*D) == 1 n = s*(2**r) + Jacobi(D,n), s odd
Then a strong Lucas probable prime requires:
lucasu(p,q,s) == 0 (mod n) or lucasv(p,q,s*(2**t)) == 0 (mod n) for some t, 0 <= t < r
- gmpy2.is_strong_prp(n, a, /) bool
Return
True
if n is a strong (also known as Miller-Rabin) probable prime to the base a. Assuming:gcd(n,a) == 1 n is odd n = s*(2**r) + 1, with s odd
Then a strong probable prime requires one of the following is true:
a**s == 1 (mod n) or a**(s*(2**t)) == -1 (mod n) for some t, 0 <= t < r.
- gmpy2.is_strong_selfridge_prp(n, /) bool
Return
True
if n is a strong Lucas probable prime with Selfidge parameters (p,q). The Selfridge parameters are chosen by finding the first element D in the sequence {5, -7, 9, -11, 13, …} such that Jacobi(D,n) == -1. Then let p=1 and q = (1-D)/4. Then perform a strong Lucas probable prime test.
- gmpy2.lucasu(p, q, k, /) mpz
Return the k-th element of the Lucas U sequence defined by p,q. p*p - 4*q must not equal 0; k must be greater than or equal to 0.
- gmpy2.lucasu_mod(p, q, k, n, /) mpz
Return the k-th element of the Lucas U sequence defined by p,q (mod n). p*p - 4*q must not equal 0; k must be greater than or equal to 0; n must be greater than 0.
Rationals
mpq type
- class gmpy2.mpq(n=0, /)
- class gmpy2.mpq(n, m, /)
- class gmpy2.mpq(s, /, base=10)
Return a rational number constructed from a non-complex number n exactly or from a pair of
Rational
values n and m or from a string s made up of digits in the given base. Every input, that is accepted by theFraction
type constructor is also accepted.A string may be made up to two integers in the same base separated by a ‘/’ character, both parsed the same as the
mpz
type constructor does. If base is 0 then the leading characters are used to recognize the base, this is done separately for the numerator and denominator. If base=10, any string that represents a finite value and is accepted by thefloat
constructor is also accepted.- as_integer_ratio() tuple[mpz, mpz]
Return a pair of integers, whose ratio is exactly equal to the original number. The ratio is in lowest terms and has a positive denominator.
- conjugate() mpz
Return the conjugate of x (which is just a new reference to x since x is not a complex number).
- digits(base=10, /) str
Return a Python string representing x in the given base (2 to 62, default is 10). A leading ‘-’ is present if x<0, but no leading ‘+’ is present if x>=0.
- from_decimal(dec, /) mpq
Converts a finite
decimal.Decimal
instance to a rational number, exactly.
- denominator
the denominator of a rational number in lowest terms
- imag
the imaginary part of a complex number
- numerator
the numerator of a rational number in lowest terms
- real
the real part of a complex number
mpq Functions
Contexts
context()
creates a new context. set_context()
will set the active
context. get_context()
will return a reference to the active context. Note
that contexts are mutable: modifying the reference returned by get_context()
will modify the active context until a new context is enabled with
set_context()
. The context.copy()
method will return a copy of the
context. Contexts that implement the standard single, double, and
quadruple precision floating point types can be created using ieee()
.
Context Type
- class gmpy2.context(**kwargs)
- class gmpy2.context(ctx, /, **kwargs)
Return a new context for controlling gmpy2 arithmetic, based either on the default context or on a given by ctx value. Context options additionally can be overriden by keyword arguments.
- check_range(x, /) mpfr
Return a new
mpfr
with exponent that lies within the range of emin and emax specified by context.
- degrees(x, /) mpfr
Convert angle x from radians to degrees. Note: In rare cases the result may not be correctly rounded.
- divmod(x, y, /) tuple[mpz | mpfr, mpz | mpq | mpfr]
Return divmod(x, y).
Note: overflow, underflow, and inexact exceptions are not supported for
mpfr
arguments.
- factorial(n, /) mpfr
Return the floating-point approximation to the factorial of n.
See
fac()
to get the exact integer result.
- is_finite(x, /) bool
Return
True
if x is an actual number (i.e. non NaN or Infinity). If x is anmpc
, returnTrue
if both x.real and x.imag are finite.
- is_infinite(x, /) bool
Return
True
if x is +Infinity or -Infinity. If x is anmpc
, returnTrue
if either x.real or x.imag is infinite. Otherwise returnFalse
.
- is_zero(x, /) bool
Return
True
if x is equal to 0. If x is anmpc
, returnTrue
if both x.real and x.imag are equal to 0.
- jn(n, x, /) mpfr
Return the first kind Bessel function of order n of x. Note: the order of the arguments changed in gmpy2 2.2.0a2
- lgamma(x, /) tuple[mpfr, int]
Return a
tuple
containing the logarithm of the absolute value of gamma(x) and the sign of gamma(x)
- maxnum(x, y, /) mpfr
Return the maximum number of x and y. If x and y are not
mpfr
, they are converted tompfr
. The result is rounded to match the specified context. If only one of x or y is a number, then that number is returned.
- minnum(x, y, /) mpfr
Return the minimum number of x and y. If x and y are not
mpfr
, they are converted tompfr
. The result is rounded to match the specified context. If only one of x or y is a number, then that number is returned.
- mod(x, y, /) mpz | mpq | mpfr
Return mod(x, y). Note: overflow, underflow, and inexact exceptions are not supported for
mpfr
arguments.
- next_toward(x, y, /) mpfr
Return the next
mpfr
from x in the direction of y. The result has the same precision as x.
- norm(x, /) mpfr
Return the norm of a complex x. The norm(x) is defined as x.real**2 + x.imag**2. abs(x) is the square root of norm(x).
- polar(x, /) tuple[mpfr, mpfr]
Return the polar coordinate form of a complex x that is in rectangular form.
- radians(x, /) mpfr
Convert angle x from degrees to radians. Note: In rare cases the result may not be correctly rounded.
- rect(r, phi, /) mpc
Return the rectangular coordinate form of a complex number that is given in polar form.
- reldiff(x, y, /) mpfr
Return the relative difference between x and y. Result is equal to abs(x-y)/x.
- remainder(x, y, /) mpfr
Return x - n*y where n is the integer quotient of x/y, rounded to the nearest integer and ties rounded to even.
- remquo(x, y, /) tuple[mpfr, int]
Return a
tuple
containing the remainder(x,y) and the low bits of the quotient.
- rint_ceil(x, /) mpfr
Return x rounded to the nearest integer by first rounding to the next higher or equal integer and then, if needed, using the context rounding mode.
- rint_floor(x, /) mpfr
Return x rounded to the nearest integer by first rounding to the next lower or equal integer and then, if needed, using the context rounding mode.
- rint_round(x, /) mpfr
Return x rounded to the nearest integer by first rounding to the nearest integer (ties away from 0) and then, if needed, using the context rounding mode.
- rint_trunc(x, /) mpfr
Return x rounded to the nearest integer by first rounding towards zero and then, if needed, using the context rounding mode.
- root(x, n, /) mpfr
Return n-th root of x. The result always an
mpfr
. Note: not IEEE 754-2008 compliant; result differs when x = -0 and n is even. Seecontext.rootn()
.
- rootn(x, n, /) mpfr
Return n-th root of x. The result always an
mpfr
. Note: this is IEEE 754-2008 compliant version ofcontext.root()
.
- round2(x, n=0, /) mpfr
Return x rounded to n bits. Uses default precision if n is not specified. See
context.round_away()
to access the mpfr_round() function of the MPFR.
- round_away(x, /) mpfr
Return an
mpfr
that is x rounded to the nearest integer, with ties rounded away from 0.
- sin_cos(x, /) tuple[mpfr | mpc, mpfr | mpc]
Return a tuple containing the sine and cosine of x; x in radians.
- trunc(x, /) mpfr
Return an
mpfr
that is x truncated towards 0. Same as x.floor() if x>=0 or x.ceil() if x<0.
- yn(n, x, /) mpfr
Return the second kind Bessel function of order n of x. Note: the order of the arguments changed in gmpy2 2.2.0a2
- allow_complex
This attribute controls whether or not an
mpc
result can be returned if anmpfr
result would normally not be possible.
- allow_release_gil
If set to
True
, manympz
andmpq
computations will release the GIL.This is considered an experimental feature.
- divzero
This flag is not user controllable. It is automatically set if a division by zero occurred and NaN result was returned.
- emax
This attribute controls the maximum allowed exponent of an
mpfr
result. The maximum exponent is platform dependent and can be retrieved withget_emax_max()
.
- emin
This attribute controls the minimum allowed exponent of an
mpfr
result. The minimum exponent is platform dependent and can be retrieved withget_emin_min()
.
- erange
This flag is not user controllable. It is automatically set if an erange error occurred.
- imag_prec
This attribute controls the precision of the imaginary part of an
mpc
result. If the value is Default, then the value ofreal_prec
is used.
- imag_round
This attribute controls the rounding mode for the imaginary part of an
mpc
result. If the value is Default, then the value of thereal_round
attribute is used. Note: RoundAwayZero is not a valid rounding mode formpc
.
- inexact
This flag is not user controllable. It is automatically set if an inexact result is returned.
- invalid
This flag is not user controllable. It is automatically set if an invalid (Not-A-Number) result is returned.
- overflow
This flag is not user controllable. It is automatically set if a result overflowed to +/-Infinity and
trap_overflow
isFalse
.
- precision
This attribute controls the precision of an
mpfr
result. The precision is specified in bits, not decimal digits. The maximum precision that can be specified is platform dependent and can be retrieved withget_max_precision()
.Note: Specifying a value for precision that is too close to the maximum precision will cause the MPFR library to fail.
- real_prec
This attribute controls the precision of the real part of an
mpc
result. If the value is Default, then the value of theprecision
attribute is used.
- real_round
This attribute controls the rounding mode for the real part of an
mpc
result. If the value is Default, then the value of the round attribute is used. Note: RoundAwayZero is not a valid rounding mode formpc
.
- round
There are five rounding modes available to
mpfr
type:RoundAwayZero - The result is rounded away from 0.0.
RoundDown - The result is rounded towards -Infinity.
RoundToNearest - Round to the nearest value; ties are rounded to an even value.
RoundToZero - The result is rounded towards 0.0.
RoundUp - The result is rounded towards +Infinity.
- subnormalize
The usual IEEE-754 floating point representation supports gradual underflow when the minimum exponent is reached. The MFPR library does not enable gradual underflow by default but it can be enabled to precisely mimic the results of IEEE-754 floating point operations.
- trap_divzero
This attribute controls whether or not a
DivisionByZeroError
exception is raised if division by 0 occurs. TheDivisionByZeroError
is a sub-class of Python’sZeroDivisionError
.
- trap_erange
This attribute controls whether or not a
RangeError
exception is raised when certain operations are performed on NaN and/or Infinity values. Settingtrap_erange
toTrue
can be used to raise an exception if comparisons are attempted with a NaN.
- trap_inexact
This attribute controls whether or not an
InexactResultError
exception is raised if an inexact result is returned. To check if the result is greater or less than the exact result, check the rc attribute of thempfr
result.
- trap_invalid
This attribute controls whether or not an
InvalidOperationError
exception is raised if a numerical result is not defined. A special NaN (Not-A-Number) value will be returned if an exception is not raised. TheInvalidOperationError
is a sub-class of Python’sValueError
.For example, gmpy2.sqrt(-2) will normally return mpfr(‘nan’). However, if
allow_complex
is set toTrue
, then anmpc
result will be returned.
- trap_overflow
If set to
False
, a result that is larger than the largest possiblempfr
given the current exponent range will be replaced by +/-Infinity. If set toTrue
, anOverflowResultError
exception is raised.
- trap_underflow
If set to
False
, a result that is smaller than the smallest possiblempfr
given the current exponent range will be replaced by +/-0.0. If set toTrue
, anUnderflowResultError
exception is raised.
- underflow
This flag is not user controllable. It is automatically set if a result underflowed to +/-0.0 and
trap_underflow
isFalse
.
Context Functions
- gmpy2.ieee(size, /, subnormalize=True) context
Return a new context corresponding to a standard IEEE floating point format. The supported sizes are 16, 32, 64, 128, and multiples of 32 greater than 128.
Exceptions
- exception gmpy2.RangeError
- exception gmpy2.InexactResultError
- exception gmpy2.OverflowResultError
- exception gmpy2.UnderflowResultError
- exception gmpy2.InvalidOperationError
- exception gmpy2.DivisionByZeroError
Multiple-precision Reals
mpfr Type
- class gmpy2.mpfr(n=0, /, precision=0)
- class gmpy2.mpfr(n, /, precision, context)
- class gmpy2.mpfr(s, /, precision=0, base=0)
- class gmpy2.mpfr(s, /, precision, base, context)
Return a floating-point number after converting a numeric value n or a string s made of digits in the given base.
A string can be with fraction-part (with a period as a separator) and/or exponent-part with an exponent marker ‘e’ or ‘E’ for bases up to 10, else ‘@’ in any base. In bases 2 and 16, the exponent prefix can also be ‘p’ or ‘P’, in which case the exponent indicates a multiplication by a power of 2 instead of the base. The value of an exponent is always written in base 10. The fractional-part digits are parsed the same as the
mpz
type constructor does and both the whole number and exponent-part optionally can be preceded by ‘+’ or ‘-’. Every input, accepted by thefloat
type constructor or thefloat.fromhex
method is also accepted.If a precision greater than or equal to 2 is specified, then it is used. A precision of 0 (the default) implies the precision of either the specified context or the current context is used. A precision of 1 minimizes the loss of precision by following these rules:
If n is a radix-2 floating point number, then the full precision of n is retained.
If n is an integer, then the precision is the bit length of the integer.
- __format__(fmt) str
Return a Python string by formatting ‘x’ using the format string ‘fmt’. A valid format string consists of:
optional alignment code:
‘<’ -> left shifted in field ‘>’ -> right shifted in field ‘^’ -> centered in field
optional leading sign code
‘+’ -> always display leading sign ‘-’ -> only display minus for negative values ‘ ‘ -> minus for negative values, space for positive values
optional width.precision
optional rounding mode:
‘U’ -> round toward plus Infinity ‘D’ -> round toward minus Infinity ‘Y’ -> round away from zero ‘Z’ -> round toward zero ‘N’ -> round to nearest
optional conversion code:
‘a’,’A’ -> hex format ‘b’ -> binary format ‘e’,’E’ -> scientific format ‘f’,’F’ -> fixed point format ‘g’,’G’ -> fixed or float format
The default format is ‘.6f’.
- as_integer_ratio() tuple[mpz, mpz]
Return the exact rational equivalent of an
mpfr
. Value is atuple
for compatibility with Python’sfloat.as_integer_ratio
.
- as_simple_fraction(precision=0) mpq
Return a simple rational approximation to x. The result will be accurate to ‘precision’ bits. If ‘precision’ is 0, the precision of ‘x’ will be used.
- conjugate() mpz
Return the conjugate of x (which is just a new reference to x since x is not a complex number).
- digits(base=10, prec=0, /) tuple[str, int, int]
Returns up to ‘prec’ digits in the given base. If ‘prec’ is 0, as many digits that are available are returned. No more digits than available given x’s precision are returned. ‘base’ must be between 2 and 62, inclusive. The result is a three element
tuple
containing the mantissa, the exponent, and the number of bits of precision.
- is_finite() bool
Return
True
if x is an actual number (i.e. non NaN or Infinity). If x is anmpc
, returnTrue
if both x.real and x.imag are finite.
- is_infinite() bool
Return
True
if x is +Infinity or -Infinity. If x is anmpc
, returnTrue
if either x.real or x.imag is infinite. Otherwise returnFalse
.
- is_zero() bool
Return
True
if x is equal to 0. If x is anmpc
, returnTrue
if both x.real and x.imag are equal to 0.
- imag
imaginary component
- precision
precision in bits
- rc
return code
- real
real component
mpfr Functions
- gmpy2.check_range(x, /) mpfr
Return a new
mpfr
with exponent that lies within the current range of emin and emax.
- gmpy2.cmp(x, y, /) int
Return -1 if x < y; 0 if x = y; or 1 if x > y. Both x and y must be integer, rational or real. Note: 0 is returned (and exception flag set) if either argument is NaN.
- gmpy2.const_catalan(precision=0) mpfr
Return the catalan constant using the specified precision. If no precision is specified, the default precision is used.
- gmpy2.const_euler(precision=0) mpfr
Return the euler constant using the specified precision. If no precision is specified, the default precision is used.
- gmpy2.const_log2(precision=0) mpfr
Return the log2 constant using the specified precision. If no precision is specified, the default precision is used.
- gmpy2.const_pi(precision=0) mpfr
Return the constant pi using the specified precision. If no precision is specified, the default precision is used.
- gmpy2.degrees(x, /) mpfr
Convert angle x from radians to degrees. Note: In rare cases the result may not be correctly rounded.
- gmpy2.factorial(n, /) mpfr
Return the floating-point approximation to the factorial of n.
See
fac()
to get the exact integer result.
- gmpy2.get_exp(x, /) int
Return the exponent of x. Returns 0 for NaN or Infinity and sets the
context.erange
flag of the current context and will raise an exception ifcontext.trap_erange
is set.
- gmpy2.inf(n, /) mpfr
Return an
mpfr
initialized to Infinity with the same sign as n. If n is not given, +Infinity is returned.
- gmpy2.is_finite(x, /) bool
Return
True
if x is an actual number (i.e. non NaN or Infinity). If x is anmpc
, returnTrue
if both x.real and x.imag are finite.
- gmpy2.is_infinite(x, /) bool
Return
True
if x is +Infinity or -Infinity. If x is anmpc
, returnTrue
if either x.real or x.imag is infinite. Otherwise returnFalse
.
- gmpy2.jn(n, x, /) mpfr
Return the first kind Bessel function of order n of x. Note: the order of the arguments changed in gmpy2 2.2.0a2
- gmpy2.lgamma(x, /) tuple[mpfr, int]
Return a
tuple
containing the logarithm of the absolute value of gamma(x) and the sign of gamma(x)
- gmpy2.maxnum(x, y, /) mpfr
Return the maximum number of x and y. If x and y are not
mpfr
, they are converted tompfr
. The result is rounded to match the current context. If only one of x or y is a number, then that number is returned.
- gmpy2.minnum(x, y, /) mpfr
Return the minimum number of x and y. If x and y are not
mpfr
, they are converted tompfr
. The result is rounded to match the current context. If only one of x or y is a number, then that number is returned.
- gmpy2.modf(x, /) tuple[mpfr, mpfr]
Return a
tuple
containing the integer and fractional portions of x.
- gmpy2.mpfr_grandom(random_state, /) tuple[mpfr, mpfr]
Return two random numbers with gaussian distribution.
- gmpy2.mpfr_nrandom(random_state, /)
Return a random number with gaussian distribution.
- gmpy2.radians(x, /) mpfr
Convert angle x from degrees to radians. Note: In rare cases the result may not be correctly rounded.
- gmpy2.reldiff(x, y, /) mpfr
Return the relative difference between x and y. Result is equal to abs(x-y)/x.
- gmpy2.remainder(x, y, /) mpfr
Return x - n*y where n is the integer quotient of x/y, rounded to the nearest integer and ties rounded to even.
- gmpy2.remquo(x, y, /) tuple[mpfr, int]
Return a
tuple
containing the remainder(x,y) and the low bits of the quotient.
- gmpy2.rint_ceil(x, /) mpfr
Return x rounded to the nearest integer by first rounding to the next higher or equal integer and then, if needed, using the current rounding mode.
- gmpy2.rint_floor(x, /) mpfr
Return x rounded to the nearest integer by first rounding to the next lower or equal integer and then, if needed, using the current rounding mode.
- gmpy2.rint_round(x, /) mpfr
Return x rounded to the nearest integer by first rounding to the nearest integer (ties away from 0) and then, if needed, using the current rounding mode.
- gmpy2.rint_trunc(x, /) mpfr
Return x rounded to the nearest integer by first rounding towards zero and then, if needed, using the current rounding mode.
- gmpy2.root(x, n, /) mpfr
Return n-th root of x. The result always an
mpfr
. Note: not IEEE 754-2008 compliant; result differs when x = -0 and n is even. Seerootn()
.
- gmpy2.rootn(x, n, /) mpfr
Return n-th root of x. The result always an
mpfr
. Note: this is IEEE 754-2008 compliant version ofroot()
.
- gmpy2.round2(x, n=0, /) mpfr
Return x rounded to n bits. Uses default precision if n is not specified. See
round_away()
to access the mpfr_round() function of the MPFR.
- gmpy2.round_away(x, /) mpfr
Return an
mpfr
that is x rounded to the nearest integer, with ties rounded away from 0.
- gmpy2.set_exp(x, n, /) mpfr
Set the exponent of x to n. If n is outside the range of valid exponents,
set_exp()
will set thecontext.erange
flag of the current context and either return the original value or raise an exception ifcontext.trap_erange
is set.
- gmpy2.sinh_cosh(x, /) tuple[mpfr, mpfr]
Return a
tuple
containing the hyperbolic sine and cosine of x.
- gmpy2.trunc(x, /) mpfr
Return an
mpfr
that is x truncated towards 0. Same as x.floor() if x>=0 or x.ceil() if x<0.
- gmpy2.yn(n, x, /) mpfr
Return the second kind Bessel function of order n of x. Note: the order of the arguments changed in gmpy2 2.2.0a2
- gmpy2.zero(n, /) mpfr
Return an
mpfr
initialized to 0.0 with the same sign as n. If n is not given, +0.0 is returned.
- gmpy2.get_max_precision() int
Return the maximum bits of precision that can be used for calculations. Note: to allow extra precision for intermediate calculations, avoid setting precision close the maximum precision.
- gmpy2.can_round(b, err, rnd1, rnd2, prec, /) bool
Let b be an approximation to an unknown number x that is rounded according to rnd1. Assume the b has an error at most two to the power of E(b)-err where E(b) is the exponent of b. Then return
True
if x can be rounded correctly to prec bits with rounding mode rnd2.
Multiple-precision Complex
mpc Type
- class gmpy2.mpc(c=0, /, precision=0)
- class gmpy2.mpc(c=0, /, precision, context)
- class gmpy2.mpc(real, /, imag=0, precision=0)
- class gmpy2.mpc(real, /, imag, precision, context)
- class gmpy2.mpc(s, /, precision=0, base=10)
- class gmpy2.mpc(s, /, precision, base, context)
Return a complex floating-point number constructed from a numeric value c or from a pair of two non-complex numbers real and imag or from a string s made of digits in the given base.
A string can be possibly with real-part and/or imaginary-part (that have ‘j’ as a suffix), separated by ‘+’ and parsed the same as the
mpfr
constructor does (but the base must be up to 36).The precision can be specified by either a single number that is used for both the real and imaginary components, or as a pair of different precisions for the real and imaginary components. For every component, the meaning of its precision value is the same as in the
mpfr
type constructor.- __format__(fmt) str
Return a Python string by formatting ‘x’ using the format string ‘fmt’. A valid format string consists of:
optional alignment code:
‘<’ -> left shifted in field ‘>’ -> right shifted in field ‘^’ -> centered in field
optional leading sign code
‘+’ -> always display leading sign ‘-’ -> only display minus for negative values ‘ ‘ -> minus for negative values, space for positive values
optional width.real_precision.imag_precision
optional rounding mode:
‘U’ -> round toward plus infinity ‘D’ -> round toward minus infinity ‘Z’ -> round toward zero ‘N’ -> round to nearest
optional output style:
‘P’ -> Python style, 1+2j, (default) ‘M’ -> MPC style, (1 2)
optional conversion code:
‘a’,’A’ -> hex format ‘b’ -> binary format ‘e’,’E’ -> scientific format ‘f’,’F’ -> fixed point format ‘g’,’G’ -> fixed or scientific format
The default format is ‘f’.
- digits(base=10, prec=0, /) tuple[tuple[str, int, int], tuple[str, int, int]]
Returns up to ‘prec’ digits in the given base. If ‘prec’ is 0, as many digits that are available given c’s precision are returned. ‘base’ must be between 2 and 62. The result consists of 2 three-element tuples that contain the mantissa, exponent, and number of bits of precision of the real and imaginary components.
- is_finite() bool
Return
True
if x is an actual number (i.e. non NaN or Infinity). If x is anmpc
, returnTrue
if both x.real and x.imag are finite.
- is_infinite() bool
Return
True
if x is +Infinity or -Infinity. If x is anmpc
, returnTrue
if either x.real or x.imag is infinite. Otherwise returnFalse
.
- is_zero() bool
Return
True
if x is equal to 0. If x is anmpc
, returnTrue
if both x.real and x.imag are equal to 0.
- imag
imaginary component
- precision
precision in bits
- rc
return code
- real
real component
mpc Functions
- gmpy2.is_zero(x, /) bool
Return
True
if x is equal to 0. If x is anmpc
, returnTrue
if both x.real and x.imag are equal to 0.
- gmpy2.mpc_random(random_state, /) mpc
Return uniformly distributed number in the unit square [0,1]x[0,1].
- gmpy2.norm(x, /) mpfr
Return the norm of a complex x. The norm(x) is defined as x.real**2 + x.imag**2. abs(x) is the square root of norm(x).
- gmpy2.polar(x, /) tuple[mpfr, mpfr]
Return the polar coordinate form of a complex x that is in rectangular form.
- gmpy2.rect(r, phi, /) mpc
Return the rectangular coordinate form of a complex number that is given in polar form.
Generic Functions
Miscellaneous Functions
- gmpy2.from_binary(bytes, /) mpz | xmpz | mpq | mpfr | mpc
Return a Python object from a byte sequence created by
to_binary()
.
- gmpy2.random_state(seed=0, /) object
Return new object containing state information for the random number generator. An optional integer can be specified as the seed value.
- gmpy2.to_binary(x, /) bytes
Return a Python byte sequence that is a portable binary representation of a gmpy2 object x. The byte sequence can be passed to
from_binary()
to obtain an exact copy of x’s value. Raises aTypeError
if x is not a gmpy2 object.
Cython usage
The gmpy2 module provides a C-API that can be conveniently used from Cython. All types and functions are declared in the header gmpy2.pxd that is installed automatically in your Python path together with the library.
Initialization
In order to use the C-API you need to make one call to the function void import_gmpy2(void).
Types
The types mpz
, mpq
, mpfr
and mpc
are
declared as extension types in gmpy2.pxd. They correspond respectively to the C
structures MPZ_Object, MPQ_Object, MPFR_Object and MPC_Object.
Fast type checking can be done with the following C functions
- bint MPZ_Check(object)
equivalent to isinstance(obj, mpz)
- bint MPQ_Check(object)
equivalent to isinstance(obj, mpq)
- bint MPFR_Check(object)
equivalent to isinstance(obj, mpfr)
- bint MPC_Check(object)
equivalent to isinstance(obj, mpc)
Object creation
To create a new gmpy2 types there are four basic functions
- mpz GMPy_MPZ_New(void * ctx)
create a new mpz object from a given context ctx
- mpq GMPy_MPQ_New(void * ctx)
create a new mpq object from a given context ctx
- mpfr MPFR_New(void * ctx, mpfr_prec_t prec)
create a new mpfr object with given context ctx and precision prec
- mpc MPC_New(void * ctx, mpfr_prec_t rprec, mpfr_prec_t iprec)
create a new mpc object with given context ctx, precisions rprec and iprec of respectively real and imaginary parts
The context can be set to NULL and controls the default behavior (e.g. precision).
The gmpy2.pxd header also provides convenience macro to wrap a (copy of) a mpz_t, mpq_t, mpfr_t or a mpc_t object into the corresponding gmpy2 type.
- mpz GMPy_MPZ_From_mpz(mpz_srcptr z)
return a new mpz object with a given mpz_t value z
- mpq GMPy_MPQ_From_mpq(mpq_srcptr q)
return a new mpq object from a given mpq_t value q
- mpq GMPy_MPQ_From_mpz(mpz_srcptr num, mpz_srcptr den)
return a new mpq object with a given mpz_t numerator num and mpz_t denominator den
- mpfr GMPy_MPFR_From_mpfr(mpfr_srcptr x)
return a new mpfr object with a given mpfr_t value x
- mpc GMPy_MPC_From_mpc(mpc_srcptr c)
return a new mpc object with a given mpc_t value c
- mpc GMPy_MPC_From_mpfr(mpfr_srcptr re, mpfr_srcptr im)
return a new mpc object with a given mpfr_t real part re and mpfr_t imaginary part im
Access to the underlying C type
Each of the gmpy2 objects has a field corresponding to the underlying C type. The following functions give access to this field
mpz_t MPZ(mpz)
mpq_t MPQ(mpq)
mpfr_t MPFR(mpfr)
mpc_t MPC(mpc)
Compilation
The header gmpy2.pxd as well as the C header gmpy2.h from which it depends are installed in the Python path. In order to make Cython and the C compiler aware of the existence of these files, the Python path should be part of the include directories.
Recall that import_gmpy2() needs to be called before any other function of the C-API.
Here is a minimal example of a Cython file test_gmpy2.pyx:
"A minimal cython file test_gmpy2.pyx"
from gmpy2 cimport *
cdef extern from "gmp.h":
void mpz_set_si(mpz_t, long)
import_gmpy2() # needed to initialize the C-API
cdef mpz z = GMPy_MPZ_New(NULL)
mpz_set_si(MPZ(z), -7)
print(z + 3)
The corresponding setup.py is given below.
"A minimal setup.py for compiling test_gmpy2.pyx"
import sys
from setuptools import Extension, setup
from Cython.Build import cythonize
ext = Extension("test_gmpy2", ["test_gmpy2.pyx"],
include_dirs=sys.path, libraries=['gmp', 'mpfr', 'mpc'])
setup(name="cython_gmpy_test",
ext_modules=cythonize([ext], include_path=sys.path))
With these two files in the same repository, you should be able to compile your module using
$ python setup.py build_ext --inplace
For more about compilation and installation of cython files and extension modules, please refer to the official documentation of Cython and distutils.
Conversion Methods
A python object could interact with gmpy2 if it implements one of the following methods:
__mpz__
: return an object of typempz
.__mpq__
: return an object of typempq
.__mpfr__
: return an object of typempfr
.__mpc__
: return an object of typempc
.
Implementing on of these methods allow gmpy2 to convert a python object into a gmpy2 type. Example:
>>> from gmpy2 import mpz
>>> class CustInt:
... def __init__(self, x):
... self.x = x
... def __mpz__(self):
... return mpz(self.x)
...
>>> ci = CustInt(5)
>>> z = mpz(ci); z
mpz(5)
>>> type(z)
<class 'gmpy2.mpz'>
Arithmetic operations
gmpy2 allow arithmetic operations between gmpy2 numbers and objects with conversion methods. Operation with object that implements floating conversion and exact conversion methods are not supported. That means that only the following cases are supported:
An integer type have to implement
__mpz__
A rational type have to implement
__mpq__
and can implement__mpz__
A real type have to implement
__mpfr__
A complex type have to implement
__mpc__
and can implement__mpfr__
Examples:
>>> import gmpy2
>>> from gmpy2 import mpz, mpq, mpfr, mpc
>>> gmpy2.set_context(gmpy2.context())
>>> class Q:
... def __mpz__(self): return mpz(1)
... def __mpq__(self): return mpq(3,2)
>>> q = Q()
>>> mpz(2) + q
mpq(7,2)
>>> mpq(1,2) * q
mpq(3,4)
>>> mpfr(10) * q
mpfr('15.0')
Release Notes
Changes in gmpy2 2.2.0
Remove support for versions of Python < 3.7. (skirpichev)
Support more modern build tools. (skirpichev)
Use contextvars to manage gmpy2 contexts. (casevh)
_mpmath functions now use vectorcall protocol. (casevh)
Many documentation updates. (skirpichev)
Add
mpz.as_integer_ratio()
/mpz.to_bytes()
andmpz.from_bytes()
. (skirpichev)Add
is_probab_prime()
to directly expose the GMP behavior. (skirpichev)Expose
context
type. (skirpichev)Correct error in
is_strong_bpsw_prp()
. (casevh)Added
prev_prime()
when GMP >= 6.3. (sethtroisi)Change argument order of
jn()
andyn()
to match MPFR. (casevh)Fix documentation and code for
is_extra_strong_lucas_prp()
. (casevh)
Changes in gmpy2 2.1.5
Version bump to fix wheel issues. No code changes.
Changes in gmpy2 2.1.4
Version bump to fix wheel issues. No code changes.
Changes in gmpy2 2.1.3
Fix mpz(-3).is_prime().
Add powmod_sec().
Fix mpfr(‘inf’) and mpfr(‘nan’) if subnormalization is enabled.
powmod() and powmod_sec() release the GIL.
Fix error messages for iroot(x,n) for large n.
Add powmod_base_list() and powmod_exp_list() (experimental).
Fix gmpy2.mpq(mpq, int).
Fix issues with INF, NAN, and mpfr(“-0”) when subnormalization is True
Changes in gmpy2 2.1.2
Code cleanup.
Support Apple Silicon binary wheels.
is_prime(-2) now returns False. Issue #312.
Changes in gmpy2 2.1.1
Code cleanup.
Properly return NOTIMPLEMENTED for unsupported arguments in
**
. Issue #319.
Changes in gmpy2 2.1.0
Improvements to setup.py.
Add thread-safe contexts.
MPFR and MPC are now required.
Invalid Operation exception now raised for addition, etc.
inverse() now raises exception if inverse does not exist.
Add context methods.
Major code refactoring required to properly support thread-safe contexts.
`` __str__`` and
__repr__
no longer append “L” on Python 2.mpq(mpfr) now returns the exact result.
Fix repr(mpc) for precision >325 bits.
Intermediate conversions of Integer to mpfr are now done with the full precision of the Integer.
Remove support for interaction with Decimal type.
No longer attempt to override the memory allocation functions.
Register gmpy2 types into the numeric tower.
mpz(x) call int(x) if mpz() does not know how to convert x directly.
Convert
mpz
to a type using__new__
instead of a factory function.Bug fix for
<<small mpfr>> ** <<small Python integer>>
.Compile with Python 3.11.
Changes in gmpy2 2.1.0rc2
Documentation updates.
Improvements to build environment.
Changes in gmpy2 2.1.0rc1
Changes in gmpy2 2.1.0b6
Improve argument type processing by saving type information to decrease the number of type check calls. Especially helpful for
mpfr
andmpc
types. (Not complete but common operations are done.)Added limited support for releasing the GIL; disabled by default; see
context.allow_release_gil
.Refactored handling of inplace operations for
mpz
andxmpz
types; inplace operations onxmpz
will only return anxmpz
result.Refactored handling of conversion to C integer types. Some exception types changes to reflect Python types.
gcd()
andlcm()
now support more than two arguments to align with the corresponding functions in the math module.
Changes in gmpy2 2.1.0b5
Avoid MPFR bug in mfr_fac_ui (
factorial()
) on platforms where long is 32-bits and argument is >= 44787929.Fixed testing bugs with Python 2.7.
Fixed
mpz(0)
to C long or long long.Fixed incorrect results in
f2q()
.Adjust test suite to reflect changes in output in MPFR 4.1.0.
Changes in gmpy2 2.1.0b4
Fix comparisons with
mpq
and custom rational objects.Fixes for some uncommon integer conversions scenarios.
Changes in gmpy2 2.1.0b3
Version bump only.
Changes in gmpy2 2.1.0b2
Many bug fixes.
Changes in gmpy2 2.1.0b1
Changes in gmpy2 2.1.a05
Added
root_of_unity()
.
Changes in gmpy2 2.1.0a4
Fix issue 204; missing file for Cython.
Additional support for MPFR 4
Changes in gmpy2 2.1.0a3
Updates to
setup.py
.Initial support for MPFR4
Add
mpfr_nrandom()
mpfr_grandom()
now calls nrandom twice; may return different values versus MPFR3.Add
rootn()
; same asroot()
except different sign when taking even root of -0.0.
Changes in gmpy2 2.1.0a2
Revised build process.
Removal of unused code/macros.
Cleanup of Cython interface.
Changes in gmpy2 2.1.0a1
Thread-safe contexts are now supported. Properly integrating thread-safe contexts required an extensive rewrite of almost all internal functions.
MPFR and MPC are now required. It is no longer possible to build a version of gmpy2 that only supports the GMP library.
The function
inverse()
now raises an exception if the inverse does not exist.Context methods have been added for MPFR/MPC related functions.
A new context option (
rational_division
) has been added that changes the behavior of integer division involvingmpz
instances to return a rational result instead of a floating point result.gmpy2 types are now registered in the numeric tower of the
numbers
module.In previous versions of gmpy2,
mpz()
was a factory function that returned anmpz
instance. It is now an actual type. The same is true for the other gmpy2 types.If a Python object has an
__mpz__
method, it will be called byempz()
to allow an unrecognized type to be converted to an mpz instance. The same is true for the other gmpy2 types.A new C-API and Cython interface has been added.
Changes in gmpy2 2.0.4
Fix
bit_scan0()
for negative values.Changes to
setup.py
to allow static linking.Fix performance regression with mpmath and Python 3.
Changes in gmpy2 2.0.3
Changes in gmpy2 2.0.2
Rebuild Windows binary installers due to MPIR 2.6.0 bug in
next_prime()
.Another fix for
is_extra_strong_lucas_prp()
.
Changes in gmpy2 2.0.1
Updated
setup.py
to work in more situations.Corrected exception handling in basic operations with
mpfr
type.Correct
InvalidOperation
exception not raised in certain circumstances.invert()
now raises an exception if the modular inverse does not exist.Fixed internal exception in
is_bpsw_prp()
andis_strong_bpsw_prp()
.Updated
is_extra_strong_lucas_prp()
to latest version.
Changes in gmpy2 2.0.0
Fix segmentation fault in
_mpmath_normalize()
(an undocumented helper function for mpmath). (casevh)Fix issues when compiled without support for MPFR. (casevh)
Conversion of too large an
mpz
tofloat
now raisesOverflowError
instead of returninginf
. (casevh)The build and install process (i.e.
setup.py
) has been completely rewritten. See the Installation section for more information. (casevh)get_context()
no longer accepts keyword arguments. (casevh)
Known issues in gmpy2 2.0.0
The test suite is still incomplete.
Changes in gmpy2 2.0.0b4
Added
__ceil__()
,__floor__()
,__trunc__()
, and__round__()
methods tompz
andmpq
types. (casevh)Added
__complex__()
tompc
type. (casevh)round(mpfr)
now correctly returns anmpz
type. (casevh)Add mpz.denominator and mpz.numerator. (casevh)
If no arguments are given to
mpz
,mpq
,mpfr
,mpc
, andxmpz
, return 0 of the appropriate type. (casevh)Fix broken comparison between
mpz
andmpq
whenmpz
is on the left. (casevh)Added
__sizeof__()
to all types. Note:sys.getsizeof()
calls__sizeof__()
to get the memory size of a gmpy2 object. The returned value reflects the size of the allocated memory which may be larger than the actual minimum memory required by the object. (casevh)
Known issues in gmpy2 2.0.0b4
The new test suite (
test/runtest.py
) is incomplete and some tests fail on Python 2.x due to formatting issues.
Changes in gmpy2 2.0.0b3
mp_version()
,mpc_version()
, andmpfr_version()
now return normal strings on Python 2.x instead of Unicode strings. (casevh)Fix warnings when shifting 32-bit integer by 32 bits. (casevh)
Faster conversion of the standard library
Fraction
type tompq
. (casevh)Consistently return
OverflowError
when convertinginf
. (casevh)Fix
mpz.__format__()
when the format code includes “#”. (casevh)Add
is_infinite()
and deprecateis_inf()
. (casevh)Add
is_finite()
and deprecateis_number()
. (casevh)Fixed the various
is_XXX()
tests when used withmpc
. (casevh)Fixed error handling with mpc(); mpc(1,”nan”) is properly handled. (casevh)
Added caching for
mpc
objects. (casevh)Faster code path for basic operation is both operands are
mpfr
ormpc
. (casevh)
Changes in gmpy2 2.0.0b2
Allow
xmpz
slice assignment to increase length ofxmpz
instance by specifying a value for stop. (casevh)Fixed reference counting bug in several
is_xxx_prp()
tests. (casevh)Added
iter_bits()
,iter_clear()
,iter_set()
methods toxmpz
. (casevh)Added
powmod()
for easy access to three argumentpow()
. (casevh)Removed
addmul()
andsubmul()
which were added in 2.0.0b1 since they are slower than just using Python code. (casevh)Bug fix in gcd_ext when both arguments are not
mpz
. (casevh)Added
ieee()
to create contexts for 32, 64, or 128 bitfloat
’s. (casevh)Bug fix in
context()
not settingemax
/emin
correctly if they had been changed earlier. (casevh)Contexts can be directly used in with statement without requiring
set_context()
/local_context()
sequence. (casevh)local_context()
now accepts an optional context. (casevh)
Changes in gmpy2 2.0.0b1
Rename to gmpy2 to allow backwards incompatible changes (casevh)
Renamed ‘mpf’ to ‘mpfr’ to reflect use of MPFR (casevh)
Renamed functions that manipulate individual bits to
bit_XXX()
to align withbit_length()
.Added caching for
mpq
. (casevh)Support changed hash function in Python 3.2. (casevh)
Add caching of the calculated hash value. (casevh)
Fix
mpq
formatting issue. (casevh)Add read/write bit access using slices to
xmpz
. (casevh)Add read-only bit access using slices to
mpz
. (casevh)Add
pack()
/unpack()
methods to split/join an integer into n-bit chunks. (casevh)Add support for MPFR (casevh)
Removed fcoform float conversion modifier. (casevh)
Add support for MPC. (casevh)
Added context manager. (casevh)
Allow building with just GMP/MPIR if MPFR not available. (casevh)
Allow building with GMP/MPIR and MPFR if MPC not available. (casevh)
Removed most instance methods in favor of gmpy2.function. The general guideline is that properties of an instance can be done via instance methods but functions that return a new result are done using gmpy2.function. (casevh)
Added
__ceil__()
,__floor__()
, and__trunc__()
methods since they are called bymath.ceil()
,math.floor()
, andmath.trunc()
. (casevh)Removed
gmpy2.pow()
to avoid conflicts. (casevh)Removed
gmpy2._copy()
and addedxmpz.copy()
. (casevh)Added support for
__format__()
. (casevh)Added
as_integer_ratio()
,as_mantissa_exp()
,as_simple_fraction()
. (casevh)Updated rich_compare. (casevh)
Require MPFR 3.1.0+ to get divby0 support. (casevh)
Updated random number generation support. (casevh)
Changed license to LGPL 3+. (casevh)
Added
lucasu()
,lucasu_mod()
,lucasv()
, andlucasv_mod()
. (casevh) Based on code contributed by David Cleaver.Added probable-prime tests. (casevh) Based on code contributed by David Cleaver.
Added
to_binary()
/from_binary()
. (casevh)Renamed
numdigits()
tonum_digits()
. (casevh)Added keyword precision to constants. (casevh)
Added
addmul()
andsubmul()
. (casevh)Added
__round__()
,round2()
,round_away()
formpfr
. (casevh)round()
is no longer a module level function. (casevh)Renamed module functions
min()/max()
tomin2()/max2()
. (casevh) No longer conflicts with builtinmin()
andmax()
Removed
set_debug()
and related functionality. (casevh)Removed mpf.setprec(), use mpf.round() (casevh)
Fix test compatibility with Python 3.1.2 and 3.2 (casevh)
Remove old random number functions, to be replaced later (casevh)
Remove tagoff option (casevh)
Debug messages only available if compiled with -DDEBUG (casevh)
Renamed context() -> local_context(), new_context() -> context() (casevh)
Added get_context() (casevh)
Changes in gmpy 1.11
Recognize True/False (bug in 1.10) (casevh)
Optimize argument handling (casevh)
Added caching for mpz (casevh)
Changes in gmpy 1.10
Remove dependancy on pymemcompat.h (casevh)
Remove callback (casevh)
Added support for -DMPIR to include MPIR instead of GMP (casevh)
Major code revisions to add support for Python 3.x (casevh)
Fixed bug in binary() and qbinary() (casevh)
Fixed bug in rich comparisons (casevh)
Added % and divmod support to mpq and mpf (casevh)
Changed memory allocation functions to use PyMem (casevh)
Removed small number interning (casevh)
Added tdivmod, cdivmod, and fdivmod (casevh)
Added more helper functions for mpmath (casevh)
Faster mpz<>PyLong conversion (casevh)
Faster hash(mpz) (casevh)
Changes in gmpy 1.04
Avoid GMP/mingw32 bug when converting very small floats to mpz. (casevh)
Significant performance improvement for long->mpz and mpz->long. (casevh)
Added “rich comparisons” to mpz, mpq and mpf types (aleaxit)
Added additional tests (casevh, aleaxit)
Fixed bug when converting very large mpz to str (casevh)
Faster conversion from mpz->binary and binary->mpz (casevh)
Added support for pickling (casevh)
Added divexact (casevh)
Fixed mpf comparisons by rounding mpf results when GMP returns a longer result. Added fround() (casevh)
Added bit_length (Thanks Mario Pernici)
Added helper functions for mpmath (casevh)
Faster conversion from mpq->binary and binary->mpq (casevh)
Recognize MPIR, mpir_version() (casevh)
Changes in gmpy 1.03
Fixed the bug that caused crashes on gmpy.mpf(float(‘inf’)) and other such conversions, implicit and explicit
Fixed a bug in get_zconst’s prototype affecting 64-bit machines, thanks to Gary Bunting
Fixed a bug in hashing on 64-bit systems. hash(long) now equals hash(mpz) for large values. (casevh)
Changed int() to return a long value instead of OverFlowError. Complies with PEP 237. (casevh)
Added support in setup.py for darwinports/macports build of GMP on MacOSX. (aleaxit)
Changes in gmpy 1.02
fix warning in comparison of mpq’s
added support of mpq(‘12.34’) [[string w/o a slash, but with a dot]]
fixes for 64-bit build (thanks to a patch by dmcooke)
added experimental support for decimal.Decimal (and user-coded types) via wider use of special conversion methods (if present) and their sly insertion on-the-fly into the decimal.Decimal class (!)
two bugfixes, thanks to Simon Burton
Brought back into C89 compliance (thanks to Chip Turner), had drifted to C99 (declarations in the middle of the code).
Python 2.5 support (Py_ssize_t, __index__) thanks to Chip Turner
Pushed coverage to 93.3% (missing only “sanity check” level error tests [mostly for out-of-memory conditions], output to stderr conditioned by global.debug, & a couple of very obscure cases)
Changes in gmpy 1.01
cleanups, ensure support for Python 2.4.1 on MacOSX 10.4/XCode 2.1 as well as Python 2.2 and 2.3 (on MacOSX and Linux)
fixed memory leak on divm (thanks to mensanator@aol.com)
fixed bug on mpq(‘123’) [[str2mpq on string w/o a slash]]
added floordiv and truediv operators, and tests for them
NOT tested on GMP 3 (have none left around…), ONLY on GMP 4.*
Changes in gmpy 1.0
minor cleanups, ensure support for Python 2.3
fixed misdiagnosis of some argument counts in macro
SELF_ONE_ARG_CONVERTED (tx to Paul Rubin!)
Changes in gmpy 0.9
change ValueError to OverflowError for ‘too-large’ errors
fix bug in mpq_pow (negative base, exp. with odd denominator) (fix now corrected – _even_ denominator is the error!)
fixed gcc warnings reported by K. Briggs
support GMP 4 (but added no GMP4-only functionality yet)
updated tests to 0.9, better coverage
Changes in gmpy 0.8
(again, requests & suggestions by great Pearu!)
raise test coverage 72.5% -> 90.0%
introduced callbacks (not documented/tested for now; Pearu will test/support/document in PySymbolic)
some errors went undiagnosed, caused crash: now fixed
workaround for GMP bug(?s?) in mpz_fits_… (?)
added exposure of mpf_ sqrt and pow_ui
Changes in gmpy 0.7
Good feedback from Keith Briggs, some advice from Tim Peters and Fred Lundh — thanks all!
fixed bug of ‘”%d” where “%ld” was meant’ in many places and other sundry minor warnings given by gcc
fixed hash (delegating to Python) so mp[nqz](x) will produce the same value as hash(x) for any Python number x
workaround for GMP 3.1.1 bug, mpz_root wrongly returning ‘exact’ for non-exact root if dest==source, which stopped needed value-error for inexact mpq**mpq operations
determined correct ‘actual precision’ of floats
explicitly stored precision with binary-form mpf’s
extended explicit-bits request to all ->mpf operations (good in itself, plus, preparing for future MPFR)
removed the limitation of no binary-form for <0 mpz
introduced macros to parse args, for conciseness
Changes in gmpy 0.6
(lots of good ideas from Pearu once more!-)
fixed silly bugs in kronecker and mpq_abs
gmpy-level workaround for scan0/scan1 bugs (?) in gmp 3.1.1
added qdiv; anynum->mpq substituted for all such conversions (also anynum->mpz and anynum->mpf by analogy, with care!)
added global.fcoform for optional use of intermediate string in float2mpf (used for any float->mpf conversion)
added set_fcoform function for global.fcoform access
general cleanup of sources; added alloca for msvc++; - many sundry minor bugfixes & uniformization; - a little useful refactoring (more would be good…)
added caching of mpq objects
power for mpq
stern-brocot algorithm for mpf->mpq (also exposed as f2q) - also used for float->mpq - with stricter tracking of mpf’s requested-precision - added getrprec method to mpf, getrprec module-function
exposed ceil, floor and trunc methods/functions for mpf’s
changed a couple exceptions from value to zerodivision
added ‘qual’ and ‘floa’ options to gmpy.rand
Changes in gmpy 0.5
added jacobi, legendre, kronecker
added random-number generation, seed set/save, shuffling
added mpq (at last!-)
Changes in gmpy 0.4
split gmpy.c/gmpy.h introducing C-API interface (Pearu’s suggestion)
cleanup some casts using Pearu’s new macros
further cache-tweaks at Pearu’s suggestion (macros introduced)
added sign (Pearu’s request), getbit, setbit
added docstrings
renamed copy functions to start with _ (‘internal, private’)
added .comb as a synonym of .bincoef
Changes in gmpy 0.3
performance tweaks via mpz-caching & fixed-constants
added get/set functions for zcache, zco min/max
added get-only function for versions (of gmp, and of gmpy)
removed all ‘traces’ of mutability (to be re-done… much later!)
cleaned up all of the mpz_cmp_ui(X,0) to mpz_sgn(X)
cleaned up Py_BuildValue usage (N vs O, explicit-() for tuples)
added numdigits, lowbits, root, next_prime, invert, popcount,
hamdist, scan0, scan1
renamed bin to bincoef
Changes in gmpy 0.2
15 Nov 2000
pre-alpha: bugfixes re formatting (tx, Peanu!)
no tags on oct() and hex() of mpz’s
insert ‘tagoff’ in options (gmpy.mpz() vs mpz() in repr) (for Peanu!)
speedups for _nonzero & _cmp (tx, Peanu!)
slight speedup (7/8%?) for excess reallocs 4<->8 bytes (Peanu’s help!)
added copy/fcopy; bin; fib; remove
Changes in gmpy 0.1
6 Nov 2000
pre-alpha — first placed on sourceforge