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.
gmpy2 requires CPython 3.7 or above. Pre-compiled binary wheels
are available on PyPI. You can install latest release with pip:
or some specific version with:
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:
Start by importing the contents of the package with:
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'
- 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'.
- 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 and
bytearray 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 return False.
- is_prime(n=25,
/) -> bool
- Return True if x is probably prime, else False 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, an
OverflowError 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
- 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_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.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_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.fac(n,
/) -> mpz
- Return the exact factorial of n.
See factorial(n) to get the floating-point approximation.
- gmpy2.is_prime(x,
n=25, /) -> bool
- Return True if x is probably prime, else False 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.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_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.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_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.
- gmpy2.unpack(x,
n, /) -> list
- Unpack an integer x into a list of n-bit values. Equivalent to repeated
division by 2**n. Raises error if x is negative.
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.
The ability to change an xmpz object in-place allows for
efficient and rapid bit manipulation.
Individual bits can be set or cleared:
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))
- 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 or False 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
underlying xmpz 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
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 the is_strong_prp() test with
base 2 and the is_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:
Then an Euler probable prime requires:
a**((n-1)/2) == (a/n) (mod n)
where (a/n) is the Jacobi symbol.
- 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_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 the
is_strong_prp() test with base and the
is_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.
- gmpy2.lucasv(p,
q, k, /) -> mpz
- Return the k-th element of the Lucas V sequence defined by p,q. p*p - 4*q
must not equal 0; k must be greater than or equal to 0.
- gmpy2.lucasv_mod(p,
q, k, n, /) -> mpz
- Return the k-th element of the Lucas V 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.
- 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 the
Fraction 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 the float constructor is also accepted.
- 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.
- 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
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().
- 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 overridden by keyword arguments.
- degrees(x, /)
-> mpfr
- Convert angle x from radians to degrees. Note: In rare cases the result
may not be correctly rounded.
- 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 an mpc, return True if both x.real and x.imag are
finite.
- is_infinite(x,
/) -> bool
- Return True if x is +Infinity or -Infinity. If x is an mpc,
return True if either x.real or x.imag is infinite. Otherwise
return False.
- is_zero(x, /)
-> bool
- Return True if x is equal to 0. If x is an mpc, return
True 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
- maxnum(x, y, /)
-> mpfr
- Return the maximum number of x and y. If x and y are not mpfr, they
are converted to mpfr. 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 to mpfr. The result is rounded to match the specified
context. If only one of x or y is a number, then that number is
returned.
- 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).
- 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.
- 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.
- rint(x, /) ->
mpfr
- Return x rounded to the nearest integer using the context rounding
mode.
- 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. See
context.rootn().
- rootn(x, n, /)
-> mpfr
- Return n-th root of x. The result always an mpfr. Note: this is
IEEE 754-2008 compliant version of context.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.
- 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 an mpfr result would normally not be possible.
- allow_release_gil
- If set to True, many mpz and mpq 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
with get_emax_max().
- emin
- This attribute controls the minimum allowed exponent of an mpfr
result. The minimum exponent is platform dependent and can be retrieved
with get_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 of
real_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 the
real_round attribute is used. Note: RoundAwayZero is not a valid
rounding mode for mpc.
- 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 is False.
- 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 with
get_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 the precision
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 for
mpc.
- 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. The
DivisionByZeroError is a sub-class of Python’s
ZeroDivisionError.
- trap_erange
- This attribute controls whether or not a RangeError exception is
raised when certain operations are performed on NaN and/or Infinity
values. Setting trap_erange to True 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
the mpfr 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. The
InvalidOperationError is a sub-class of Python’s
ValueError.
For example, gmpy2.sqrt(-2) will normally return
mpfr(‘nan’). However, if allow_complex is set to
True, then an mpc result will be returned.
- trap_overflow
- If set to False, a result that is larger than the largest possible
mpfr given the current exponent range will be replaced by
+/-Infinity. If set to True, an OverflowResultError
exception is raised.
- trap_underflow
- If set to False, a result that is smaller than the smallest
possible mpfr given the current exponent range will be replaced by
+/-0.0. If set to True, an UnderflowResultError exception is
raised.
- underflow
- This flag is not user controllable. It is automatically set if a result
underflowed to +/-0.0 and trap_underflow is False.
- 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 the
float type constructor or the float.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:
- 1.
- If n is a radix-2 floating point number, then the full precision of n is
retained.
- 2.
- 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'.
- 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 an mpc, return True if both x.real and x.imag are
finite.
- is_infinite()
-> bool
- Return True if x is +Infinity or -Infinity. If x is an mpc,
return True if either x.real or x.imag is infinite. Otherwise
return False.
- is_zero() ->
bool
- Return True if x is equal to 0. If x is an mpc, return
True if both x.real and x.imag are equal to 0.
- 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.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 if context.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 an mpc, return True 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 an mpc,
return True if either x.real or x.imag is infinite. Otherwise
return False.
- 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.maxnum(x,
y, /) -> mpfr
- Return the maximum number of x and y. If x and y are not mpfr, they
are converted to mpfr. 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 to mpfr. 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.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. See
rootn().
- 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.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 the context.erange flag of the current
context and either return the original value or raise an exception if
context.trap_erange is set.
- 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
- 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 an mpc, return True if both x.real and x.imag are
finite.
- is_infinite()
-> bool
- Return True if x is +Infinity or -Infinity. If x is an mpc,
return True if either x.real or x.imag is infinite. Otherwise
return False.
- is_zero()
-> bool
- Return True if x is equal to 0. If x is an mpc, return
True if both x.real and x.imag are equal to 0.
- 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.f2q(x,
err=0, /) -> mpz | mpq
- Return the 'best' mpq approximating x to within relative error err.
Default is the precision of x. Uses Stern-Brocot tree to find the 'best'
approximation. An mpz object is returned if the denominator is 1.
If err<0, relative error is 2.0 ** err.
- 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 a TypeError if x is
not a gmpy2 object.
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.
In order to use the C-API you need to make one call to the
function void import_gmpy2(void).
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
To create a new gmpy2 types there are four basic functions
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.
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)
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.
A python object could interact with gmpy2 if it implements one of
the following methods:
- __mpz__ : return an object of type mpz.
- __mpq__ : return an object of type mpq.
- __mpfr__ : return an object of type mpfr.
- __mpc__ : return an object of type mpc.
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'>
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')
- Fix internal use of char when int should be used. (jamesjer)
- Add xmpz.bit_count(). (skirpichev)
- 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() and
mpz.from_bytes(). (skirpichev)
- Add is_probab_prime() to directly expose the GMP behavior.
(skirpichev)
- gcd()/lcm() now uses vectorcall protocol. (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() and yn() to match MPFR.
(casevh)
- Fix documentation and code for is_extra_strong_lucas_prp().
(casevh)
- •
- Version bump to fix wheel issues. No code changes.
- •
- Version bump to fix wheel issues. No code changes.
- 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
- Code cleanup.
- Support Apple Silicon binary wheels.
- is_prime(-2) now returns False. Issue #312.
- Code cleanup.
- Properly return NOTIMPLEMENTED for unsupported arguments in **.
Issue #319.
- 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.
- Documentation updates.
- Improvements to build environment.
- Added support for embedded underscore characters in string literals.
- Allow GIL release for mpz/xmpz/mpq types only.
- Improve argument type processing by saving type information to decrease
the number of type check calls. Especially helpful for mpfr and
mpc types. (Not complete but common operations are done.)
- Resolve bug in mpfr to mpq conversion; issue #287.
- Added limited support for releasing the GIL; disabled by default; see
context.allow_release_gil.
- Refactored handling of inplace operations for mpz and xmpz
types; inplace operations on xmpz will only return an xmpz
result.
- Refactored handling of conversion to C integer types. Some exception types
changes to reflect Python types.
- gcd() and lcm() now support more than two arguments to align
with the corresponding functions in the math module.
- 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.
- Fix comparisons with mpq and custom rational objects.
- Fixes for some uncommon integer conversions scenarios.
- Added cmp() and cmp_abs().
- Improved compatibility with the numbers module protocol.
- Many bug fixes.
- Fix qdiv() not returning mpz when it should.
- Added root_of_unity().
- Fix issue 204; missing file for Cython.
- Additional support for MPFR 4
- 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 as root() except different sign when
taking even root of -0.0.
- Revised build process.
- Removal of unused code/macros.
- Cleanup of Cython interface.
- 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 involving mpz 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 an mpz 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 bye
mpz() 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.
- Fix bit_scan0() for negative values.
- Changes to setup.py to allow static linking.
- Fix performance regression with mpmath and Python 3.
- •
- Fix lucas2() and atanh(); they were returning incorrect
values.
- Rebuild Windows binary installers due to MPIR 2.6.0 bug in
next_prime().
- Another fix for is_extra_strong_lucas_prp().
- 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() and
is_strong_bpsw_prp().
- Updated is_extra_strong_lucas_prp() to latest version.
- 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 to float now raises
OverflowError instead of returning inf. (casevh)
- Renamed min2()/max2() to minnum()/maxnum().
(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)
- •
- The test suite is still incomplete.
- Added __ceil__(), __floor__(), __trunc__(), and
__round__() methods to mpz and mpq types.
(casevh)
- Added __complex__() to mpc type. (casevh)
- round(mpfr) now correctly returns an mpz type. (casevh)
- Add mpz.denominator and mpz.numerator. (casevh)
- If no arguments are given to mpz, mpq, mpfr,
mpc, and xmpz, return 0 of the appropriate type.
(casevh)
- Fix broken comparison between mpz and mpq when mpz 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)
- •
- The new test suite (test/runtest.py) is incomplete and some tests
fail on Python 2.x due to formatting issues.
- mp_version(), mpc_version(), and mpfr_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 to
mpq. (casevh)
- Improved conversion of the Decimal type to mpfr.
(casevh)
- Consistently return OverflowError when converting inf.
(casevh)
- Fix mpz.__format__() when the format code includes "#".
(casevh)
- Add is_infinite() and deprecate is_inf(). (casevh)
- Add is_finite() and deprecate is_number(). (casevh)
- Fixed the various is_XXX() tests when used with mpc.
(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 or
mpc. (casevh)
- Fix mpfr + float segmentation fault. (casevh)
- Allow xmpz slice assignment to increase length of xmpz
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
to xmpz. (casevh)
- Added powmod() for easy access to three argument pow().
(casevh)
- Removed addmul() and submul() 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 bit
float's. (casevh)
- Bug fix in context() not setting emax/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)
- 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 with bit_length().
- Added caching for mpq. (casevh)
- Added rootrem(), fib2(), lucas(), lucas2().
(casevh)
- Support changed hash function in Python 3.2. (casevh)
- Added is_even(), is_odd(). (casevh)
- Add caching of the calculated hash value. (casevh)
- Add xmpz (mutable mpz) type. (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 by math.ceil(), math.floor(),
and math.trunc(). (casevh)
- Removed gmpy2.pow() to avoid conflicts. (casevh)
- Removed gmpy2._copy() and added xmpz.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)
- Added fsum(), degrees(), radians(). (casevh)
- Updated random number generation support. (casevh)
- Changed license to LGPL 3+. (casevh)
- Added lucasu(), lucasu_mod(), lucasv(), and
lucasv_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() to num_digits(). (casevh)
- Added keyword precision to constants. (casevh)
- Added addmul() and submul(). (casevh)
- Added __round__(), round2(), round_away() for
mpfr. (casevh)
- round() is no longer a module level function. (casevh)
- Renamed module functions min()/max() to min2()/max2().
(casevh) No longer conflicts with builtin min() and
max()
- 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)
- Recognize True/False (bug in 1.10) (casevh)
- Optimize argument handling (casevh)
- Added caching for mpz (casevh)
- 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)
- 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)
- 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)
- 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)
- 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.*
- minor cleanups, ensure support for Python 2.3
- fixed misdiagnosis of some argument counts in macro
- SELF_ONE_ARG_CONVERTED (tx to Paul Rubin!)
- 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
(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
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
(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
- added jacobi, legendre, kronecker
- added random-number generation, seed set/save, shuffling
- added mpq (at last!-)
- 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
- 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
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
6 Nov 2000
- •
- pre-alpha --- first placed on sourceforge