GMPY2(3)
okay bestie, you're reading the GMPY2(3) manual โ that's gmpy2, the iconic C-coded Python extension module that does multiple-precision arithmetic ๐
โจ. Let's get into it.
โจ NAME โจ
gmpy2 โ gmpy2 Documentation ๐
okay so gmpy2 is a C-coded Python extension module that supports multiple-precision arithmetic. It is the successor to the original gmpy module (which only supported 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) ๐ฆ - MPC (
https://www.multiprecision.org/mpc/) ๐ - Generalized Lucas sequences and primality tests are based on the following code:
mpz_lucas:https://sourceforge.net/projects/mpzlucas/mpz_prp:https://sourceforge.net/projects/mpzprp/
๐ 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 ints and Fractions, 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 (https://www.msys2.org/) to build thegmpy2from 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 offrom gmpy2 import *is not recommended in real code. The names ingmpy2have been chosen to avoid conflict with Python's builtin names butgmpy2does 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 (https://docs.python.org/3/tutorial/inputoutput.html#tut-f-strings) or with str.format(); see Format Specification Mini-Language (https://docs.python.org/3/library/string.html#formatspec) 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.
classmethod 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.bytesandbytearrayare examples of built-in objects that support the buffer protocol.byteorderโ The byte order used to represent the integer. Ifbyteorderis'big', the most significant byte is at the beginning of the byte array. Ifbyteorderis'little', the most significant byte is at the end of the byte array. To request the native byte order of the host system, usesys.byteorderas the byte order value.signedโ Indicates whether two's complement is used to represent the integer.
__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
okay so you're formatting a number and you want it just so. Here's everything you can stack into that format string ๐
- 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 with0b,0oor0x
- 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'. periodt. โจ
as_integer_ratio() -> tuple[mpz <#gmpy2.mpz>, mpz <#gmpy2.mpz>]โ hands you back a pair of integers whose ratio is exactly equal to the original number. ๐ซถ the ratio is in lowest terms and the denominator is positive, no exceptions.bit_clear(n, /) -> mpz <#gmpy2.mpz>โ returns a copy of x with the n-th bit cleared. bye bit ๐bit_count() -> intโ returns how many1-bits are set inabs(x). it's counting the ones bb ๐งฎbit_flip(n, /) -> mpz <#gmpy2.mpz>โ returns a copy of x with the n-th bit inverted. 0 becomes 1, 1 becomes 0, iconic behaviour honestly.bit_length() -> intโ returns the number of significant bits in the radix-2 representation of x. ๐ note:mpz(0).bit_length()returns0.bit_scan0(n=0, /) -> int | Noneโ returns the index of the first 0-bit of x with index >= n. andn >= 0, always. if there are no more0-bits in x at or above index n (which can only happen forx<0, assuming an infinitely long 2's complement format), thenNoneis returned. ๐ญbit_scan1(n=0, /) -> int | Noneโ returns the index of the first 1-bit of x with index >= n.n >= 0. if there are no more1-bits in x at or above index n (which can only happen forx>=0, assuming an infinitely long 2's complement format), thenNoneis returned. no bit found, no vibes.bit_set(n, /) -> mpz <#gmpy2.mpz>โ returns a copy of x with the n-th bit set. โจbit_test(n, /) -> boolโ returns the value of the n-th bit of x. is it 0 or is it 1, we must know ๐ต๏ธconjugate() -> mpz <#gmpy2.mpz>โ returns the conjugate of x. and likeโฆ it's literally just a new reference to x, bestie, because x is not a complex number. there was never anything to conjugate. ๐digits(base=10, /) -> strโ returns a Python string representing x in the given base. values for base can range between2to62. a leading'-'is present ifx<0, but no leading'+'shows up ifx>=0.is_congruent(y, m, /) -> boolโ returnsTrueif x is congruent to y modulo m, else it returnsFalse. ๐is_divisible(d, /) -> boolโ returnsTrueif x is divisible by d, elseFalse. clean division only ๐is_even() -> boolโTrueif x is even,Falseotherwise. 2๏ธโฃis_odd() -> boolโTrueif x is odd,Falseotherwise. 3๏ธโฃis_power() -> boolโ returnsTrueif x is a perfect power (meaning there exists a y and ann > 1such thatx=y**n), elseFalse. โจis_prime(n=25, /) -> boolโ returnsTrueif x is probably prime, elseFalseif x is definitely composite. x gets checked for small divisors and up to n Miller-Rabin tests are performed.is_probab_prime(n=25, /) -> intโ returns2if x is definitely prime,1if x is probably prime, or0if 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 between15and50. so likeโฆ 15 to 50, not 4, not 9000.is_square() -> boolโ returnsTrueif x is a perfect square, elseFalse. ๐ชnum_digits(base=10, /) -> intโ returns the length of the string representing the absolute value of x in the given base. values for base can range between2and62. โ ๏ธ heads up: the value returned may be1too large.to_bytes(length=1, byteorder='big', *, signed=False) -> bytesโ returns an array of bytes representing an integer. ๐งฑ- length โ length of the bytes object to use. an
OverflowErroris 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, usesys.byteorderas the byte order value. - signed โ determines whether two's complement is used to represent the integer. if signed is
Falseand a negative integer is given, anOverflowErroris raised. ๐จ
- length โ length of the bytes object to use. an
denominatorโ the denominator of a rational number in lowest terms.imagโ the imaginary part of a complex number. yeah, it's giving imaginary bestie ๐ฆnumeratorโ the numerator of a rational number in lowest terms.realโ the real part of a complex number. the down-to-earth one ๐ธ
โจ mpz Functions โจ
these are the module-level baddies ๐
same energy as the methods up there, except you pass x in yourself.
gmpy2.bincoef(n, k, /) -> mpz <#gmpy2.mpz>โ returns the binomial coefficient ("n choose k").k >= 0.gmpy2.bit_clear(x, n, /) -> mpz <#gmpy2.mpz>โ returns a copy of x with the n-th bit cleared.gmpy2.bit_count(x, /) -> intโ returns the number of1-bits set inabs(x).gmpy2.bit_flip(x, n, /) -> mpz <#gmpy2.mpz>โ returns a copy of x with the n-th bit inverted.gmpy2.bit_length(x, /) -> intโ returns the number of significant bits in the radix-2 representation of x. ๐ note:bit_length(0)returns0.gmpy2.bit_mask(n, /) -> mpz <#gmpy2.mpz>โ returns an mpz exactly n bits in length with all bits set. every single bit is on, we love a full house ๐gmpy2.bit_scan0(x, n=0, /) -> int | Noneโ returns the index of the first0-bit of x with index >= n.n >= 0. if there are no more0-bits in x at or above index n (which can only happen forx<0, assuming an infinitely long 2's complement format), thenNoneis returned.gmpy2.bit_scan1(x, n=0, /) -> int | Noneโ returns the index of the first1-bit of x with index >= n.n >= 0. if there are no more1-bits in x at or above index n (which can only happen forx>=0, assuming an infinitely long 2's complement format), thenNoneis returned.gmpy2.bit_set(x, n, /) -> mpz <#gmpy2.mpz>โ returns a copy of x with the n-th bit set.gmpy2.bit_test(x, n, /) -> boolโ returns the value of the n-th bit of x.gmpy2.c_div(x, y, /) -> mpz <#gmpy2.mpz>โ returns 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 <#gmpy2.mpz>โ returns the quotient of x divided by2**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 <#gmpy2.mpz>, mpz <#gmpy2.mpz>]โ returns 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 <#gmpy2.mpz>, mpz <#gmpy2.mpz>]โ returns the quotient and remainder of x divided by2**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 <#gmpy2.mpz>โ returns 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 <#gmpy2.mpz>โ returns the remainder of x divided by2**n. the remainder will be negative. x must be an integer. n must be>0.gmpy2.comb(n, k, /) -> mpz <#gmpy2.mpz>โ returns the number of combinations of "n things, taking k at a time".k >= 0. same asbincoef(n, k). twins fr fr ๐ฏgmpy2.divexact(x, y, /) -> mpz <#gmpy2.mpz>โ returns the quotient of x divided by y. faster than standard division but requires the remainder is zero! do not play with this one unless you're sure ๐ฅgmpy2.divm(a, b, m, /) -> mpz <#gmpy2.mpz>โ returns x such thatb*x == a mod m. raises aZeroDivisionErrorexception if no such value x exists. ๐ญgmpy2.double_fac(n, /) -> mpz <#gmpy2.mpz>โ returns the exact double factorial (n!!) of n. the double factorial is defined asn*(n-2)*(n-4)...so yeah, it skips every other one ๐ซgmpy2.f_div(x, y, /) -> mpz <#gmpy2.mpz>โ returns 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 <#gmpy2.mpz>โ returns the quotient of x divided by2**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 <#gmpy2.mpz>, mpz <#gmpy2.mpz>]โ returns 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 <#gmpy2.mpz>, mpz <#gmpy2.mpz>]โ returns quotient and remainder after dividing x by2**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 <#gmpy2.mpz>โ returns 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 <#gmpy2.mpz>โ returns remainder of x divided by2**n. the remainder will be positive. x must be an integer. n must be>0.gmpy2.fac(n, /) -> mpz <#gmpy2.mpz>โ returns the exact factorial of n. ๐ seefactorial(n)to get the floating-point approximation.gmpy2.fib(n, /) -> mpz <#gmpy2.mpz>โ returns the n-th Fibonacci number. ๐gmpy2.fib2(n, /) -> tuple[mpz <#gmpy2.mpz>, mpz <#gmpy2.mpz>]โ returns a 2-tuple with the (n-1)-th and n-th Fibonacci numbers. two for the price of one ๐ซถgmpy2.gcd(*integers, /) -> mpz <#gmpy2.mpz>โ returns the greatest common divisor of integers. the biggest thing they all agree on ๐gmpy2.gcdext(a, b, /) -> tuple[mpz <#gmpy2.mpz>, mpz <#gmpy2.mpz>, mpz <#gmpy2.mpz>]โ bestie, it gives you a 3-element tuple(g,s,t)whereg == gcd(a,b)andg == a*s + b*t. fr fr ๐gmpy2.hamdist(x, y, /) -> intโ returns the Hamming distance (the number of bit-positions where the bits differ) between integersxandy. lowkey useful for error correction vibes ๐ญgmpy2.invert(x, m, /) -> mpz <#gmpy2.mpz>โ returnsysuch thatx*y == 1modulom. RaisesZeroDivisionErrorif no inverse exists. no inverse? tragic ๐gmpy2.iroot(x, n, /) -> tuple[mpz <#gmpy2.mpz>, bool]โ returns the integer n-th root ofxand a boolean that isTrueiff the root is exact.x >= 0.n > 0. slay โจgmpy2.iroot_rem(x, n, /) -> tuple[mpz <#gmpy2.mpz>, mpz <#gmpy2.mpz>]โ returns a 2-element tuple(y,r)such thatyis the integer n-th root ofxandx=y**n + r.x >= 0.n > 0. ๐gmpy2.is_congruent(x, y, m, /) -> boolโ returnsTrueifxis congruent toymodulom, else returnsFalse. ๐gmpy2.is_divisible(x, d, /) -> boolโ returnsTrueifxis divisible byd, else returnsFalse. ๐ซถgmpy2.is_even(x, /) -> boolโ returnsTrueifxis even,Falseotherwise. even? periodt ๐ธgmpy2.is_odd(x, /) -> boolโ returnsTrueifxis odd,Falseotherwise. odd one out energy ๐gmpy2.is_power(x, /) -> boolโ returnsTrueifxis a perfect power (there exists ayand ann > 1, such thatx=y**n), else returnsFalse. ๐ฅgmpy2.is_prime(x, n=25, /) -> boolโ returnsTrueifxis probably prime, elseFalseifxis definitely composite.xis checked for small divisors and up tonMiller-Rabin tests are performed. probably prime? iykyk ๐gmpy2.is_probab_prime(x, n=25, /) -> intโ returns2ifxis definitely prime,1ifxis probably prime, or0ifxis definitely non-prime.xis checked for small divisors and up tonMiller-Rabin tests are performed. Reasonable values ofnare between15and50. iconic โญgmpy2.is_square(x, /) -> boolโ returnsTrueifxis a perfect square, else returnsFalse. ๐gmpy2.isqrt(x, /) -> mpz <#gmpy2.mpz>โ returns the integer square root of a non-negative integerx. ๐gmpy2.isqrt_rem(x, /)โ returns a 2-element tuple(s,t)such thats=isqrt(x)andt=x-s*s.x >=0. ๐ฆgmpy2.jacobi(x, y, /) -> mpz <#gmpy2.mpz>โ returns the Jacobi symbol(x|y).ymust be odd and>0. ๐gmpy2.kronecker(x, y, /) -> mpz <#gmpy2.mpz>โ returns the Kronecker-Jacobi symbol(x|y). โจgmpy2.lcm(*integers, /) -> mpz <#gmpy2.mpz>โ returns the lowest common multiple ofintegers. ๐งgmpy2.legendre(x, y, /) -> mpz <#gmpy2.mpz>โ returns the Legendre symbol(x|y).yis assumed to be an odd prime. ๐gmpy2.lucas(n, /) -> mpz <#gmpy2.mpz>โ returns the n-th Lucas number. ๐ธgmpy2.lucas2(n, /) -> tuple[mpz <#gmpy2.mpz>, mpz <#gmpy2.mpz>]โ returns a 2-tuple with the(n-1)-th and n-th Lucas numbers. ๐ซถgmpy2.mpz_random(random_state, int, /) -> mpz <#gmpy2.mpz>โ returns uniformly distributed random integer between0andn-1. ๐gmpy2.mpz_rrandomb(random_state, bit_count, /) -> mpz <#gmpy2.mpz>โ returns a random integer between0and2**bit_count-1with long sequences of zeros and one in its binary representation. ๐gmpy2.mpz_urandomb(random_state, bit_count, /) -> mpz <#gmpy2.mpz>โ returns uniformly distributed random integer between0and2**bit_count-1. ๐ฅgmpy2.multi_fac(n, m, /) -> mpz <#gmpy2.mpz>โ returns the exact m-multi factorial ofn. The m-multifactorial is defined asn*(n-m)*(n-2m)...slay โจgmpy2.next_prime(x, /) -> mpz <#gmpy2.mpz>โ returns the next probable prime number> x. ๐gmpy2.num_digits(x, base=10, /) -> intโ returns the length of the string representing the absolute value ofxin the givenbase. Values forbasecan range between2and62. The value returned may be1too large. ๐ญgmpy2.pack(lst, n, /) -> mpz <#gmpy2.mpz>โ packs a list of integerslstinto a singlempzby concatenating each integer element oflstafter padding to lengthnbits. Raises an error if any integer is negative or greater thannbits in length. ๐gmpy2.popcount(x, /) -> intโ returns the number of 1-bits set inx. Ifx<0, the number of 1-bits is infinite so-1is returned in that case. ๐gmpy2.powmod(x, y, m, /) -> mpz <#gmpy2.mpz>โ returns(x**y) mod m. Same as the three argument version of Python's built-inpow, but converts all three arguments tompz. ๐ฅgmpy2.powmod_exp_list(base, exp_lst, mod, /) -> list[mpz <#gmpy2.mpz>, ...]โ returnslist(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 <#gmpy2.mpz>, ...]โ returnslist(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 <#gmpy2.mpz>โ returns(x**y) mod m. Calculatesx ** y (mod m)but using a constant time algorithm to reduce the risk of side channel attacks.ymust be an integer>0.mmust be an odd integer. ๐gmpy2.prev_prime(x, /) -> mpz <#gmpy2.mpz>โ returns the previous probable prime number< x. Only present when compiled with GMP 6.3.0 or later. ๐gmpy2.primorial(n, /) -> mpz <#gmpy2.mpz>โ returns the product of all positive prime numbers less than or equal ton. ๐gmpy2.remove(x, f, /) -> tuple[mpz <#gmpy2.mpz>, mpz <#gmpy2.mpz>]โ returns a 2-element tuple(y,m)such thatx=y*(f**m)andfdoes not dividey. Remove the factorffromxas many times as possible.mis the multiplicityfinx.f > 1. โจgmpy2.t_div(x, y, /) -> mpz <#gmpy2.mpz>โ returns the quotient ofxdivided byy. The quotient is rounded towards0.xandymust be integers. ๐gmpy2.t_div_2exp(x, n, /) -> mpz <#gmpy2.mpz>โ returns the quotient ofxdivided by2**n. The quotient is rounded towards zero (truncation).nmust be>0. ๐gmpy2.t_divmod(x, y, /) -> tuple[mpz <#gmpy2.mpz>, mpz <#gmpy2.mpz>]โ returns the quotient and remainder ofxdivided byy. The quotient is rounded towards zero (truncation) and the remainder will have the same sign asx.xandymust be integers. ๐ฆgmpy2.t_divmod_2exp(x, n, /) -> tuple[mpz <#gmpy2.mpz>, mpz <#gmpy2.mpz>]โ returns the quotient and remainder ofxdivided by2**n. The quotient is rounded towards zero (truncation) and the remainder will have the same sign asx.xmust be an integer.nmust be>0. โจgmpy2.t_mod(x, y, /) -> mpz <#gmpy2.mpz>โ returns the remainder ofxdivided byy. The remainder will have the same sign asx.xandymust be integers. ๐gmpy2.t_mod_2exp(x, n, /) -> mpz <#gmpy2.mpz>โ returns the remainder ofxdivided by2**n. The remainder will have the same sign asx.xmust be an integer.nmust be>0. ๐ธgmpy2.unpack(x, n, /) -> listโ unpacks an integerxinto a list of n-bit values. Equivalent to repeated division by2**n. Raises error ifxis negative. ๐ซถ
๐ Integers (Advanced topics) ๐
gmpy2 gives you 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. no cap ๐
>>> 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. it's giving speed โจ
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) ๐
okay bestie, meet xmpz โ the integer with main character energy that you're actually allowed to mutate. ๐ฆ
You build one from a numeric value n, or from a string s made of digits in the given base. And literally every input that the mpz type constructor accepts? xmpz accepts it too. no notes. โจ
Note: this type can be faster when you're using it for augmented assignment (+=,-=, etc.), but โ and this is the tradeoff, bestie โxmpzobjects cannot be used as dictionary keys. ๐
๐
__format__(fmt) -> str
Hands you back a Python string by formatting mpz 'x' using the format string 'fmt'. A valid format string is a little build-your-own situation, and it goes like this:
- 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 with0b,0oor0x
- 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'. periodt. ๐
๐ธ bit_clear(n, /) -> mpz
Return a copy of x with the n-th bit cleared. bye bye bit. ๐
๐ธ bit_count() -> int
Return the number of 1-bits set in abs(x). It's literally counting your blessings (the blessings are ones). โจ
๐ธ bit_flip(n, /) -> mpz
Return a copy of x with the n-th bit inverted. glow-up for one single bit. ๐ฆ
๐ธ bit_length() -> int
Return the number of significant bits in the radix-2 representation of x.
Note:mpz(0).bit_length()returns0. yes bestie, zero has zero bits of significance, it's giving humble. ๐ญ
๐ธ bit_scan0(n=0, /) -> int | None
Return the index of the first 0-bit of x with index >= n. And n >= 0, okay?
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. it's giving "nothing to see here". ๐
๐ธ bit_scan1(n=0, /) -> int | None
Return the index of the first 1-bit of x with index >= n. n >= 0, always.
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. same energy, different bit. ๐ซถ
๐ธ bit_set(n, /) -> mpz
Return a copy of x with the n-th bit set. slay, that bit is ON. ๐ฅ
๐ธ bit_test(n, /) -> bool
Return the value of the n-th bit of x. is it set or is it not, we simply must know. ๐
๐ธ conjugate() -> mpz
Return the conjugate of x โ which is just a new reference to x, because x is not a complex number, bestie. it's giving "I'm my own conjugate". ๐
๐ธ copy() -> xmpz
Return a copy of a x. ๐
๐ธ 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. it's giving minimal, it's giving clean. โจ
๐ฆ 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. yes this is unhinged, yes it's documented, we move. ๐
๐ฆ 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. it's the "and then you hit send" step, don't skip it. ๐ธ
๐ง 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. fr fr, no limbs_finish, no effect. ๐
๐ง limbs_read() -> int
Returns the address of the immutable buffer representing the limbs of x. look but don't touch, bestie. ๐
๐ง 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. like, gone gone. your old x is not coming back. ๐
๐ง 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! you heard me. it's a trade. ๐ญ
โญ 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. so like, an estimate with commitment issues. ๐
โญ num_limbs() -> int
Return the number of limbs of x. simple. iconic. ๐
โญ 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. keeping it real, literally. ๐
๐ฅ Advanced Number Theory Functions ๐ฅ
okay so this whole girlboss section is 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. two tests, one icon. โจ
๐ gmpy2.is_euler_prp(n, a, /) -> bool
Return True if n is an Euler probable prime to the base a (also known as Solovay-Strassen, iykyk).
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. math girlies rise ๐
๐ 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
"extra strong" is such a vibe, honestly. ๐ฅ
๐ 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)
the classic. the blueprint. the one everybody knows. ๐
๐ 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).
fibonacci girlies, this one's for you ๐ฆ
๐ 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)
no cap. โจ
๐ gmpy2.is_selfridge_prp(n, /) -> bool
Return True if n is a Lucas probable prime with Selfridge parameters (p,q). (the manpage spells it "Selfidge" and honestly? we respect the typo era. ๐)
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.
it's giving "the algorithm picks its own outfit". ๐
๐ 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.
(yeah bestie the manpage really did leave the base blank right there. we are simply living with that. ๐ญ)
๐ 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
strong AND lucas AND probable AND prime. the whole resume. ๐ฅ
๐ gmpy2.is_strong_prp(n, a, /) -> bool
Return True if n is a strong probable prime to the base a โ also known as Miller-Rabin, iykyk.
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.
one of those two hits, and she's a probable prime. that's it, that's the test. ๐
๐ gmpy2.is_strong_selfridge_prp(n, /) -> bool
Return True if n is a strong Lucas probable prime with Selfridge 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.
same outfit-picking as before, but now she's strong. ๐ชโจ
๐ 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. those two rules? non-negotiable, bestie. ๐
gmpy2.lucasu_mod(p, q, k, n, /)->mpzโ pulls the k-th element of the Lucas U sequence defined byp,q, but modn. Ground rules bestie:p*p - 4*qmust not equal0,kmust be >=0, andnmust be >0. no exceptions ๐gmpy2.lucasv(p, q, k, /)->mpzโ the k-th element of the Lucas V sequence defined byp,q. rules of the house:p*p - 4*qmust not equal0, andkmust be >=0.gmpy2.lucasv_mod(p, q, k, n, /)->mpzโ k-th element of the Lucas V sequence defined byp,q, but (you guessed it) modn. same vibes check:p*p - 4*qmust not equal0,k>=0, andn>0.
๐ Rationals
the mpq type, she's giving fraction energy
class gmpy2.mpq(n=0, /)
class gmpy2.mpq(n, m, /)
class gmpy2.mpq(s, /, base=10)
okay so this makes you a rational number โจ โ either exactly from a non-complex number n, or from a pair of Rational values n and m, or from a string s built out of digits in whatever base you say. And honestly? every input that the Fraction type constructor accepts, this accepts too. periodt ๐ซถ
Now about that string life: a string can be up to two integers in the same base, split by a / character, and both halves get parsed exactly the same way the mpz constructor does. If base is 0, the leading characters are used to sniff out the base โ and this happens separately for the numerator and the denominator, fancy right? ๐
And if base=10, any string that represents a finite value and is accepted by the float constructor is also accepted. slay.
classmethod from_decimal(dec, /)->mpqโ converts a finitedecimal.Decimalinstance into a rational number, exactly. no rounding nonsense here.classmethod from_float(f, /)->mpqโ converts a finitefloatto a rational number, exactly.as_integer_ratio()->tuple[mpz, mpz]โ hands you a pair of integers whose ratio is exactly equal to the original number. The ratio is in lowest terms and the denominator is positive. math but make it clean ๐ธconjugate()->mpzโ returns the conjugate ofx. and sincexis not a complex number, this is literally just a new reference tox. iconic minimal effort ๐digits(base=10, /)->strโ gives you a Python string ofxin the given base. allowed bases are2to62, default is10. A leading'-'shows up ifx<0, but there's no leading'+'ifx>=0. she doesn't do extra.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
gmpy2.qdiv(x, y=1, /)->mpz|mpqโ returnsx/yas anmpzif that's actually possible, otherwise as anmpqwhenxisn't exactly divisible byy. she adapts โจ
๐ Contexts
so context() creates a brand new context. set_context() sets the active context. get_context() gives you a reference to that active context. and here's the tea bestie โ contexts are mutable: modifying the reference you got back from get_context() will modify the active context until a new context gets enabled with set_context(). The context.copy() method will hand you a copy of the context. And if you want contexts that implement the standard single, double, and quadruple precision floating point types, that's what ieee() is for. ๐
๐ Context Type
class gmpy2.context(**kwargs)
class gmpy2.context(ctx, /, **kwargs)
returns a fresh new context for controlling gmpy2 arithmetic โ based either on the default context or on one given by the ctx value. and you can override context options on top of that with keyword arguments. very customizable, very demure.
abs(x, /)->mpz|mpq|mpfrโ returnsabs(x), and the context gets applied to the result.acos(x, /)->mpfr|mpcโ inverse cosine ofx; result in radians.acosh(x, /)->mpfr|mpcโ inverse hyperbolic cosine ofx.add(x, y, /)->mpz|mpq|mpfr|mpcโ returnsx + y.agm(x, y, /)->mpfrโ arithmetic-geometric mean ofxandy.ai(x, /)->mpfrโ Airy function ofx.asin(x, /)->mpfr|mpcโ inverse sine ofx; result in radians.asinh(x, /)->mpfr|mpcโ inverse hyperbolic sine ofx.atan(x, /)->mpfr|mpcโ inverse tangent ofx; result in radians.atan2(y, x, /)->mpfrโ arc-tangent of(y/x); result in radians.atanh(x, /)->mpfr|mpcโ inverse hyperbolic tanget ofx. (yes, "tanget" โ we keep the lore exactly as written ๐ซถ)cbrt(x, /)->mpfrโ the cube root ofx.ceil(x, /)->mpfrโ returns anmpfrthat is the smallest integer>= x.check_range(x, /)->mpfrโ returns a newmpfrwhose exponent lies within the range ofeminandemaxspecified by the context.clear_flags()->Noneโ clears all the MPFR exception flags. clean slate bestie โจconst_catalan()->mpfrโ the catalan constant, at the context's precision.const_euler()->mpfrโ the euler constant, at the context's precision.const_log2()->mpfrโ the log2 constant, at the context's precision.const_pi()->mpfrโ the constant pi, at the context's precision.copy()->contextโ a copy of a context.cos(x, /)->mpfr|mpcโ cosine ofx;xin radians.cosh(x, /)->mpfr|mpcโ hyperbolic cosine ofx.cot(x, /)->mpfrโ cotangent ofx;xin radians.coth(x, /)->mpfrโ hyperbolic cotangent ofx.csc(x, /)->mpfrโ cosecant ofx;xin radians.csch(x, /)->mpfrโ hyperbolic cosecant ofx.degrees(x, /)->mpfrโ converts anglexfrom radians to degrees.
โ ๏ธ heads up bestie: in rare cases the result may not be correctly rounded. not a drill.
digamma(x, /)->mpfrโ digamma ofx.div(x, y, /)->mpz|mpq|mpfr|mpcโ returnsx / y; uses true division.div_2exp(x, n, /)->mpfr|mpcโ returnsmpfrormpcdivided by2**n.divmod(x, y, /)->tuple[mpz | mpfr, mpz | mpq | mpfr]โ returnsdivmod(x, y).
note: overflow, underflow, and inexact exceptions are not supported for mpfr arguments. so don't come for her about those ๐
eint(x, /)->mpfrโ exponential integral ofx.erf(x, /)->mpfrโ error function ofx.erfc(x, /)->mpfrโ complementary error function ofx.exp(x, /)->mpfr|mpcโ the exponential ofx.exp10(x, /)->mpfrโ returns10**x.exp2(x, /)->mpfrโ returns2**x.expm1(x, /)->mpfrโ returnsexp(x) - 1.factorial(n, /)->mpfrโ the floating-point approximation to the factorial ofn.
if you want the exact integer result, go see fac() instead. this one's just the vibe approximation ๐ธ
floor(x, /)->mpfrโ returns anmpfrthat is the largest integer<= x.floor_div(x, y, /)->mpz|mpfrโ returnsx // y; uses floor division.fma(x, y, z, /)->mpz|mpq|mpfr|mpcโ the correctly rounded result of(x * y) + z. she does not cut corners โจfmma(x, y, z, t, /)->mpfrโ the correctly rounded result of(x * y) + (z * t).fmms(x, y, z, t, /)->mpfrโ the correctly rounded result of(x * y) - (z * t).fmod(x, y, /)->mpfrโ returnsx - n*ywherenis the integer quotient ofx/y, rounded toward0.fms(x, y, z, /)->mpz|mpq|mpfr|mpcโ the correctly rounded result of(x * y) - z.frac(x, /)->mpfrโ fractional part ofx.frexp(x, /)->tuple[int, mpfr]โ a tuple with the exponent and mantissa ofx.fsum(iterable, /)->mpfrโ an accurate sum of the values in the iterable. no floating point drama ๐gamma(x, /)->mpfrโ gamma ofx.gamma_inc(a, x, /)->mpfrโ the (upper) incomplete gamma ofaandx.hypot(x, y, /)->mpfrโ the square root of(x**2 + y**2).is_finite(x, /)->boolโTrueifxis an actual number (i.e. non NaN or Infinity). Ifxis anmpc, returnsTrueif bothx.realandx.imagare finite.is_infinite(x, /)->boolโTrueifxis+Infinityor-Infinity. Ifxis anmpc, returnsTrueif eitherx.realorx.imagis infinite. Otherwise it'sFalse.is_integer(x, /)->boolโTrueifxis an integer;Falseotherwise.is_nan(x, /)->boolโTrueifxis NaN (Not-A-Number), elseFalse.is_regular(x, /)->boolโTrueifxis not zero, NaN, or Infinity;Falseotherwise.is_signed(x, /) -> boolโ gives youTruewhen the sign bit ofxis set โจis_zero(x, /) -> boolโTrueifxis equal to 0. And ifxis anmpc? Then it'sTrueonly when bothx.realandx.imagare equal to 0 ๐j0(x, /) -> mpfrโ first kind Bessel function of order 0 ofx๐ซj1(x, /) -> mpfrโ first kind Bessel function of order 1 ofxjn(n, x, /) -> mpfrโ first kind Bessel function of ordernofx. โ ๏ธ not me telling you this again but: the order of the arguments changed in gmpy2 2.2.0a2lgamma(x, /) -> tuple[mpfr, int]โ returns a tuple holding the logarithm of the absolute value ofgamma(x), plus the sign ofgamma(x)๐ซถli2(x, /) -> mpfrโ real part of the dilogarithm ofxlngamma(x, /) -> mpfrโ natural logarithm ofgamma(x)log(x, /) -> mpfr | mpcโ the natural logarithm ofx๐ธlog10(x, /) -> mpfr | mpcโ the base-10 logarithm ofxlog1p(x, /) -> mpfrโ natural logarithm of(1+x)log2(x, /) -> mpfrโ base-2 logarithm ofxmaxnum(x, y, /) -> mpfrโ the max ofxandy. Ifxandyaren'tmpfr, they get converted tompfrfirst. Then the result is rounded to match the specified context ๐ Bonus: if only one ofxoryis a number, then that number is what comes back.minnum(x, y, /) -> mpfrโ the min ofxandy. Same deal asmaxnum: not-mpfrinputs get converted tompfr, the result gets rounded to match the specified context, and if only one ofxoryis a number, that number is returned ๐minus(x, /) -> mpz | mpq | mpfr | mpcโ returns-x. The context is applied to the result.mod(x, y, /) -> mpz | mpq | mpfrโ returnsmod(x, y). ๐จ real talk though: overflow, underflow, and inexact exceptions are not supported formpfrarguments.modf(x, /) -> tuple[mpfr, mpfr]โ a tuple with the integer portion and the fractional portion ofx๐mul(x, y, /) -> mpz | mpq | mpfr | mpcโ returnsx * ymul_2exp(x, n, /) -> mpfr | mpcโ anmpfrormpcmultiplied by2**nnext_above(x, /) -> mpfrโ the nextmpfrfromxtoward+Infinityโฌ๏ธnext_below(x, /) -> mpfrโ the nextmpfrfromxtoward-Infinityโฌ๏ธnext_toward(x, y, /) -> mpfrโ the nextmpfrfromxheading in the direction ofy. Result keeps the same precision asx.norm(x, /) -> mpfrโ the norm of a complexx.norm(x)is defined asx.real**2 + x.imag**2, andabs(x)is the square root ofnorm(x)โจphase(x, /) -> mpfrโ the phase angle (aka the argument) of a complexx๐plus(x, /) -> mpz | mpq | mpfr | mpcโ returns+x, and the context is applied to the result.polar(x, /) -> tuple[mpfr, mpfr]โ the polar coordinate form of a complexxthat's in rectangular formpow(x, y, /) -> mpz | mpq | mpfr | mpcโ returnsx ** y๐ฅproj(x, /) -> mpcโ the projection of a complexxonto the Riemann sphere ๐radians(x, /) -> mpfrโ converts anglexfrom degrees to radians. Small heads up: in rare cases the result may not be correctly rounded.rec_sqrt(x, /) -> mpfrโ the reciprocal of the square root ofxrect(r, phi, /) -> mpcโ the rectangular coordinate form of a complex number that you gave in polar formreldiff(x, y, /) -> mpfrโ the relative difference betweenxandy. The result equalsabs(x-y)/x.remainder(x, y, /) -> mpfrโ returnsx - n*ywherenis the integer quotient ofx/y, rounded to the nearest integer, and ties rounded to even โ๏ธremquo(x, y, /) -> tuple[mpfr, int]โ a tuple withremainder(x,y)and the low bits of the quotientrint(x, /) -> mpfrโxrounded to the nearest integer using the context rounding moderint_ceil(x, /) -> mpfrโxrounded to the nearest integer, by first rounding to the next higher-or-equal integer and then, if needed, using the context rounding moderint_floor(x, /) -> mpfrโxrounded to the nearest integer, by first rounding to the next lower-or-equal integer and then, if needed, using the context rounding moderint_round(x, /) -> mpfrโxrounded to the nearest integer, by first rounding to the nearest integer (ties away from 0) and then, if needed, using the context rounding moderint_trunc(x, /) -> mpfrโxrounded to the nearest integer, by first rounding towards zero and then, if needed, using the context rounding moderoot(x, n, /) -> mpfrโ then-th root ofx. The result is always anmpfr. ๐จ note: not IEEE 754-2008 compliant; the result differs whenx = -0andnis even. Seecontext.rootn().root_of_unity(n, k, /) -> mpcโ then-th root ofmpc(1)raised to thek-th power ๐ซrootn(x, n, /) -> mpfrโ then-th root ofx. The result is always anmpfr. โจ note: this is the IEEE 754-2008 compliant version ofcontext.root().round2(x, n=0, /) -> mpfrโxrounded tonbits. Uses the default precision ifnisn't specified. Seecontext.round_away()to access thempfr_round()function of the MPFR.round_away(x, /) -> mpfrโ anmpfrthat isxrounded to the nearest integer, with ties rounded away from 0 ๐ซถsec(x, /) -> mpfrโ secant ofx;xin radianssech(x, /) -> mpfrโ hyperbolic secant ofxsin(x, /) -> mpfr | mpcโ sine ofx;xin radians ๐sin_cos(x, /) -> tuple[mpfr | mpc, mpfr | mpc]โ a tuple with the sine and the cosine ofx;xin radians. Two for one, we love to see it ๐sinh(x, /) -> mpfr | mpcโ hyperbolic sine ofxsinh_cosh(x, /) -> tuple[mpfr, mpfr]โ a tuple with the hyperbolic sine and cosine ofxsqrt(x, /) -> mpfr | mpcโ the square root ofx๐ฑsquare(x, /) -> mpz | mpq | mpfr | mpcโ returnsx * xsub(x, y, /) -> mpz | mpq | mpfr | mpcโ returnsx - ytan(x, /) -> mpfr | mpcโ tangent ofx;xin radianstanh(x, /) -> mpfr | mpcโ hyperbolic tangent ofxtrunc(x, /) -> mpfrโ anmpfrthat isxtruncated towards 0. Same asx.floor()ifx>=0orx.ceil()ifx<0โ๏ธy0(x, /) -> mpfrโ second kind Bessel function of order 0 ofxy1(x, /) -> mpfrโ second kind Bessel function of order 1 ofxyn(n, x, /) -> mpfrโ the second kind Bessel function of ordernofx. โ ๏ธ once again for the people in the back: the order of the arguments changed in gmpy2 2.2.0a2zeta(x, /) -> mpfrโ Riemann zeta ofx๐
๐ attributes, aka the lil switches that run the whole vibe ๐
allow_complexโ this attribute controls whether or not anmpcresult can be returned if anmpfrresult would normally not be possible ๐allow_release_gilโ if you set it toTrue, lots ofmpzandmpqcomputations will release the GIL.
๐งช This is considered an experimental feature. You've been warned, bestie.
divzeroโ this flag is not user controllable. It gets set automatically if a division by zero occurred and a NaN result was returned ๐จemaxโ this attribute controls the maximum allowed exponent of anmpfrresult. The maximum exponent is platform dependent and can be retrieved withget_emax_max()โฌ๏ธeminโ this attribute controls the minimum allowed exponent of anmpfrresult. The minimum exponent is platform dependent and can be retrieved withget_emin_min()โฌ๏ธerangeโ bestie this one is NOT yours to touch ๐ โโ๏ธ it flips itself on automatically whenever an erange error happens.imag_precโ controls the precision of the imaginary part of anmpcresult. If it's set toDefault, then whateverreal_precis gets used instead. โจimag_roundโ controls the rounding mode for the imaginary part of anmpcresult. If it'sDefault, then thereal_roundvalue is used. Heads up though:RoundAwayZerois not a valid rounding mode formpc. ๐inexactโ not user controllable, sorry bestie. It just sets itself if an inexact result comes back.invalidโ also not user controllable. Auto-sets if an invalid (Not-A-Number) result is returned. ๐ซoverflowโ not user controllable either. Sets itself automatically if a result overflowed to +/-Infinity andtrap_overflowisFalse.precisionโ controls the precision of anmpfrresult. It's measured in bits, not decimal digits, okay? The max precision you can ask for is platform dependent, and you can grab it withget_max_precision(). โ ๏ธ Also: if you setprecisiontoo close to the maximum, the MPFR library will literally fail. Don't do it.rational_divisionโ set this toTrueandmpz/mpzhands you back anmpqinstead of anmpfr. It's giving "keep it exact" energy. ๐real_precโ controls the precision of the real part of anmpcresult. If it'sDefault, then theprecisionattribute's value is used.real_roundโ controls the rounding mode for the real part of anmpcresult. If it'sDefault, then theroundattribute's value is used. Same warning as before:RoundAwayZerois not a valid rounding mode formpc.roundโ thempfrtype has five rounding modes and here they all are:RoundAwayZeroโ the result is rounded away from 0.0.RoundDownโ the result is rounded towards -Infinity.RoundToNearestโ rounds to the nearest value; ties go to an even value.RoundToZeroโ the result is rounded towards 0.0.RoundUpโ the result is rounded towards +Infinity.
subnormalizeโ so the usual IEEE-754 floating point representation supports gradual underflow when you hit the minimum exponent. The MPFR library does not enable gradual underflow by default, but you can turn it on to exactly mimic what IEEE-754 floating point operations do. Niche but iconic. ๐ฆtrap_divzeroโ controls whether aDivisionByZeroErrorgets raised when division by 0 happens. Fun fact:DivisionByZeroErroris a sub-class of Python'sZeroDivisionError.trap_erangeโ controls whether aRangeErroris raised when certain operations get performed on NaN and/or Infinity values. Settingtrap_erangetoTrueis the move if you want an exception when comparisons get attempted against a NaN.trap_inexactโ controls whether anInexactResultErrorgets raised when an inexact result is returned. And if you want to know whether the result was greater or less than the exact result, go check thercattribute of thempfrresult. ๐ต๏ธโโ๏ธtrap_invalidโ controls whether anInvalidOperationErrorgets raised when a numerical result isn't defined. If no exception is raised, you get a special NaN (Not-A-Number) value instead.InvalidOperationErroris a sub-class of Python'sValueError.
For example, gmpy2.sqrt(-2) will normally return mpfr('nan'). But if allow_complex is set to True, then you get an mpc result back instead. ๐
trap_overflowโ if set toFalse, a result bigger than the largest possiblempfrgiven the current exponent range gets replaced by +/-Infinity. If set toTrue, anOverflowResultErrorexception is raised instead.trap_underflowโ if set toFalse, a result smaller than the smallest possiblempfrgiven the current exponent range gets replaced by +/-0.0. If set toTrue, anUnderflowResultErrorexception gets raised.underflowโ not user controllable. Auto-sets if a result underflowed to +/-0.0 andtrap_underflowisFalse.
๐ Context Functions ๐
gmpy2.get_context() -> context
Returns a reference to the current context. Easy.
gmpy2.ieee(size, /, subnormalize=True) -> context
Returns a brand new context matching a standard IEEE floating point format. The supported sizes are 16, 32, 64, 128, and multiples of 32 greater than 128. Slay. โจ
gmpy2.local_context(**kwargs) -> context
gmpy2.local_context(context, /, **kwargs) -> context
Returns a new context for controlling gmpy2 arithmetic, based either on the current context or on a ctx value. Context options can also be overridden with keyword arguments. iykyk ๐ซถ
gmpy2.set_context(context, /) -> None
Activates a context object controlling gmpy2 arithmetic. That's it, that's the function.
๐ญ Exceptions ๐ญ
exception gmpy2.RangeError
exception gmpy2.InexactResultError
exception gmpy2.OverflowResultError
exception gmpy2.UnderflowResultError
exception gmpy2.InvalidOperationError
exception gmpy2.DivisionByZeroError
There they all are, the whole squad. ๐
๐ธ Multiple-precision Reals ๐ธ
mpfr Type โ the main character ๐
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)
Returns a floating-point number after converting either a numeric value n or a string s made of digits in the given base.
So for strings: they can have a fraction-part (period as the separator) and/or an exponent-part. The exponent marker is 'e' or 'E' for bases up to 10, and '@' in any base. In bases 2 and 16 the exponent prefix can also be 'p' or 'P' โ and in that case the exponent means multiply by a power of 2 instead of the base. Note that the value of an exponent is always written in base 10. The fractional-part digits get parsed the same way the mpz type constructor does it, and both the whole number and the exponent-part can optionally be preceded by '+' or '-'. Every input that the float type constructor or the float.fromhex method accepts is also accepted here. ๐
Now for precision, listen up:
- If a precision greater than or equal to 2 is specified, then it gets used.
- A precision of 0 (which is the default) means 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
nis a radix-2 floating point number, then the full precision ofnis retained. - If
nis an integer, then the precision is the bit length of the integer.
- If
__format__(fmt) -> str
Returns 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]
Returns the exact rational equivalent of an mpfr. The value is a tuple, purely for compatibility with Python's float.as_integer_ratio. ๐
as_mantissa_exp() -> tuple[mpz, mpz]
Returns the mantissa and exponent of an mpfr. That's the whole thing.
as_simple_fraction(precision=0) -> mpq
Returns a simple rational approximation to x. The result is accurate to 'precision' bits. And if 'precision' is 0, then the precision of 'x' gets used instead.
conjugate() -> mpz
Returns the conjugate of x โ which is literally just a new reference to x since x is not a complex number. Waste of effort? Maybe. Iconic? Absolutely. ๐
digits(base=10, prec=0, /) -> tuple[str, int, int]โ bestie, this one gives you up toprecdigits in whateverbaseyou want. Ifprecis0, it returns as many digits as are available, and it won't give you more digits than x's precision allows.basehas to be between2and62, inclusive. You get back a three-element tuple: the mantissa, the exponent, and the number of bits of precision. ๐is_finite() -> boolโ returnsTrueif x is an actual number (so not NaN or Infinity, periodt). If x is anmpc <#gmpy2.mpc>, it returnsTrueonly if bothx.realandx.imagare finite. ๐is_infinite() -> boolโ returnsTrueif x is+Infinityor-Infinity. If x is anmpc <#gmpy2.mpc>, it returnsTrueif eitherx.realorx.imagis infinite. Otherwise it'sFalse.is_integer() -> boolโ returnsTrueif x is an integer;Falseotherwise. no cap.is_nan() -> boolโ returnsTrueif x is NaN (Not-A-Number), elseFalse.is_regular() -> boolโ returnsTrueif x is not zero, NaN, or Infinity;Falseotherwise.is_signed() -> boolโ returnsTrueif the sign bit of x is set.is_zero() -> boolโ returnsTrueif x is equal to0. If x is anmpc <#gmpy2.mpc>, it returnsTrueif bothx.realandx.imagare equal to0. ๐ซถimagโ imaginary component โจprecisionโ precision in bits ๐rcโ return code ๐realโ real component ๐ฆ
โจ mpfr Functions โจ
gmpy2.agm(x, y, /) -> mpfr <#gmpy2.mpfr>โ returns the arithmetic-geometric mean of x and y. slay โจgmpy2.ai(x, /) -> mpfr <#gmpy2.mpfr>โ returns the Airy function of x.gmpy2.atan2(y, x, /) -> mpfr <#gmpy2.mpfr>โ returns arc-tangent of(y/x); the result is in radians.gmpy2.cbrt(x, /) -> mpfr <#gmpy2.mpfr>โ returns the cube root of x. periodt.gmpy2.ceil(x, /) -> mpfr <#gmpy2.mpfr>โ returns anmpfrthat is the smallest integer>= x.gmpy2.check_range(x, /) -> mpfr <#gmpy2.mpfr>โ returns a newmpfrwith an exponent that lies within the current range ofeminandemax.gmpy2.cmp(x, y, /) -> intโ returns-1ifx < y;0ifx = y; or1ifx > y. Both x and y must be integer, rational or real. Note:0is returned (and the exception flag is set) if either argument is NaN. ๐gmpy2.const_catalan(precision=0) -> mpfr <#gmpy2.mpfr>โ returns the catalan constant using the specified precision. If no precision is specified, the default precision is used.gmpy2.const_euler(precision=0) -> mpfr <#gmpy2.mpfr>โ returns the euler constant using the specified precision. If no precision is specified, the default precision is used.gmpy2.const_log2(precision=0) -> mpfr <#gmpy2.mpfr>โ returns the log2 constant using the specified precision. If no precision is specified, the default precision is used.gmpy2.const_pi(precision=0) -> mpfr <#gmpy2.mpfr>โ returns the constant pi using the specified precision. If no precision is specified, the default precision is used.gmpy2.cot(x, /) -> mpfr <#gmpy2.mpfr>โ returns cotangent of x; x in radians.gmpy2.coth(x, /) -> mpfr <#gmpy2.mpfr>โ returns hyperbolic cotangent of x.gmpy2.csc(x, /) -> mpfr <#gmpy2.mpfr>โ returns cosecant of x; x in radians.gmpy2.csch(x, /) -> mpfr <#gmpy2.mpfr>โ returns hyperbolic cosecant of x.gmpy2.degrees(x, /) -> mpfr <#gmpy2.mpfr>โ converts angle x from radians to degrees. Note: in rare cases the result may not be correctly rounded. ๐gmpy2.digamma(x, /) -> mpfr <#gmpy2.mpfr>โ returns digamma of x.gmpy2.eint(x, /) -> mpfr <#gmpy2.mpfr>โ returns exponential integral of x.gmpy2.erf(x, /) -> mpfr <#gmpy2.mpfr>โ returns error function of x.gmpy2.erfc(x, /) -> mpfr <#gmpy2.mpfr>โ returns complementary error function of x.gmpy2.exp10(x, /) -> mpfr <#gmpy2.mpfr>โ returns10**x.gmpy2.exp2(x, /) -> mpfr <#gmpy2.mpfr>โ returns2**x.gmpy2.expm1(x, /) -> mpfr <#gmpy2.mpfr>โ returnsexp(x) - 1.gmpy2.factorial(n, /) -> mpfr <#gmpy2.mpfr>โ returns the floating-point approximation to the factorial of n. Seefac() <#gmpy2.fac>to get the exact integer result. ๐gmpy2.floor(x, /) -> mpfr <#gmpy2.mpfr>โ returns anmpfrthat is the largest integer<= x.gmpy2.fmma(x, y, z, t, /) -> mpfr <#gmpy2.mpfr>โ returns correctly rounded result of(x * y) + (z + t).gmpy2.fmms(s, y, z, t, /) -> mpfr <#gmpy2.mpfr>โ returns correctly rounded result of(x * y) - (z + t).gmpy2.fmod(x, y, /) -> mpfr <#gmpy2.mpfr>โ returnsx - n*ywherenis the integer quotient ofx/y, rounded to0.gmpy2.frac(x, /) -> mpfr <#gmpy2.mpfr>โ returns fractional part of x.gmpy2.frexp(x, /) -> tuple[int, mpfr <#gmpy2.mpfr>]โ returns a tuple containing the exponent and mantissa of x.gmpy2.fsum(iterable, /) -> mpfr <#gmpy2.mpfr>โ returns an accurate sum of the values in the iterable.gmpy2.gamma(x, /) -> mpfr <#gmpy2.mpfr>โ returns gamma of x.gmpy2.gamma_inc(a, x, /) -> mpfr <#gmpy2.mpfr>โ returns (upper) incomplete gamma of a and x.gmpy2.get_exp(x, /) -> intโ returns the exponent of x. It returns0for NaN or Infinity and sets thecontext.erange <#gmpy2.context.erange>flag of the current context, and it will raise an exception ifcontext.trap_erange <#gmpy2.context.trap_erange>is set. ๐จgmpy2.hypot(x, y, /) -> mpfr <#gmpy2.mpfr>โ returns square root of(x**2 + y**2).gmpy2.inf(n, /) -> mpfr <#gmpy2.mpfr>โ returns anmpfrinitialized to Infinity with the same sign as n. If n is not given,+Infinityis returned.gmpy2.is_finite(x, /) -> boolโ returnsTrueif x is an actual number (i.e. non NaN or Infinity). If x is anmpc <#gmpy2.mpc>, it returnsTrueif bothx.realandx.imagare finite.gmpy2.is_infinite(x, /) -> boolโ returnsTrueif x is+Infinityor-Infinity. If x is anmpc <#gmpy2.mpc>, it returnsTrueif eitherx.realorx.imagis infinite. Otherwise it returnsFalse.gmpy2.is_regular(x, /) -> boolโ returnsTrueif x is not zero, NaN, or Infinity;Falseotherwise.gmpy2.is_signed(x, /) -> boolโ returnsTrueif the sign bit of x is set.gmpy2.is_unordered(x, y, /) -> boolโ returnsTrueif either x and/or y is NaN.gmpy2.j0(x, /) -> mpfr <#gmpy2.mpfr>โ returns first kind Bessel function of order 0 of x.gmpy2.j1(x, /) -> mpfr <#gmpy2.mpfr>โ returns first kind Bessel function of order 1 of x.gmpy2.jn(n, x, /) -> mpfr <#gmpy2.mpfr>โ returns the first kind Bessel function of order n of x. Note: the order of the arguments changed ingmpy2 2.2.0a2.gmpy2.lgamma(x, /) -> tuple[mpfr <#gmpy2.mpfr>, int]โ returns a tuple containing the logarithm of the absolute value ofgamma(x)and the sign ofgamma(x).gmpy2.li2(x, /) -> mpfr <#gmpy2.mpfr>โ returns real part of dilogarithm of x.gmpy2.lngamma(x, /) -> mpfr <#gmpy2.mpfr>โ returns natural logarithm ofgamma(x).gmpy2.log1p(x, /) -> mpfr <#gmpy2.mpfr>โ returns natural logarithm of(1+x).gmpy2.log2(x, /) -> mpfr <#gmpy2.mpfr>โ returns base-2 logarithm of x.gmpy2.maxnum(x, y, /) -> mpfr <#gmpy2.mpfr>โ returns the maximum number of x and y. If x and y are notmpfr, 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 <#gmpy2.mpfr>โ returns the minimum number of x and y. If x and y are notmpfr, 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 <#gmpy2.mpfr>, mpfr <#gmpy2.mpfr>]โ returns a tuple containing the integer and fractional portions of x.gmpy2.mpfr_from_old_binary(string, /) -> mpfr <#gmpy2.mpfr>โ returns anmpfrfrom aGMPY 1.xbinarympfformat.gmpy2.mpfr_grandom(random_state, /) -> tuple[mpfr <#gmpy2.mpfr>, mpfr <#gmpy2.mpfr>]โ returns two random numbers with gaussian distribution.gmpy2.mpfr_nrandom(random_state, /)โ returns a random number with gaussian distribution.gmpy2.mpfr_random(random_state, /) -> mpfr <#gmpy2.mpfr>โ returns uniformly distributed number between[0,1].gmpy2.nan() -> mpfr <#gmpy2.mpfr>โ returns anmpfrinitialized to NaN (Not-A-Number).gmpy2.next_above(x, /) -> mpfr <#gmpy2.mpfr>โ returns the nextmpfrfrom x toward+Infinity.gmpy2.next_below(x, /) -> mpfr <#gmpy2.mpfr>โ returns the nextmpfrfrom x toward-Infinity.gmpy2.radians(x, /) -> mpfr <#gmpy2.mpfr>โ converts angle x from degrees to radians. Note: in rare cases the result may not be correctly rounded. ๐gmpy2.rec_sqrt(x, /) -> mpfr <#gmpy2.mpfr>โ returns the reciprocal of the square root of x.gmpy2.reldiff(x, y, /) -> mpfr <#gmpy2.mpfr>โ returns the relative difference between x and y. Result is equal toabs(x-y)/x.gmpy2.remainder(x, y, /) -> mpfr <#gmpy2.mpfr>โ returnsx - n*ywherenis the integer quotient ofx/y, rounded to the nearest integer and ties rounded to even.gmpy2.remquo(x, y, /) -> tuple[mpfr <#gmpy2.mpfr>, int]โ returns a tuple containing theremainder(x,y)and the low bits of the quotient.gmpy2.rint(x, /) -> mpfr <#gmpy2.mpfr>โ returns x rounded to the nearest integer using the current rounding mode.gmpy2.rint_ceil(x, /) -> mpfr <#gmpy2.mpfr>โ returns 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 <#gmpy2.mpfr>โ returns 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 <#gmpy2.mpfr>โ returns x rounded to the nearest integer by first rounding to the nearest integer (ties away from0) and then, if needed, using the current rounding mode.gmpy2.rint_trunc(x, /) -> mpfr <#gmpy2.mpfr>โ returns 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โ okay so this gives you then-th root ofx, and the result is always anmpfr. โจ โ ๏ธ bestie, heads up: this is not IEEE 754-2008 compliant โ the result differs whenx = -0andnis even. peeprootn()if you need that. ๐gmpy2.rootn(x, n, /) -> mpfrโ same n-th root energy, but this is the IEEE 754-2008 compliant version ofroot(). slay. ๐gmpy2.round2(x, n=0, /) -> mpfrโ returnsxrounded tonbits. if you don't passn, it uses the default precision. checkround_away()to access thempfr_round()function of the MPFR. ๐gmpy2.round_away(x, /) -> mpfrโ returns anmpfrthat isxrounded to the nearest integer, with ties rounded away from0. no cap. ๐ซถgmpy2.sec(x, /) -> mpfrโ returns the secant ofx;xin radians. ๐ธgmpy2.sech(x, /) -> mpfrโ returns the hyperbolic secant ofx. ๐ฆgmpy2.set_exp(x, n, /) -> mpfrโ sets the exponent ofxton. ifnis outside the range of valid exponents,set_exp()will set thecontext.erangeflag of the current context and either return the original value or raise an exception ifcontext.trap_erangeis set. โ ๏ธgmpy2.set_sign(x, s, /) -> mpfrโ ifsisTrue, returnsxwith the sign bit set. periodt. ๐gmpy2.sign(x, /) -> intโ returns-1ifx < 0,0ifx == 0, or+1ifx >0. (yes, that's exactly how it's written, don't @ me.) ๐gmpy2.sinh_cosh(x, /) -> tuple[mpfr, mpfr]โ returns a tuple containing the hyperbolic sine and cosine ofx. ๐gmpy2.trunc(x, /) -> mpfrโ returns anmpfrthat isxtruncated towards0. same asx.floor()ifx>=0orx.ceil()ifx<0. ๐งgmpy2.y0(x, /) -> mpfrโ returns the second kind Bessel function of order0ofx. ๐gmpy2.y1(x, /) -> mpfrโ returns the second kind Bessel function of order1ofx. โญgmpy2.yn(n, x, /) -> mpfrโ returns the second kind Bessel function of ordernofx. โ ๏ธ note: the order of the arguments changed ingmpy2 2.2.0a2. ๐gmpy2.zero(n, /) -> mpfrโ returns anmpfrinitialized to0.0with the same sign asn. ifnis not given,+0.0is returned. ๐gmpy2.zeta(x, /) -> mpfrโ returns the Riemann zeta ofx. ๐ฅgmpy2.get_max_precision() -> intโ returns the maximum bits of precision that can be used for calculations. โ ๏ธ note: to allow extra precision for intermediate calculations, avoid setting precision close to the maximum precision. ๐ญgmpy2.get_emax_max() -> intโ returns the maximum possible exponent that can be set formpfr. ๐gmpy2.get_emin_min() -> intโ returns the minimum possible exponent that can be set formpfr. ๐gmpy2.copy_sign(x, y, /) -> mpfrโ returns anmpfrcomposed ofxwith the sign ofy. ๐ซถgmpy2.can_round(b, err, rnd1, rnd2, prec, /) -> boolโ letbbe an approximation to an unknown numberxthat is rounded according tornd1. assume thatbhas an error at most two to the power ofE(b)-errwhereE(b)is the exponent ofb. then returnTrueifxcan be rounded correctly toprecbits with rounding modernd2. ๐คgmpy2.free_cache() -> Noneโ free the internal cache of constants maintained by MPFR. bye bestie ๐
๐ 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)
returns 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 have a real-part and/or an imaginary-part (with 'j' as a suffix), separated by '+', and it's parsed the same way the mpfr constructor does it (but 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. ๐ธ
methods:
__format__(fmt) -> strโ returns 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'.
- optional alignment code:
conjugate() -> mpcโ returns the conjugate ofx. ๐digits(base=10, prec=0, /) -> tuple[tuple[str, int, int], tuple[str, int, int]]โ returns up toprecdigits in the givenbase. ifprecis0, as many digits that are available givenc's precision are returned.basemust be between2and62. 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โ returnTrueifxis an actual number (i.e. non NaN or Infinity). ifxis anmpc, returnTrueif bothx.realandx.imagare finite. ๐is_infinite() -> boolโ returnTrueifxis+Infinityor-Infinity. ifxis anmpc, returnTrueif eitherx.realorx.imagis infinite. otherwise returnFalse. โญis_nan() -> boolโ returnTrueifxis NaN (Not-A-Number) elseFalse. ๐is_zero() -> boolโ returnTrueifxis equal to0. ifxis anmpc, returnTrueif bothx.realandx.imagare equal to0. ๐imagโ imaginary component ๐precisionโ precision in bits ๐rcโ return code ๐realโ real component ๐ซถ
โจ mpc Functions โจ
gmpy2.acos(x, /) -> mpfr | mpcโ returns inverse cosine ofx; result in radians. ๐ธgmpy2.acosh(x, /) -> mpfr | mpcโ returns inverse hyperbolic cosine ofx. ๐ฆgmpy2.asin(x, /) -> mpfr | mpcโ returns inverse sine ofx; result in radians. ๐gmpy2.asinh(x, /) -> mpfr | mpcโ returns inverse hyperbolic sine ofx. ๐งgmpy2.atan(x, /) -> mpfr | mpcโ returns inverse tangent ofx; result in radians. ๐gmpy2.atanh(x, /) -> mpfr | mpcโ returns inverse hyperbolic tangent ofx. โญgmpy2.cos(x, /) -> mpfr | mpcโ returns cosine ofx;xin radians. ๐gmpy2.cosh(x, /) -> mpfr | mpcโ returns hyperbolic cosine ofx. ๐ฅgmpy2.div_2exp(x, n, /) -> mpfr | mpcโ returnsxdivided by2**n. ๐gmpy2.exp(x, /) -> mpfr | mpcโ returns the exponential ofx. ๐gmpy2.is_nan(x, /) -> boolโ returnTrueifxis NaN (Not-A-Number) elseFalse. ๐gmpy2.is_zero(x, /) -> boolโ returnTrueifxis equal to0. ifxis anmpc, returnTrueif bothx.realandx.imagare equal to0. ๐gmpy2.log(x, /) -> mpfr | mpcโ returns the natural logarithm ofx. ๐gmpy2.log10(x, /) -> mpfr | mpcโ returns the base-10 logarithm ofx. ๐ซถgmpy2.mpc_random(random_state, /) -> mpcโ returns a uniformly distributed number in the unit square[0,1]x[0,1]. ๐ฒgmpy2.mul_2exp(x, n, /) -> mpfr | mpcโ returnsxmultiplied by2**n. โจgmpy2.norm(x, /) -> mpfrโ returns the norm of a complexx.norm(x)is defined asx.real**2 + x.imag**2.abs(x)is the square root ofnorm(x). ๐gmpy2.phase(x, /) -> mpfrโ returns the phase angle, also known as argument, of a complexx. โญgmpy2.polar(x, /) -> tuple[mpfr, mpfr]โ returns the polar coordinate form of a complexxthat is in rectangular form. ๐gmpy2.proj(x, /) -> mpcโ returns the projection of a complexxon to the Riemann sphere. ๐gmpy2.rect(r, phi, /) -> mpcโ returns the rectangular coordinate form of a complex number that is given in polar form. ๐gmpy2.root_of_unity(n, k, /) -> mpcโ returns then-th root ofmpc(1)raised to thek-th power.. (yes, two dots, iconic) ๐gmpy2.sin(x, /) -> mpfr | mpcโ returns sine ofx;xin radians. ๐gmpy2.sin_cos(x, /) -> tuple[mpfr | mpc, mpfr | mpc]โ returns a tuple containing the sine and cosine ofx;xin radians. ๐ซถgmpy2.sinh(x, /) -> mpfr | mpcโ returns hyperbolic sine ofx. ๐ฆgmpy2.sqrt(x, /) -> mpfr | mpcโ returns the square root ofx. ๐ธgmpy2.tan(x, /) -> mpfr | mpcโ returns tangent ofx;xin radians. ๐ฅgmpy2.tanh(x, /) -> mpfr | mpcโ returns hyperbolic tangent ofx. ๐ง
๐ Generic Functions ๐
gmpy2.add(x, y, /) -> mpz | mpq | mpfr | mpcโ returnsx + y. ๐gmpy2.div(x, y, /) -> mpz | mpq | mpfr | mpcโ returnsx / y; uses true division. periodt. ๐gmpy2.mul(x, y, /) -> mpz | mpq | mpfr | mpcโ bestie it literally returnsx * y. that's it, that's the function ๐gmpy2.sub(x, y, /) -> mpz | mpq | mpfr | mpcโ returnsx - y. subtraction nation rise ๐ซถgmpy2.square(x, /) -> mpz | mpq | mpfr | mpcโ returnsx * x. the glow-up of multiplying by yourself โจgmpy2.f2q(x, err=0, /) -> mpz | mpqโ returns the 'best'mpqthat approximatesxwithin a relative error oferr. default is the precision ofx. it uses a Stern-Brocot tree to hunt down that 'best' approximation (iykyk ๐ง). if the denominator turns out to be 1, you get anmpzobject back instead. and iferr < 0, the relative error is2.0 ** err. not me thinking that's kinda iconicgmpy2.fma(x, y, z, /) -> mpz | mpq | mpfr | mpcโ returns the correctly rounded result of(x * y) + z. fused multiply-add serving precision ๐gmpy2.fms(x, y, z, /) -> mpz | mpq | mpfr | mpcโ returns the correctly rounded result of(x * y) - z. yes it's fma's chaotic sibling ๐gmpy2.cmp_abs(x, y, /) -> intโ returns-1ifabs(x) < abs(y);0ifabs(x) = abs(y); and1otherwise. comparing the vibes, ignoring the signs ๐
๐ธ Miscellaneous Functions ๐ธ
gmpy2.digits(x, base=10, prec=0, /) -> strโ returns a string representing the numberx. it's giving stringified ๐gmpy2.from_binary(bytes, /) -> mpz | xmpz | mpq | mpfr | mpcโ returns a Python object from a byte sequence that was created byto_binary(). the reunion arc ๐ฅนgmpy2.license() -> strโ returns a string giving license information. read the fine print bestie, it's important ๐gmpy2.mp_limbsize() -> intโ returns the number of bits per limb. limbs!! like a body?? no it's just GMP internals ๐ฆgmpy2.mp_version() -> strโ returns a string giving the current GMP version.gmpy2.mpc_version() -> strโ returns a string giving the current MPC version.gmpy2.mpfr_version() -> strโ returns a string giving the current MPFR version.gmpy2.random_state(seed=0, /) -> objectโ returns a brand new object holding state info for the random number generator. you can optionally pass an integer as the seed value ๐ฒgmpy2.to_binary(x, /) -> bytesโ returns a Python byte sequence that is a portable binary representation of a gmpy2 objectx. you can hand that byte sequence tofrom_binary()and get an exact copy ofx's value back. raises aTypeErrorifxisn't a gmpy2 object. no fakes allowed ๐ โโ๏ธgmpy2.version() -> strโ returns a string giving the current GMPY2 version. the origin story fr fr โญ
๐ง Cython usage ๐ง
the gmpy2 module provides a C-API that can be used conveniently from Cython. all the types and functions are declared in the header gmpy2.pxd, which gets installed automatically in your Python path right alongside the library. slay ๐
โจ Initialization โจ
to use the C-API you need to make one single call to the function void import_gmpy2(void). one call. that's the whole ritual ๐ฏ๏ธ
๐ฆ 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. they match, that's the whole point ๐
fast type checking can be done with the following C functions:
bint MPZ_Check(object)โ equivalent toisinstance(obj, mpz)bint MPQ_Check(object)โ equivalent toisinstance(obj, mpq)bint MPFR_Check(object)โ equivalent toisinstance(obj, mpfr)bint MPC_Check(object)โ equivalent toisinstance(obj, mpc)
๐ Object creation ๐
to create a new gmpy2 type there are four basic functions:
mpz GMPy_MPZ_New(void * ctx)โ create a newmpzobject from a given contextctxmpq GMPy_MPQ_New(void * ctx)โ create a newmpqobject from a given contextctxmpfr MPFR_New(void * ctx, mpfr_prec_t prec)โ create a newmpfrobject with a given contextctxand precisionprecmpc MPC_New(void * ctx, mpfr_prec_t rprec, mpfr_prec_t iprec)โ create a newmpcobject with a given contextctx, and precisionsrprecandiprecof respectively the real and imaginary parts
the context can be set to NULL and controls the default behavior (e.g. precision). setting it to NULL is like letting the algorithm pick your outfit for you, honestly relatable ๐
the gmpy2.pxd header also provides a convenience macro to wrap a (copy of) an mpz_t, mpq_t, mpfr_t or mpc_t object into the corresponding gmpy2 type:
mpz GMPy_MPZ_From_mpz(mpz_srcptr z)โ return a newmpzobject with a givenmpz_tvaluezmpq GMPy_MPQ_From_mpq(mpq_srcptr q)โ return a newmpqobject from a givenmpq_tvalueqmpq GMPy_MPQ_From_mpz(mpz_srcptr num, mpz_srcptr den)โ return a newmpqobject with a givenmpz_tnumeratornumandmpz_tdenominatordenmpfr GMPy_MPFR_From_mpfr(mpfr_srcptr x)โ return a newmpfrobject with a givenmpfr_tvaluexmpc GMPy_MPC_From_mpc(mpc_srcptr c)โ return a newmpcobject with a givenmpc_tvaluecmpc GMPy_MPC_From_mpfr(mpfr_srcptr re, mpfr_srcptr im)โ return a newmpcobject with a givenmpfr_treal partreandmpfr_timaginary partim
๐ Access to the underlying C type ๐
each of the gmpy2 objects has a field corresponding to the underlying C type. the following functions give you access to that 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 that it depends on are installed in the Python path. to make Cython and the C compiler aware that these files exist, the Python path should be part of the include directories. manifesting โจ
quick reminder bestie: import_gmpy2() needs to be called before any other function of the C-API. do not skip this step, it WILL haunt you ๐
here's 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. go read the docs, they ate ๐
๐ 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 one of these methods allows 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'>
look at that, your own little class getting adopted into the gmpy2 family ๐ฅน
โญ Arithmetic operations โญ
gmpy2 allows arithmetic operations between gmpy2 numbers and objects with conversion methods. operations with objects that implement floating conversion and exact conversion methods are not supported. that means only the following cases are supported:
- an integer type has to implement
__mpz__ - a rational type has to implement
__mpq__and can implement__mpz__ - a real type has to implement
__mpfr__ - a complex type has 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')
the way that mpz(2) + q just becomes mpq(7,2)?? cheating but in a slay way ๐
๐ Release Notes ๐
๐ Changes in gmpy2 2.2.1 ๐
- fix internal use of
charwhenintshould be used. (jamesjer) - add
xmpz.bit_count(). (skirpichev)
๐ Changes in gmpy2 2.2.0 ๐
- remove support for versions of Python < 3.7. (skirpichev)
- support more modern build tools. (skirpichev)
- use
contextvarsto manage gmpy2 contexts. (casevh) _mpmathfunctions now use the 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) gcd()/lcm()now uses the vectorcall protocol. (skirpichev)- expose
contexttype. (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. the most nothing-burger release, and honestly? respect ๐
๐ Changes in gmpy2 2.1.4 ๐
- version bump to fix wheel issues. no code changes. again โจ
๐ Changes in gmpy2 2.1.3 ๐
- fix
mpz(-3).is_prime(). - add
powmod_sec(). - fix
mpfr('inf')andmpfr('nan')if subnormalization is enabled. powmod()andpowmod_sec()release the GIL.- fix error messages for
iroot(x,n)for largen. - add
powmod_base_list()andpowmod_exp_list()(experimental). - fix
gmpy2.mpq(mpq, int). - fix issues with
INF,NAN, andmpfr("-0")when subnormalization isTrue
๐ Changes in gmpy2 2.1.2 ๐
- code cleanup.
- support Apple Silicon binary wheels.
is_prime(-2)now returnsFalse. 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 an exception if inverse does not exist.- add context methods.
- Major code refactoring was literally required to properly support thread-safe contexts. it's giving surgery bestie ๐ฅ
__str__and__repr__no longer tack an"L"onto the end on Python 2. the L era is over ๐mpq(mpfr)now returns the exact result. no rounding drama โจ- Fixed
repr(mpc)for precision >325 bits. - Intermediate conversions of Integer to mpfr are now done with the full precision of the Integer.
- Support for interaction with the Decimal type? Removed. gone, bye ๐
- No longer attempt to override the memory allocation functions. we said no thank you ๐
- gmpy2 types got registered into the numeric tower. iconic behavior honestly ๐
mpz(x)now callsint(x)ifmpz()doesn't know how to convertxdirectly.mpzgot converted to an actual type using__new__instead of being a factory function. glow up ๐ฆ- Bug fix for small
mpfr** small Python integer. (the little guys matter too ๐ญ) - Compiles with Python 3.11. periodt.
โจ Changes in gmpy2 2.1.0rc2
- Documentation updates. (yes bestie, the docs got love too ๐)
- Improvements to the build environment. ๐ ๏ธ
โจ Changes in gmpy2 2.1.0rc1
- Added support for embedded underscore characters in string literals.
1_000_000core ๐ธ - GIL release now allowed for
mpz/xmpz/mpqtypes only. nobody else, sorry ๐ซ
โจ Changes in gmpy2 2.1.0b6
- Improved argument type processing by saving type information, which decreases the number of type check calls. Extra helpful for
mpfrandmpctypes. (Not complete, but the common operations are done.) ๐โโ๏ธ๐จ - Resolved a bug in
mpfrโmpqconversion; issue #287. - Added limited support for releasing the GIL; disabled by default; see
context.allow_release_gil. - Refactored how in-place operations are handled for
mpzandxmpztypes; in-place operations onxmpzwill only return anxmpzresult. no switching up on us ๐ - Refactored conversion to C integer types. Some exception types changed to reflect Python types.
gcd()andlcm()now support more than two arguments, to align with the matching functions over in the math module. glow up for the gcd girlies ๐ซถ
โจ Changes in gmpy2 2.1.0b5
- Avoided an MPFR bug in
mfr_fac_ui(factorial()) on platforms wherelongis 32-bits and the argument is >= 44787929. ๐ง - Fixed testing bugs with Python 2.7.
- Fixed
mpz(0)to Clongorlong long. - Fixed incorrect results in
f2q(). ๐ญ - Adjusted the test suite to reflect output changes in MPFR 4.1.0.
โจ Changes in gmpy2 2.1.0b4
- Fixed comparisons with
mpqand custom rational objects. - Fixes for some uncommon integer conversion scenarios. edge cases, we see you ๐
โจ Changes in gmpy2 2.1.0b3
- Version bump only. that's it, that's the change ๐
โจ Changes in gmpy2 2.1.0b2
- Many bug fixes. slay ๐๐จ
โจ Changes in gmpy2 2.1.0b1
- Added
cmp()andcmp_abs(). - Improved compatibility with the
numbersmodule protocol. ๐ค - Many bug fixes.
โจ Changes in gmpy2 2.1.a05
- Fixed
qdiv()not returningmpzwhen it should. ๐ - Added
root_of_unity(). ๐ฑ
โจ Changes in gmpy2 2.1.0a4
- Fixed issue 204; a missing file for Cython.
- Additional support for MPFR 4:
- Added
fmma()andfmms().
- Added
โจ Changes in gmpy2 2.1.0a3
- Updates to
setup.py. - Initial support for MPFR4:
- Added
mpfr_nrandom() mpfr_grandom()now calls nrandom twice; it may return different values versus MPFR3.- Added
rootn(); same asroot()except different sign when taking an even root of-0.0.
- Added
โจ Changes in gmpy2 2.1.0a2
- Revised build process. ๐ ๏ธ
- Removal of unused code/macros. declutter era ๐งน
- Cleanup of the Cython interface.
โจ Changes in gmpy2 2.1.0a1
- Thread-safe contexts are now supported. Properly integrating them required an extensive rewrite of almost all internal functions. no cap, everything got touched.
- MPFR and MPC are now required. It is no longer possible to build a gmpy2 that only supports the GMP library. they're a package deal now fr fr ๐
- 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 involvingmpzinstances, so it returns a rational result instead of a floating point result. bestie choice honestly. - gmpy2 types are now registered in the numeric tower of the
numbersmodule. - In previous versions of gmpy2,
mpz()was a factory function that returned anmpzinstance. It's now an actual type. Same glow up for the other gmpy2 types. ๐ - If a Python object has an
__mpz__method, it will be called bympz()to let an unrecognized type be converted to an mpz instance. Same deal for the other gmpy2 types. - A new C-API and Cython interface has been added. ๐
โจ Changes in gmpy2 2.0.4
- Fixed
bit_scan0()for negative values. - Changes to
setup.pyto allow static linking. - Fixed a performance regression with mpmath and Python 3. ๐๏ธ
โจ Changes in gmpy2 2.0.3
- Fixed
lucas2()andatanh(); they were returning incorrect values. oops ๐ฌ fixed now though.
โจ Changes in gmpy2 2.0.2
- Rebuilt the Windows binary installers due to an MPIR 2.6.0 bug in
next_prime(). ๐ช - Yet another fix for
is_extra_strong_lucas_prp().
โจ Changes in gmpy2 2.0.1
- Updated
setup.pyto work in more situations. - Corrected exception handling in basic operations with the
mpfrtype. - Fixed
InvalidOperationexception not being raised in certain circumstances. invert()now raises an exception if the modular inverse does not exist.- Fixed an internal exception in
is_bpsw_prp()andis_strong_bpsw_prp(). - Updated
is_extra_strong_lucas_prp()to the latest version. โจ
โจ Changes in gmpy2 2.0.0
- Fixed a segmentation fault in
_mpmath_normalize()(an undocumented helper function for mpmath). (casevh) ๐โ๐ - Fixed issues when compiled without support for MPFR. (casevh)
- Converting too large an
mpzto float now raisesOverflowErrorinstead of returninginf. (casevh) - Renamed
min2()/max2()tominnum()/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) ๐ซ
Known issues in gmpy2 2.0.0
- The test suite is still incomplete. we're working on it bestie ๐ญ
โจ Changes in gmpy2 2.0.0b4
- Added
__ceil__(),__floor__(),__trunc__(), and__round__()methods to thempzandmpqtypes. (casevh) ๐ - Added
__complex__()to thempctype. (casevh) round(mpfr)now correctly returns anmpztype. (casevh)- Added
mpz.denominatorandmpz.numerator. (casevh) - If no arguments are given to
mpz,mpq,mpfr,mpc, andxmpz, they return0of the appropriate type. (casevh) zero but make it โจtypedโจ - Fixed broken comparison between
mpzandmpqwhenmpzis 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)- Fixed warnings when shifting a 32-bit integer by 32 bits. (casevh)
- Faster conversion of the standard library
Fractiontype tompq. (casevh) ๐โโ๏ธ - Improved conversion of the
Decimaltype tompfr. (casevh) - Consistently return
OverflowErrorwhen convertinginf. (casevh) - Fixed
mpz.__format__()when the format code includes"#". (casevh) - Added
is_infinite()and deprecatedis_inf(). (casevh) - Added
is_finite()and deprecatedis_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
mpcobjects. (casevh) ๐พ - Faster code path for basic operations when both operands are
mpfrormpc. (casevh) - Fixed an
mpfr+ float segmentation fault. (casevh) ๐
โจ Changes in gmpy2 2.0.0b2
xmpzslice assignment can now increase the length of anxmpzinstance by specifying a value forstop. (casevh)- Fixed a reference counting bug in several
is_xxx_prp()tests. (casevh) - Added
iter_bits(),iter_clear(), anditer_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're slower than just using Python code. (casevh) bye girlies โ๏ธ - Bug fix in
gcd_extwhen both arguments are notmpz. (casevh) - Added
ieee()to create contexts for 32, 64, or 128 bit floats. (casevh) ๐ - Bug fix in
context()not settingemax/emincorrectly if they had been changed earlier. (casevh) - Contexts can now be used directly in a
withstatement without needing theset_context()/local_context()sequence. (casevh) main character energy tbh ๐ local_context()now accepts an optional context. (casevh)
โจ Changes in gmpy2 2.0.0b1
- Renamed to gmpy2, to allow backwards incompatible changes. (casevh)
- Renamed
'mpf'to'mpfr'to reflect the use of MPFR. (casevh) - Renamed the functions that manipulate individual bits to
bit_XXX()to align withbit_length(). - Added caching for
mpq. (casevh) ๐ - Added
rootrem(),fib2(),lucas(),lucas2(). (casevh) - Support for the changed hash function in Python 3.2. (casevh)
- โจ Added
is_even(),is_odd(). (casevh) - โจ Add caching of the calculated hash value. (casevh)
- โจ Add
xmpz(mutablempz) type. (casevh) - โจ Fix
mpqformatting 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
fcoformfloat 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 usinggmpy2.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)
- โจ Added
fsum(),degrees(),radians(). (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(), usempf.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
-DMPIRto include MPIR instead of GMP (casevh) - ๐ซถ Major code revisions to add support for Python 3.x (casevh)
- ๐ซถ Fixed bug in
binary()andqbinary()(casevh) - ๐ซถ Fixed bug in rich comparisons (casevh)
- ๐ซถ Added
%anddivmodsupport tompqandmpf(casevh) - ๐ซถ Changed memory allocation functions to use
PyMem(casevh) - ๐ซถ Removed small number interning (casevh)
- ๐ซถ Added
tdivmod,cdivmod, andfdivmod(casevh) - ๐ซถ Added more helper functions for
mpmath(casevh) - ๐ซถ Faster
mpz<>PyLongconversion (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->
mpzandmpz->long. (casevh) - ๐
Added "rich comparisons" to
mpz,mpqandmpftypes (aleaxit) - ๐ Added additional tests (casevh, aleaxit)
- ๐
Fixed bug when converting very large
mpztostr(casevh) - ๐
Faster conversion from
mpz->binary and binary->mpz(casevh) - ๐ Added support for pickling (casevh)
- ๐
Added
divexact(casevh) - ๐
Fixed
mpfcomparisons by roundingmpfresults when GMP returns a longer result. Addedfround()(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 equalshash(mpz)for large values. (casevh) - ๐ Changed
int()to return a long value instead ofOverFlowError. Complies with PEP 237. (casevh) - ๐ Added support in
setup.pyfor 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 thedecimal.Decimalclass (!) - ๐ฆ 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')[[str2mpqon 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
ValueErrortoOverflowErrorfor '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 andpow_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 ashash(x)for any Python number x - ๐ง workaround for GMP 3.1.1 bug,
mpz_rootwrongly returning 'exact' for non-exact root ifdest==source, which stopped needed value-error for inexactmpq**mpqoperations - ๐ง determined correct 'actual precision' of floats
- ๐ง explicitly stored precision with binary-form
mpf's - ๐ง extended explicit-bits request to all ->
mpfoperations (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
kroneckerandmpq_abs - ๐ gmpy-level workaround for
scan0/scan1bugs (?) in gmp 3.1.1 - ๐ added
qdiv;anynum->mpqsubstituted for all such conversions (alsoanynum->mpzandanynum->mpfby analogy, with care!) - ๐ added
global.fcoformfor optional use of intermediate string infloat2mpf(used for anyfloat->mpfconversion) - ๐ added
set_fcoformfunction forglobal.fcoformaccess - ๐ general cleanup of sources; added alloca for msvc++; - many sundry minor bugfixes & uniformization; - a little useful refactoring (more would be good...)
- ๐ added caching of
mpqobjects - ๐ power for
mpq - ๐ stern-brocot algorithm for
mpf->mpq(also exposed asf2q) - also used forfloat->mpq- with stricter tracking ofmpf's requested-precision - addedgetrprecmethod tompf,getrprecmodule-function - ๐ exposed
ceil,floorandtruncmethods/functions formpf's - ๐ changed a couple exceptions from value to zerodivision
- ๐ added
'qual'and'floa'options togmpy.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.hintroducing 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
.combas a synonym of.bincoef
๐ Changes in gmpy 0.3 ๐
- ๐ฆ performance tweaks via
mpz-caching & fixed-constants - ๐ฆ added get/set functions for
zcache,zcomin/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)tompz_sgn(X) - ๐ฆ cleaned up
Py_BuildValueusage (NvsO, explicit-() for tuples) - ๐ฆ added
numdigits,lowbits,root,next_prime,invert,popcount, - ๐ฆ
hamdist,scan0,scan1 - ๐ฆ renamed
bintobincoef
๐ฆ Changes in gmpy 0.2 ๐ฆ
15 Nov 2000
- ๐ pre-alpha: bugfixes re formatting (tx, Peanu!)
- ๐ no tags on
oct()andhex()ofmpz's - ๐ insert 'tagoff' in options (
gmpy.mpz()vsmpz()in repr) (for Peanu!) - speedups for
_nonzero&_cmpโ ty, Peanu! ๐ซถ - slight speedup (7/8%?) for excess reallocs 4<->8 bytes โ Peanu's help again, we love to see it ๐
- added
copy/fcopy;bin;fib;removeโ new friends joined the party โจ
๐ Changes in gmpy 0.1 ๐
6 Nov 2000 โ literally the origin story, the pilot episode, the Big Bang of gmpy ๐ธ
- pre-alpha โ first placed on sourceforge ๐
Index <>Search Page <>
๐ Author ๐
Case Van Horsen
๐ Copyright ๐
2012 - 2024, Case Van Horsen
ok bestie that's a wrap, the whole page, the whole vibe, we ate and left exactly zero crumbs ๐
โจ this manual page is version 2.2, it got stamped with 1783079689 (that's the generation timestamp, girlypop), and it lives its best life under the name GMPY2(3) โ go forth and integer real hard ๐ฆ๐
๐ฆ where this page comes from
- ubuntu stonking: python-gmpy2-common 2.2.1-5 ยท LGPL-3.0-or-later
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms