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:


๐Ÿ“š 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 the gmpy2 from sources. To install required dependencies before, run:
pacman -S gcc gmp-devel mpfr-devel mpc-devel python-setuptools python-pip

If you are a developer or like to get the latest updates as they come, be sure to install from the git repository and include required extra dependencies, for example the optional "tests" list, which include packages required for testing:

git clone git://github.com/aleaxit/gmpy.git
cd gmpy
pip install -e .[tests]

Next you may want to run full set of unit tests to make sure everything works:

pytest test/

๐ŸŽ“ Tutorial ๐ŸŽ“

Start by importing the contents of the package with:

>>> from gmpy2 import *
Note: The use of from gmpy2 import * is not recommended in real code. The names in gmpy2 have been chosen to avoid conflict with Python's builtin names but gmpy2 does use names that may conflict with other modules or variable names. In normal usage youโ€™ll probably only want to import the classes and functions that you actually need.

Lets look first on some examples of arbitrary precision arithmetic with integer and rational types:

>>> mpz(99) * 43
mpz(4257)
>>> pow(mpz(99), 37, 59)
mpz(18)
>>> isqrt(99)
mpz(9)
>>> isqrt_rem(99)
(mpz(9), mpz(18))
>>> gcd(123, 27)
mpz(3)
>>> lcm(123, 27)
mpz(1107)
>>> (mpz(123) + 12) / 5
mpfr('27.0')
>>> (mpz(123) + 12) // 5
mpz(27)
>>> (mpz(123) + 12) / 5.0
mpfr('27.0')
>>> mpz('123') + 1
mpz(124)
>>> 10 - mpz(1)
mpz(9)
>>> is_prime(17)
True
>>> mpz('1_000_000')
mpz(1000000)
>>> mpq(3, 7)/7
mpq(3,49)
>>> mpq(45, 3) * mpq(11, 8)
mpq(165,8)
>>> mpq(1, 7) * 11
mpq(11,7)

But gmpy2 also supports correctly rounded multiple precision real and complex arithmetic. The following example shows how to control precision settings and rounding modes:

>>> mpfr('1.2')
mpfr('1.2')
>>> mpfr(float('1.2'))
mpfr('1.2')
>>> ctx = get_context()
>>> ctx.precision
53
>>> ctx.precision = 100
>>> mpfr('1.2')
mpfr('1.2000000000000000000000000000006',100)
>>> mpfr(float('1.2'))
mpfr('1.1999999999999999555910790149937',100)
>>> ctx.precision = 53
>>> ctx.round = RoundUp
>>> const_pi()
mpfr('3.1415926535897936')
>>> ctx.round = RoundToNearest
>>> const_pi()
mpfr('3.1415926535897931')

You have seen, that if the precision is changed, then mpfr(float('1.2')) differs from mpfr('1.2'). To take advantage of the higher precision provided by the mpfr type, always pass constants as strings.

Floating point contexts also are used to control exceptional conditions. For example, division by zero can either return a floating-point positive infinity (default) or raise an exception.

>>> ctx.divzero
False
>>> mpfr(1)/0
mpfr('inf')
>>> ctx.trap_divzero = True
>>> mpfr(1)/0
Traceback (most recent call last):
...
gmpy2.DivisionByZeroError: division by zero
>>> ctx.divzero
True

Exceptions are normally raised in Python when the result of a real operation is not defined over the reals; for example, math.sqrt(-2) will raise a ValueError exception. The default context in gmpy2 implements similar behavior, but by setting allow_complex flag, complex results will be returned.

>>> sqrt(mpfr(-2))
mpfr('nan')
>>> ctx.allow_complex = True
>>> sqrt(mpfr(-2))
mpc('0.0+1.4142135623730951j')

Contexts can also be used as context managers in conjunction with Python's with statement to temporarily change the current context settings for a block of code.

>>> print(const_pi())
3.1415926535897931
>>> with context(precision=100) as ctx:
...   print(const_pi())
...   ctx.precision += 20
...   print(const_pi())
...
3.1415926535897932384626433832793
3.1415926535897932384626433832795028847
>>> print(const_pi())
3.1415926535897931

It's possible to set different precision settings for real and imaginary components.

>>> ctx = get_context()
>>> ctx.real_prec = 60
>>> ctx.imag_prec = 70
>>> sqrt(mpc('1+2j'))
mpc('1.272019649514068965+0.78615137775742328606947j',(60,70))

All gmpy2 numeric types support Python's "new style" string formatting available in formatted string literals (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. bytes and bytearray are examples of built-in objects that support the buffer protocol.
  • byteorder โ€” The byte order used to represent the integer. If byteorder is 'big', the most significant byte is at the beginning of the byte array. If byteorder is 'little', the most significant byte is at the end of the byte array. To request the native byte order of the host system, use sys.byteorder as the byte order value.
  • signed โ€” Indicates whether two's complement is used to represent the integer.

__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 with 0b, 0o or 0x
  • optional width
  • optional conversion code:
    • 'd' -> decimal format
    • 'b' -> binary format
    • 'o' -> octal format
    • 'x' -> hex format
    • 'X' -> upper-case hex format

The default format is 'd'. 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 many 1-bits are set in abs(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() returns 0.
  • bit_scan0(n=0, /) -> int | None โ€” returns the index of the first 0-bit of x with index >= n. and n >= 0, always. if there are no more 0-bits in x at or above index n (which can only happen for x<0, assuming an infinitely long 2's complement format), then None is returned. ๐Ÿ˜ญ
  • bit_scan1(n=0, /) -> int | None โ€” returns the index of the first 1-bit of x with index >= n. n >= 0. if there are no more 1-bits in x at or above index n (which can only happen for x>=0, assuming an infinitely long 2's complement format), then None is returned. 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 between 2 to 62. a leading '-' is present if x<0, but no leading '+' shows up if x>=0.
  • is_congruent(y, m, /) -> bool โ€” returns True if x is congruent to y modulo m, else it returns False. ๐Ÿ”
  • is_divisible(d, /) -> bool โ€” returns True if x is divisible by d, else False. clean division only ๐Ÿ’…
  • is_even() -> bool โ€” True if x is even, False otherwise. 2๏ธโƒฃ
  • is_odd() -> bool โ€” True if x is odd, False otherwise. 3๏ธโƒฃ
  • is_power() -> bool โ€” returns True if x is a perfect power (meaning there exists a y and an n > 1 such that x=y**n), else False. โœจ
  • is_prime(n=25, /) -> bool โ€” returns True if x is probably prime, else False if 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 โ€” returns 2 if x is definitely prime, 1 if x is probably prime, or 0 if x is definitely non-prime. x is checked for small divisors and up to n Miller-Rabin tests are performed. reasonable values of n are between 15 and 50. so likeโ€ฆ 15 to 50, not 4, not 9000.
  • is_square() -> bool โ€” returns True if x is a perfect square, else False. ๐ŸŸช
  • 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 between 2 and 62. โš ๏ธ heads up: the value returned may be 1 too 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 OverflowError is raised if the integer is not representable with the given number of bytes.
    • byteorder โ€” the byte order used to represent the integer. if byteorder is 'big', the most significant byte is at the beginning of the byte array. if byteorder is 'little', the most significant byte is at the end of the byte array. to request the native byte order of the host system, use sys.byteorder as the byte order value.
    • signed โ€” determines whether two's complement is used to represent the integer. if signed is False and a negative integer is given, an OverflowError is raised. ๐Ÿšจ
  • denominator โ€” the denominator of a rational number in lowest terms.
  • imag โ€” the imaginary part of a complex number. 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 of 1-bits set in abs(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) returns 0.
  • 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 first 0-bit of x with index >= n. n >= 0. if there are no more 0-bits in x at or above index n (which can only happen for x<0, assuming an infinitely long 2's complement format), then None is returned.
  • gmpy2.bit_scan1(x, n=0, /) -> int | None โ€” returns the index of the first 1-bit of x with index >= n. n >= 0. if there are no more 1-bits in x at or above index n (which can only happen for x>=0, assuming an infinitely long 2's complement format), then None is returned.
  • gmpy2.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 by 2**n. the quotient is rounded towards +Inf (ceiling rounding). x must be an integer. n must be >0.
  • gmpy2.c_divmod(x, y, /) -> tuple[mpz <#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 by 2**n. the quotient is rounded towards +Inf (ceiling rounding) and the remainder will be negative. x must be an integer. n must be >0.
  • gmpy2.c_mod(x, y, /) -> mpz <#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 by 2**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 as bincoef(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 that b*x == a mod m. raises a ZeroDivisionError exception 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 as n*(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 by 2**n. the quotient is rounded towards -Inf (floor rounding). x must be an integer. n must be >0.
  • gmpy2.f_divmod(x, y, /) -> tuple[mpz <#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 by 2**n. the quotient is rounded towards -Inf (floor rounding) and the remainder will be positive. x must be an integer. n must be >0.
  • gmpy2.f_mod(x, y, /) -> mpz <#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 by 2**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. ๐ŸŽ€ see factorial(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) where g == gcd(a,b) and g == 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 integers x and y. lowkey useful for error correction vibes ๐Ÿ˜ญ
  • gmpy2.invert(x, m, /) -> mpz <#gmpy2.mpz> โ€” returns y such that x*y == 1 modulo m. Raises ZeroDivisionError if no inverse exists. no inverse? tragic ๐Ÿ’€
  • gmpy2.iroot(x, n, /) -> tuple[mpz <#gmpy2.mpz>, bool] โ€” returns the integer n-th root of x and a boolean that is True iff 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 that y is the integer n-th root of x and x=y**n + r. x >= 0. n > 0. ๐ŸŽ€
  • gmpy2.is_congruent(x, y, m, /) -> bool โ€” returns True if x is congruent to y modulo m, else returns False. ๐Ÿ’…
  • gmpy2.is_divisible(x, d, /) -> bool โ€” returns True if x is divisible by d, else returns False. ๐Ÿซถ
  • gmpy2.is_even(x, /) -> bool โ€” returns True if x is even, False otherwise. even? periodt ๐ŸŒธ
  • gmpy2.is_odd(x, /) -> bool โ€” returns True if x is odd, False otherwise. odd one out energy ๐Ÿ‘‘
  • gmpy2.is_power(x, /) -> bool โ€” returns True if x is a perfect power (there exists a y and an n > 1, such that x=y**n), else returns False. ๐Ÿ”ฅ
  • gmpy2.is_prime(x, n=25, /) -> bool โ€” returns True if x is probably prime, else False if x is definitely composite. x is checked for small divisors and up to n Miller-Rabin tests are performed. probably prime? iykyk ๐ŸŒˆ
  • gmpy2.is_probab_prime(x, n=25, /) -> int โ€” returns 2 if x is definitely prime, 1 if x is probably prime, or 0 if x is definitely non-prime. x is checked for small divisors and up to n Miller-Rabin tests are performed. Reasonable values of n are between 15 and 50. iconic โญ
  • gmpy2.is_square(x, /) -> bool โ€” returns True if x is a perfect square, else returns False. ๐Ÿ’–
  • gmpy2.isqrt(x, /) -> mpz <#gmpy2.mpz> โ€” returns the integer square root of a non-negative integer x. ๐ŸŽ€
  • gmpy2.isqrt_rem(x, /) โ€” returns a 2-element tuple (s,t) such that s=isqrt(x) and t=x-s*s. x >=0. ๐Ÿฆ‹
  • gmpy2.jacobi(x, y, /) -> mpz <#gmpy2.mpz> โ€” returns the Jacobi symbol (x|y). y must 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 of integers. ๐Ÿงš
  • gmpy2.legendre(x, y, /) -> mpz <#gmpy2.mpz> โ€” returns the Legendre symbol (x|y). y is 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 between 0 and n-1. ๐ŸŽ€
  • gmpy2.mpz_rrandomb(random_state, bit_count, /) -> mpz <#gmpy2.mpz> โ€” returns a random integer between 0 and 2**bit_count-1 with long sequences of zeros and one in its binary representation. ๐Ÿ’€
  • gmpy2.mpz_urandomb(random_state, bit_count, /) -> mpz <#gmpy2.mpz> โ€” returns uniformly distributed random integer between 0 and 2**bit_count-1. ๐Ÿ”ฅ
  • gmpy2.multi_fac(n, m, /) -> mpz <#gmpy2.mpz> โ€” returns the exact m-multi factorial of n. The m-multifactorial is defined as n*(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 of x in the given base. Values for base can range between 2 and 62. The value returned may be 1 too large. ๐Ÿ˜ญ
  • gmpy2.pack(lst, n, /) -> mpz <#gmpy2.mpz> โ€” packs a list of integers lst into a single mpz by concatenating each integer element of lst after padding to length n bits. Raises an error if any integer is negative or greater than n bits in length. ๐ŸŽ€
  • gmpy2.popcount(x, /) -> int โ€” returns the number of 1-bits set in x. If x<0, the number of 1-bits is infinite so -1 is returned in that case. ๐Ÿ’…
  • gmpy2.powmod(x, y, m, /) -> mpz <#gmpy2.mpz> โ€” returns (x**y) mod m. Same as the three argument version of Python's built-in pow, but converts all three arguments to mpz. ๐Ÿ”ฅ
  • gmpy2.powmod_exp_list(base, exp_lst, mod, /) -> list[mpz <#gmpy2.mpz>, ...] โ€” returns list(powmod(base, i, mod) for i in exp_lst). Will always release the GIL. (Experimental in gmpy2 2.1.x). ๐Ÿงš
  • gmpy2.powmod_base_list(base_lst, exp, mod, /) -> list[mpz <#gmpy2.mpz>, ...] โ€” returns list(powmod(i, exp, mod) for i in base_lst). Will always release the GIL. (Experimental in gmpy2 2.1.x). ๐ŸŒธ
  • gmpy2.powmod_sec(x, y, m, /) -> mpz <#gmpy2.mpz> โ€” returns (x**y) mod m. Calculates x ** y (mod m) but using a constant time algorithm to reduce the risk of side channel attacks. y must be an integer >0. m must be an odd integer. ๐Ÿ‘‘
  • gmpy2.prev_prime(x, /) -> mpz <#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 to n. ๐Ÿ’–
  • gmpy2.remove(x, f, /) -> tuple[mpz <#gmpy2.mpz>, mpz <#gmpy2.mpz>] โ€” returns a 2-element tuple (y,m) such that x=y*(f**m) and f does not divide y. Remove the factor f from x as many times as possible. m is the multiplicity f in x. f > 1. โœจ
  • gmpy2.t_div(x, y, /) -> mpz <#gmpy2.mpz> โ€” returns the quotient of x divided by y. The quotient is rounded towards 0. x and y must be integers. ๐Ÿ’…
  • gmpy2.t_div_2exp(x, n, /) -> mpz <#gmpy2.mpz> โ€” returns the quotient of x divided by 2**n. The quotient is rounded towards zero (truncation). n must be >0. ๐ŸŽ€
  • gmpy2.t_divmod(x, y, /) -> tuple[mpz <#gmpy2.mpz>, mpz <#gmpy2.mpz>] โ€” returns the quotient and remainder of x divided by y. The quotient is rounded towards zero (truncation) and the remainder will have the same sign as x. x and y must be integers. ๐Ÿฆ‹
  • gmpy2.t_divmod_2exp(x, n, /) -> tuple[mpz <#gmpy2.mpz>, mpz <#gmpy2.mpz>] โ€” returns the quotient and remainder of x divided by 2**n. The quotient is rounded towards zero (truncation) and the remainder will have the same sign as x. x must be an integer. n must be >0. โœจ
  • gmpy2.t_mod(x, y, /) -> mpz <#gmpy2.mpz> โ€” returns the remainder of x divided by y. The remainder will have the same sign as x. x and y must be integers. ๐Ÿ’œ
  • gmpy2.t_mod_2exp(x, n, /) -> mpz <#gmpy2.mpz> โ€” returns the remainder of x divided by 2**n. The remainder will have the same sign as x. x must be an integer. n must be >0. ๐ŸŒธ
  • gmpy2.unpack(x, n, /) -> list โ€” unpacks an integer x into a list of n-bit values. Equivalent to repeated division by 2**n. Raises error if x is 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 โ€” xmpz objects 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 with 0b, 0o or 0x
  • optional width
  • optional conversion code:
    • 'd' -> decimal format
    • 'b' -> binary format
    • 'o' -> octal format
    • 'x' -> hex format
    • 'X' -> upper-case hex format

The default format is 'd'. 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() returns 0. 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 by p,q, but mod n. Ground rules bestie: p*p - 4*q must not equal 0, k must be >= 0, and n must be > 0. no exceptions ๐Ÿ’…
  • gmpy2.lucasv(p, q, k, /) -> mpz โ€” the k-th element of the Lucas V sequence defined by p,q. rules of the house: p*p - 4*q must not equal 0, and k must be >= 0.
  • gmpy2.lucasv_mod(p, q, k, n, /) -> mpz โ€” k-th element of the Lucas V sequence defined by p,q, but (you guessed it) mod n. same vibes check: p*p - 4*q must not equal 0, k >= 0, and n > 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 finite decimal.Decimal instance into a rational number, exactly. no rounding nonsense here.
  • classmethod from_float(f, /) -> mpq โ€” converts a finite float to 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 of x. and since x is not a complex number, this is literally just a new reference to x. iconic minimal effort ๐Ÿ’€
  • digits(base=10, /) -> str โ€” gives you a Python string of x in the given base. allowed bases are 2 to 62, default is 10. A leading '-' shows up if x<0, but there's no leading '+' if x>=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 โ€” returns x/y as an mpz if that's actually possible, otherwise as an mpq when x isn't exactly divisible by y. 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 โ€” returns abs(x), and the context gets applied to the result.
  • acos(x, /) -> mpfr | mpc โ€” inverse cosine of x; result in radians.
  • acosh(x, /) -> mpfr | mpc โ€” inverse hyperbolic cosine of x.
  • add(x, y, /) -> mpz | mpq | mpfr | mpc โ€” returns x + y.
  • agm(x, y, /) -> mpfr โ€” arithmetic-geometric mean of x and y.
  • ai(x, /) -> mpfr โ€” Airy function of x.
  • asin(x, /) -> mpfr | mpc โ€” inverse sine of x; result in radians.
  • asinh(x, /) -> mpfr | mpc โ€” inverse hyperbolic sine of x.
  • atan(x, /) -> mpfr | mpc โ€” inverse tangent of x; result in radians.
  • atan2(y, x, /) -> mpfr โ€” arc-tangent of (y/x); result in radians.
  • atanh(x, /) -> mpfr | mpc โ€” inverse hyperbolic tanget of x. (yes, "tanget" โ€” we keep the lore exactly as written ๐Ÿซถ)
  • cbrt(x, /) -> mpfr โ€” the cube root of x.
  • ceil(x, /) -> mpfr โ€” returns an mpfr that is the smallest integer >= x.
  • check_range(x, /) -> mpfr โ€” returns a new mpfr whose exponent lies within the range of emin and emax specified 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 of x; x in radians.
  • cosh(x, /) -> mpfr | mpc โ€” hyperbolic cosine of x.
  • cot(x, /) -> mpfr โ€” cotangent of x; x in radians.
  • coth(x, /) -> mpfr โ€” hyperbolic cotangent of x.
  • csc(x, /) -> mpfr โ€” cosecant of x; x in radians.
  • csch(x, /) -> mpfr โ€” hyperbolic cosecant of x.
  • degrees(x, /) -> mpfr โ€” converts angle x from radians to degrees.
โš ๏ธ heads up bestie: in rare cases the result may not be correctly rounded. not a drill.
  • digamma(x, /) -> mpfr โ€” digamma of x.
  • div(x, y, /) -> mpz | mpq | mpfr | mpc โ€” returns x / y; uses true division.
  • div_2exp(x, n, /) -> mpfr | mpc โ€” returns mpfr or mpc divided by 2**n.
  • divmod(x, y, /) -> tuple[mpz | mpfr, mpz | mpq | mpfr] โ€” returns divmod(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 of x.
  • erf(x, /) -> mpfr โ€” error function of x.
  • erfc(x, /) -> mpfr โ€” complementary error function of x.
  • exp(x, /) -> mpfr | mpc โ€” the exponential of x.
  • exp10(x, /) -> mpfr โ€” returns 10**x.
  • exp2(x, /) -> mpfr โ€” returns 2**x.
  • expm1(x, /) -> mpfr โ€” returns exp(x) - 1.
  • factorial(n, /) -> mpfr โ€” the floating-point approximation to the factorial of n.
if you want the exact integer result, go see fac() instead. this one's just the vibe approximation ๐ŸŒธ
  • floor(x, /) -> mpfr โ€” returns an mpfr that is the largest integer <= x.
  • floor_div(x, y, /) -> mpz | mpfr โ€” returns x // 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 โ€” returns x - n*y where n is the integer quotient of x/y, rounded toward 0.
  • fms(x, y, z, /) -> mpz | mpq | mpfr | mpc โ€” the correctly rounded result of (x * y) - z.
  • frac(x, /) -> mpfr โ€” fractional part of x.
  • frexp(x, /) -> tuple[int, mpfr] โ€” a tuple with the exponent and mantissa of x.
  • fsum(iterable, /) -> mpfr โ€” an accurate sum of the values in the iterable. no floating point drama ๐Ÿ’…
  • gamma(x, /) -> mpfr โ€” gamma of x.
  • gamma_inc(a, x, /) -> mpfr โ€” the (upper) incomplete gamma of a and x.
  • hypot(x, y, /) -> mpfr โ€” the square root of (x**2 + y**2).
  • is_finite(x, /) -> bool โ€” True if x is an actual number (i.e. non NaN or Infinity). If x is an mpc, returns True if both x.real and x.imag are finite.
  • is_infinite(x, /) -> bool โ€” True if x is +Infinity or -Infinity. If x is an mpc, returns True if either x.real or x.imag is infinite. Otherwise it's False.
  • is_integer(x, /) -> bool โ€” True if x is an integer; False otherwise.
  • is_nan(x, /) -> bool โ€” True if x is NaN (Not-A-Number), else False.
  • is_regular(x, /) -> bool โ€” True if x is not zero, NaN, or Infinity; False otherwise.
  • is_signed(x, /) -> bool โ€” gives you True when the sign bit of x is set โœจ
  • is_zero(x, /) -> bool โ€” True if x is equal to 0. And if x is an mpc? Then it's True only when both x.real and x.imag are equal to 0 ๐Ÿ‘‘
  • j0(x, /) -> mpfr โ€” first kind Bessel function of order 0 of x ๐Ÿ’ซ
  • j1(x, /) -> mpfr โ€” first kind Bessel function of order 1 of x
  • jn(n, x, /) -> mpfr โ€” first kind Bessel function of order n of x. โš ๏ธ not me telling you this again but: the order of the arguments changed in gmpy2 2.2.0a2
  • lgamma(x, /) -> tuple[mpfr, int] โ€” returns a tuple holding the logarithm of the absolute value of gamma(x), plus the sign of gamma(x) ๐Ÿซถ
  • li2(x, /) -> mpfr โ€” real part of the dilogarithm of x
  • lngamma(x, /) -> mpfr โ€” natural logarithm of gamma(x)
  • log(x, /) -> mpfr | mpc โ€” the natural logarithm of x ๐ŸŒธ
  • log10(x, /) -> mpfr | mpc โ€” the base-10 logarithm of x
  • log1p(x, /) -> mpfr โ€” natural logarithm of (1+x)
  • log2(x, /) -> mpfr โ€” base-2 logarithm of x
  • maxnum(x, y, /) -> mpfr โ€” the max of x and y. If x and y aren't mpfr, they get converted to mpfr first. Then the result is rounded to match the specified context ๐ŸŽ€ Bonus: if only one of x or y is a number, then that number is what comes back.
  • minnum(x, y, /) -> mpfr โ€” the min of x and y. Same deal as maxnum: not-mpfr inputs get converted to mpfr, the result gets rounded to match the specified context, and if only one of x or y is 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 โ€” returns mod(x, y). ๐Ÿšจ real talk though: overflow, underflow, and inexact exceptions are not supported for mpfr arguments.
  • modf(x, /) -> tuple[mpfr, mpfr] โ€” a tuple with the integer portion and the fractional portion of x ๐Ÿ’…
  • mul(x, y, /) -> mpz | mpq | mpfr | mpc โ€” returns x * y
  • mul_2exp(x, n, /) -> mpfr | mpc โ€” an mpfr or mpc multiplied by 2**n
  • next_above(x, /) -> mpfr โ€” the next mpfr from x toward +Infinity โฌ†๏ธ
  • next_below(x, /) -> mpfr โ€” the next mpfr from x toward -Infinity โฌ‡๏ธ
  • next_toward(x, y, /) -> mpfr โ€” the next mpfr from x heading in the direction of y. Result keeps the same precision as x.
  • norm(x, /) -> mpfr โ€” the norm of a complex x. norm(x) is defined as x.real**2 + x.imag**2, and abs(x) is the square root of norm(x) โœจ
  • phase(x, /) -> mpfr โ€” the phase angle (aka the argument) of a complex x ๐ŸŒ€
  • 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 complex x that's in rectangular form
  • pow(x, y, /) -> mpz | mpq | mpfr | mpc โ€” returns x ** y ๐Ÿ”ฅ
  • proj(x, /) -> mpc โ€” the projection of a complex x onto the Riemann sphere ๐ŸŒ
  • radians(x, /) -> mpfr โ€” converts angle x from 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 of x
  • rect(r, phi, /) -> mpc โ€” the rectangular coordinate form of a complex number that you gave in polar form
  • reldiff(x, y, /) -> mpfr โ€” the relative difference between x and y. The result equals abs(x-y)/x.
  • remainder(x, y, /) -> mpfr โ€” returns x - n*y where n is the integer quotient of x/y, rounded to the nearest integer, and ties rounded to even โš–๏ธ
  • remquo(x, y, /) -> tuple[mpfr, int] โ€” a tuple with remainder(x,y) and the low bits of the quotient
  • rint(x, /) -> mpfr โ€” x rounded to the nearest integer using the context rounding mode
  • rint_ceil(x, /) -> mpfr โ€” x rounded to the nearest integer, by first rounding to the next higher-or-equal integer and then, if needed, using the context rounding mode
  • rint_floor(x, /) -> mpfr โ€” x rounded to the nearest integer, by first rounding to the next lower-or-equal integer and then, if needed, using the context rounding mode
  • rint_round(x, /) -> mpfr โ€” x rounded to the nearest integer, by first rounding to the nearest integer (ties away from 0) and then, if needed, using the context rounding mode
  • rint_trunc(x, /) -> mpfr โ€” x rounded to the nearest integer, by first rounding towards zero and then, if needed, using the context rounding mode
  • root(x, n, /) -> mpfr โ€” the n-th root of x. The result is always an mpfr. ๐Ÿšจ note: not IEEE 754-2008 compliant; the result differs when x = -0 and n is even. See context.rootn().
  • root_of_unity(n, k, /) -> mpc โ€” the n-th root of mpc(1) raised to the k-th power ๐Ÿ’ซ
  • rootn(x, n, /) -> mpfr โ€” the n-th root of x. The result is always an mpfr. โœจ note: this is the IEEE 754-2008 compliant version of context.root().
  • round2(x, n=0, /) -> mpfr โ€” x rounded to n bits. Uses the default precision if n isn't specified. See context.round_away() to access the mpfr_round() function of the MPFR.
  • round_away(x, /) -> mpfr โ€” an mpfr that is x rounded to the nearest integer, with ties rounded away from 0 ๐Ÿซถ
  • sec(x, /) -> mpfr โ€” secant of x; x in radians
  • sech(x, /) -> mpfr โ€” hyperbolic secant of x
  • sin(x, /) -> mpfr | mpc โ€” sine of x; x in radians ๐ŸŒŠ
  • sin_cos(x, /) -> tuple[mpfr | mpc, mpfr | mpc] โ€” a tuple with the sine and the cosine of x; x in radians. Two for one, we love to see it ๐Ÿ’…
  • sinh(x, /) -> mpfr | mpc โ€” hyperbolic sine of x
  • sinh_cosh(x, /) -> tuple[mpfr, mpfr] โ€” a tuple with the hyperbolic sine and cosine of x
  • sqrt(x, /) -> mpfr | mpc โ€” the square root of x ๐ŸŒฑ
  • square(x, /) -> mpz | mpq | mpfr | mpc โ€” returns x * x
  • sub(x, y, /) -> mpz | mpq | mpfr | mpc โ€” returns x - y
  • tan(x, /) -> mpfr | mpc โ€” tangent of x; x in radians
  • tanh(x, /) -> mpfr | mpc โ€” hyperbolic tangent of x
  • trunc(x, /) -> mpfr โ€” an mpfr that is x truncated towards 0. Same as x.floor() if x>=0 or x.ceil() if x<0 โœ‚๏ธ
  • y0(x, /) -> mpfr โ€” second kind Bessel function of order 0 of x
  • y1(x, /) -> mpfr โ€” second kind Bessel function of order 1 of x
  • yn(n, x, /) -> mpfr โ€” the second kind Bessel function of order n of x. โš ๏ธ once again for the people in the back: the order of the arguments changed in gmpy2 2.2.0a2
  • zeta(x, /) -> mpfr โ€” Riemann zeta of x ๐ŸŒ€

๐ŸŽ€ attributes, aka the lil switches that run the whole vibe ๐ŸŽ€

  • allow_complex โ€” this attribute controls whether or not an mpc result can be returned if an mpfr result would normally not be possible ๐Ÿ’œ
  • allow_release_gil โ€” if you set it to True, lots of mpz and mpq computations 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 an mpfr result. The maximum exponent is platform dependent and can be retrieved with get_emax_max() โฌ†๏ธ
  • emin โ€” this attribute controls the minimum allowed exponent of an mpfr result. The minimum exponent is platform dependent and can be retrieved with get_emin_min() โฌ‡๏ธ
  • erange โ€” 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 an mpc result. If it's set to Default, then whatever real_prec is gets used instead. โœจ
  • imag_round โ€” controls the rounding mode for the imaginary part of an mpc result. If it's Default, then the real_round value is used. Heads up though: RoundAwayZero is not a valid rounding mode for mpc. ๐Ÿ’€
  • 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 and trap_overflow is False.
  • precision โ€” controls the precision of an mpfr result. It's measured in bits, not decimal digits, okay? The max precision you can ask for is platform dependent, and you can grab it with get_max_precision(). โš ๏ธ Also: if you set precision too close to the maximum, the MPFR library will literally fail. Don't do it.
  • rational_division โ€” set this to True and mpz / mpz hands you back an mpq instead of an mpfr. It's giving "keep it exact" energy. ๐ŸŽ€
  • real_prec โ€” controls the precision of the real part of an mpc result. If it's Default, then the precision attribute's value is used.
  • real_round โ€” controls the rounding mode for the real part of an mpc result. If it's Default, then the round attribute's value is used. Same warning as before: RoundAwayZero is not a valid rounding mode for mpc.
  • round โ€” the mpfr type 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 a DivisionByZeroError gets raised when division by 0 happens. Fun fact: DivisionByZeroError is a sub-class of Python's ZeroDivisionError.
  • trap_erange โ€” controls whether a RangeError is raised when certain operations get performed on NaN and/or Infinity values. Setting trap_erange to True is the move if you want an exception when comparisons get attempted against a NaN.
  • trap_inexact โ€” controls whether an InexactResultError gets 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 the rc attribute of the mpfr result. ๐Ÿ•ต๏ธโ€โ™€๏ธ
  • trap_invalid โ€” controls whether an InvalidOperationError gets raised when a numerical result isn't defined. If no exception is raised, you get a special NaN (Not-A-Number) value instead. InvalidOperationError is a sub-class of Python's ValueError.

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 to False, a result bigger than the largest possible mpfr given the current exponent range gets replaced by +/-Infinity. If set to True, an OverflowResultError exception is raised instead.
  • trap_underflow โ€” if set to False, a result smaller than the smallest possible mpfr given the current exponent range gets replaced by +/-0.0. If set to True, an UnderflowResultError exception gets raised.
  • underflow โ€” not user controllable. Auto-sets if a result underflowed to +/-0.0 and trap_underflow is False.

๐Ÿ’– 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:
    1. If n is a radix-2 floating point number, then the full precision of n is retained.
    2. If n is an integer, then the precision is the bit length of the integer.
__format__(fmt) -> str

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 to prec digits in whatever base you want. If prec is 0, it returns as many digits as are available, and it won't give you more digits than x's precision allows. base has to be between 2 and 62, inclusive. You get back a three-element tuple: the mantissa, the exponent, and the number of bits of precision. ๐Ÿ’…
  • is_finite() -> bool โ€” returns True if x is an actual number (so not NaN or Infinity, periodt). If x is an mpc <#gmpy2.mpc>, it returns True only if both x.real and x.imag are finite. ๐Ÿ‘‘
  • is_infinite() -> bool โ€” returns True if x is +Infinity or -Infinity. If x is an mpc <#gmpy2.mpc>, it returns True if either x.real or x.imag is infinite. Otherwise it's False.
  • is_integer() -> bool โ€” returns True if x is an integer; False otherwise. no cap.
  • is_nan() -> bool โ€” returns True if x is NaN (Not-A-Number), else False.
  • is_regular() -> bool โ€” returns True if x is not zero, NaN, or Infinity; False otherwise.
  • is_signed() -> bool โ€” returns True if the sign bit of x is set.
  • is_zero() -> bool โ€” returns True if x is equal to 0. If x is an mpc <#gmpy2.mpc>, it returns True if both x.real and x.imag are equal to 0. ๐Ÿซถ
  • imag โ€” imaginary component โœจ
  • precision โ€” precision in bits ๐ŸŽ€
  • rc โ€” return code ๐Ÿ’€
  • real โ€” real component ๐Ÿฆ‹

โœจ mpfr Functions โœจ

  • gmpy2.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 an mpfr that is the smallest integer >= x.
  • gmpy2.check_range(x, /) -> mpfr <#gmpy2.mpfr> โ€” returns a new mpfr with an exponent that lies within the current range of emin and emax.
  • gmpy2.cmp(x, y, /) -> int โ€” returns -1 if x < y; 0 if x = y; or 1 if x > y. Both x and y must be integer, rational or real. Note: 0 is returned (and 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> โ€” returns 10**x.
  • gmpy2.exp2(x, /) -> mpfr <#gmpy2.mpfr> โ€” returns 2**x.
  • gmpy2.expm1(x, /) -> mpfr <#gmpy2.mpfr> โ€” returns exp(x) - 1.
  • gmpy2.factorial(n, /) -> mpfr <#gmpy2.mpfr> โ€” returns the floating-point approximation to the factorial of n. See fac() <#gmpy2.fac> to get the exact integer result. ๐Ÿ’…
  • gmpy2.floor(x, /) -> mpfr <#gmpy2.mpfr> โ€” returns an mpfr that 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> โ€” returns x - n*y where n is the integer quotient of x/y, rounded to 0.
  • 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 returns 0 for NaN or Infinity and sets the context.erange <#gmpy2.context.erange> flag of the current context, and it will raise an exception if context.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 an mpfr initialized to Infinity with the same sign as n. If n is not given, +Infinity is returned.
  • gmpy2.is_finite(x, /) -> bool โ€” returns True if x is an actual number (i.e. non NaN or Infinity). If x is an mpc <#gmpy2.mpc>, it returns True if both x.real and x.imag are finite.
  • gmpy2.is_infinite(x, /) -> bool โ€” returns True if x is +Infinity or -Infinity. If x is an mpc <#gmpy2.mpc>, it returns True if either x.real or x.imag is infinite. Otherwise it returns False.
  • gmpy2.is_regular(x, /) -> bool โ€” returns True if x is not zero, NaN, or Infinity; False otherwise.
  • gmpy2.is_signed(x, /) -> bool โ€” returns True if the sign bit of x is set.
  • gmpy2.is_unordered(x, y, /) -> bool โ€” returns True if 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 in gmpy2 2.2.0a2.
  • gmpy2.lgamma(x, /) -> tuple[mpfr <#gmpy2.mpfr>, int] โ€” returns a tuple containing the logarithm of the absolute value of gamma(x) and the sign of gamma(x).
  • gmpy2.li2(x, /) -> mpfr <#gmpy2.mpfr> โ€” returns real part of dilogarithm of x.
  • gmpy2.lngamma(x, /) -> mpfr <#gmpy2.mpfr> โ€” returns natural logarithm of gamma(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 not mpfr, they are converted to mpfr. The result is rounded to match the current context. If only one of x or y is a number, then that number is returned.
  • gmpy2.minnum(x, y, /) -> mpfr <#gmpy2.mpfr> โ€” returns the minimum number of x and y. If x and y are not mpfr, they are converted to mpfr. The result is rounded to match the current context. If only one of x or y is a number, then that number is returned.
  • gmpy2.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 an mpfr from a GMPY 1.x binary mpf format.
  • 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 an mpfr initialized to NaN (Not-A-Number).
  • gmpy2.next_above(x, /) -> mpfr <#gmpy2.mpfr> โ€” returns the next mpfr from x toward +Infinity.
  • gmpy2.next_below(x, /) -> mpfr <#gmpy2.mpfr> โ€” returns the next mpfr from 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 to abs(x-y)/x.
  • gmpy2.remainder(x, y, /) -> mpfr <#gmpy2.mpfr> โ€” returns x - n*y where n is the integer quotient of x/y, rounded to the nearest integer and ties rounded to even.
  • gmpy2.remquo(x, y, /) -> tuple[mpfr <#gmpy2.mpfr>, int] โ€” returns a tuple containing the remainder(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 from 0) 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 the n-th root of x, and the result is always an mpfr. โœจ โš ๏ธ bestie, heads up: this is not IEEE 754-2008 compliant โ€” the result differs when x = -0 and n is even. peep rootn() if you need that. ๐Ÿ‘€
  • gmpy2.rootn(x, n, /) -> mpfr โ€” same n-th root energy, but this is the IEEE 754-2008 compliant version of root(). slay. ๐Ÿ’…
  • gmpy2.round2(x, n=0, /) -> mpfr โ€” returns x rounded to n bits. if you don't pass n, it uses the default precision. check round_away() to access the mpfr_round() function of the MPFR. ๐ŸŽ€
  • gmpy2.round_away(x, /) -> mpfr โ€” returns an mpfr that is x rounded to the nearest integer, with ties rounded away from 0. no cap. ๐Ÿซถ
  • gmpy2.sec(x, /) -> mpfr โ€” returns the secant of x; x in radians. ๐ŸŒธ
  • gmpy2.sech(x, /) -> mpfr โ€” returns the hyperbolic secant of x. ๐Ÿฆ‹
  • gmpy2.set_exp(x, n, /) -> mpfr โ€” sets the exponent of x to n. if n is outside the range of valid exponents, set_exp() will set the context.erange flag of the current context and either return the original value or raise an exception if context.trap_erange is set. โš ๏ธ
  • gmpy2.set_sign(x, s, /) -> mpfr โ€” if s is True, returns x with the sign bit set. periodt. ๐Ÿ’œ
  • gmpy2.sign(x, /) -> int โ€” returns -1 if x < 0, 0 if x == 0, or +1 if x >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 of x. ๐Ÿ“
  • gmpy2.trunc(x, /) -> mpfr โ€” returns an mpfr that is x truncated towards 0. same as x.floor() if x>=0 or x.ceil() if x<0. ๐Ÿงš
  • gmpy2.y0(x, /) -> mpfr โ€” returns the second kind Bessel function of order 0 of x. ๐ŸŒˆ
  • gmpy2.y1(x, /) -> mpfr โ€” returns the second kind Bessel function of order 1 of x. โญ
  • gmpy2.yn(n, x, /) -> mpfr โ€” returns the second kind Bessel function of order n of x. โš ๏ธ note: the order of the arguments changed in gmpy2 2.2.0a2. ๐Ÿ‘‘
  • gmpy2.zero(n, /) -> mpfr โ€” returns an mpfr initialized to 0.0 with the same sign as n. if n is not given, +0.0 is returned. ๐Ÿ’–
  • gmpy2.zeta(x, /) -> mpfr โ€” returns the Riemann zeta of x. ๐Ÿ”ฅ
  • 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 for mpfr. ๐Ÿ’…
  • gmpy2.get_emin_min() -> int โ€” returns the minimum possible exponent that can be set for mpfr. ๐ŸŽ€
  • gmpy2.copy_sign(x, y, /) -> mpfr โ€” returns an mpfr composed of x with the sign of y. ๐Ÿซถ
  • gmpy2.can_round(b, err, rnd1, rnd2, prec, /) -> bool โ€” let b be an approximation to an unknown number x that is rounded according to rnd1. assume that b has an error at most two to the power of E(b)-err where E(b) is the exponent of b. then return True if x can be rounded correctly to prec bits with rounding mode rnd2. ๐Ÿค“
  • 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'.
  • conjugate() -> mpc โ€” returns the conjugate of x. ๐Ÿ’…
  • digits(base=10, prec=0, /) -> tuple[tuple[str, int, int], tuple[str, int, int]] โ€” returns up to prec digits in the given base. if prec is 0, as many digits that are available given c's precision are returned. base must be between 2 and 62. the result consists of 2 three-element tuples that contain the mantissa, exponent, and number of bits of precision of the real and imaginary components. ๐Ÿ“
  • is_finite() -> bool โ€” return True if x is an actual number (i.e. non NaN or Infinity). if x is an mpc, return True if both x.real and x.imag are finite. ๐ŸŒˆ
  • is_infinite() -> bool โ€” return True if x is +Infinity or -Infinity. if x is an mpc, return True if either x.real or x.imag is infinite. otherwise return False. โญ
  • is_nan() -> bool โ€” return True if x is NaN (Not-A-Number) else False. ๐Ÿ’€
  • is_zero() -> bool โ€” return True if x is equal to 0. if x is an mpc, return True if both x.real and x.imag are equal to 0. ๐Ÿ™ˆ
  • imag โ€” imaginary component ๐Ÿ‘‘
  • precision โ€” precision in bits ๐ŸŽ€
  • rc โ€” return code ๐Ÿ’œ
  • real โ€” real component ๐Ÿซถ

โœจ mpc Functions โœจ

  • gmpy2.acos(x, /) -> mpfr | mpc โ€” returns inverse cosine of x; result in radians. ๐ŸŒธ
  • gmpy2.acosh(x, /) -> mpfr | mpc โ€” returns inverse hyperbolic cosine of x. ๐Ÿฆ‹
  • gmpy2.asin(x, /) -> mpfr | mpc โ€” returns inverse sine of x; result in radians. ๐Ÿ“
  • gmpy2.asinh(x, /) -> mpfr | mpc โ€” returns inverse hyperbolic sine of x. ๐Ÿงš
  • gmpy2.atan(x, /) -> mpfr | mpc โ€” returns inverse tangent of x; result in radians. ๐ŸŒˆ
  • gmpy2.atanh(x, /) -> mpfr | mpc โ€” returns inverse hyperbolic tangent of x. โญ
  • gmpy2.cos(x, /) -> mpfr | mpc โ€” returns cosine of x; x in radians. ๐Ÿ’–
  • gmpy2.cosh(x, /) -> mpfr | mpc โ€” returns hyperbolic cosine of x. ๐Ÿ”ฅ
  • gmpy2.div_2exp(x, n, /) -> mpfr | mpc โ€” returns x divided by 2**n. ๐Ÿ’…
  • gmpy2.exp(x, /) -> mpfr | mpc โ€” returns the exponential of x. ๐ŸŒŸ
  • gmpy2.is_nan(x, /) -> bool โ€” return True if x is NaN (Not-A-Number) else False. ๐Ÿ’€
  • gmpy2.is_zero(x, /) -> bool โ€” return True if x is equal to 0. if x is an mpc, return True if both x.real and x.imag are equal to 0. ๐Ÿ™ˆ
  • gmpy2.log(x, /) -> mpfr | mpc โ€” returns the natural logarithm of x. ๐ŸŽ€
  • gmpy2.log10(x, /) -> mpfr | mpc โ€” returns the base-10 logarithm of x. ๐Ÿซถ
  • 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 โ€” returns x multiplied by 2**n. โœจ
  • gmpy2.norm(x, /) -> mpfr โ€” returns the norm of a complex x. norm(x) is defined as x.real**2 + x.imag**2. abs(x) is the square root of norm(x). ๐ŸŒˆ
  • gmpy2.phase(x, /) -> mpfr โ€” returns the phase angle, also known as argument, of a complex x. โญ
  • gmpy2.polar(x, /) -> tuple[mpfr, mpfr] โ€” returns the polar coordinate form of a complex x that is in rectangular form. ๐Ÿ“
  • gmpy2.proj(x, /) -> mpc โ€” returns the projection of a complex x on 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 the n-th root of mpc(1) raised to the k-th power.. (yes, two dots, iconic) ๐Ÿ‘‘
  • gmpy2.sin(x, /) -> mpfr | mpc โ€” returns sine of x; x in radians. ๐Ÿ’œ
  • gmpy2.sin_cos(x, /) -> tuple[mpfr | mpc, mpfr | mpc] โ€” returns a tuple containing the sine and cosine of x; x in radians. ๐Ÿซถ
  • gmpy2.sinh(x, /) -> mpfr | mpc โ€” returns hyperbolic sine of x. ๐Ÿฆ‹
  • gmpy2.sqrt(x, /) -> mpfr | mpc โ€” returns the square root of x. ๐ŸŒธ
  • gmpy2.tan(x, /) -> mpfr | mpc โ€” returns tangent of x; x in radians. ๐Ÿ”ฅ
  • gmpy2.tanh(x, /) -> mpfr | mpc โ€” returns hyperbolic tangent of x. ๐Ÿงš

๐ŸŒŸ Generic Functions ๐ŸŒŸ

  • gmpy2.add(x, y, /) -> mpz | mpq | mpfr | mpc โ€” returns x + y. ๐Ÿ’–
  • gmpy2.div(x, y, /) -> mpz | mpq | mpfr | mpc โ€” returns x / y; uses true division. periodt. ๐Ÿ’…
  • gmpy2.mul(x, y, /) -> mpz | mpq | mpfr | mpc โ€” bestie it literally returns x * y. that's it, that's the function ๐Ÿ’–
  • gmpy2.sub(x, y, /) -> mpz | mpq | mpfr | mpc โ€” returns x - y. subtraction nation rise ๐Ÿซถ
  • gmpy2.square(x, /) -> mpz | mpq | mpfr | mpc โ€” returns x * x. the glow-up of multiplying by yourself โœจ
  • gmpy2.f2q(x, err=0, /) -> mpz | mpq โ€” returns the 'best' mpq that approximates x within a relative error of err. default is the precision of x. it uses a Stern-Brocot tree to hunt down that 'best' approximation (iykyk ๐Ÿงš). if the denominator turns out to be 1, you get an mpz object back instead. and if err < 0, the relative error is 2.0 ** err. not me thinking that's kinda iconic
  • gmpy2.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 -1 if abs(x) < abs(y); 0 if abs(x) = abs(y); and 1 otherwise. comparing the vibes, ignoring the signs ๐ŸŒˆ

๐ŸŒธ Miscellaneous Functions ๐ŸŒธ

  • gmpy2.digits(x, base=10, prec=0, /) -> str โ€” returns a string representing the number x. it's giving stringified ๐Ÿ‘‘
  • gmpy2.from_binary(bytes, /) -> mpz | xmpz | mpq | mpfr | mpc โ€” returns a Python object from a byte sequence that was created by to_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 object x. you can hand that byte sequence to from_binary() and get an exact copy of x's value back. raises a TypeError if x isn'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 to isinstance(obj, mpz)
  • bint MPQ_Check(object) โ€” equivalent to isinstance(obj, mpq)
  • bint MPFR_Check(object) โ€” equivalent to isinstance(obj, mpfr)
  • bint MPC_Check(object) โ€” equivalent to isinstance(obj, mpc)

๐ŸŒˆ Object creation ๐ŸŒˆ

to create a new gmpy2 type there are four basic functions:

  • mpz GMPy_MPZ_New(void * ctx) โ€” create a new mpz object from a given context ctx
  • mpq GMPy_MPQ_New(void * ctx) โ€” create a new mpq object from a given context ctx
  • mpfr MPFR_New(void * ctx, mpfr_prec_t prec) โ€” create a new mpfr object with a given context ctx and precision prec
  • mpc MPC_New(void * ctx, mpfr_prec_t rprec, mpfr_prec_t iprec) โ€” create a new mpc object with a given context ctx, and precisions rprec and iprec of 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 new mpz object with a given mpz_t value z
  • mpq GMPy_MPQ_From_mpq(mpq_srcptr q) โ€” return a new mpq object from a given mpq_t value q
  • mpq GMPy_MPQ_From_mpz(mpz_srcptr num, mpz_srcptr den) โ€” return a new mpq object with a given mpz_t numerator num and mpz_t denominator den
  • mpfr GMPy_MPFR_From_mpfr(mpfr_srcptr x) โ€” return a new mpfr object with a given mpfr_t value x
  • mpc GMPy_MPC_From_mpc(mpc_srcptr c) โ€” return a new mpc object with a given mpc_t value c
  • mpc GMPy_MPC_From_mpfr(mpfr_srcptr re, mpfr_srcptr im) โ€” return a new mpc object with a given mpfr_t real part re and mpfr_t imaginary part im

๐Ÿ‘‘ Access to the underlying C type ๐Ÿ‘‘

each of the gmpy2 objects has a field corresponding to the underlying C type. the following functions give 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 type mpz.
  • __mpq__ : return an object of type mpq.
  • __mpfr__ : return an object of type mpfr.
  • __mpc__ : return an object of type mpc.

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 char when int should 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 contextvars to manage gmpy2 contexts. (casevh)
  • _mpmath functions now use the vectorcall protocol. (casevh)
  • many documentation updates. (skirpichev)
  • add mpz.as_integer_ratio() / mpz.to_bytes() and mpz.from_bytes(). (skirpichev)
  • add is_probab_prime() to directly expose the GMP behavior. (skirpichev)
  • gcd() / lcm() now uses the vectorcall protocol. (skirpichev)
  • expose context type. (skirpichev)
  • correct error in is_strong_bpsw_prp(). (casevh)
  • added prev_prime() when GMP >= 6.3. (sethtroisi)
  • change argument order of jn() and yn() to match MPFR. (casevh)
  • fix documentation and code for is_extra_strong_lucas_prp(). (casevh)

๐ŸŒŸ 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') and mpfr('nan') if subnormalization is enabled.
  • powmod() and powmod_sec() release the GIL.
  • fix error messages for iroot(x,n) for large n.
  • add powmod_base_list() and powmod_exp_list() (experimental).
  • fix gmpy2.mpq(mpq, int).
  • fix issues with INF, NAN, and mpfr("-0") when subnormalization is True

๐ŸŒŸ Changes in gmpy2 2.1.2 ๐ŸŒŸ

  • code cleanup.
  • support Apple Silicon binary wheels.
  • is_prime(-2) now returns False. Issue #312.

๐ŸŒŸ Changes in gmpy2 2.1.1 ๐ŸŒŸ

  • code cleanup.
  • properly return NOTIMPLEMENTED for unsupported arguments in **. Issue #319.

๐ŸŒŸ Changes in gmpy2 2.1.0 ๐ŸŒŸ

  • improvements to setup.py.
  • add thread-safe contexts.
  • MPFR and MPC are now required.
  • Invalid Operation exception now raised for addition, etc.
  • inverse() now raises 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 calls int(x) if mpz() doesn't know how to convert x directly.
  • mpz got 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_000 core ๐ŸŒธ
  • GIL release now allowed for mpz/xmpz/mpq types 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 mpfr and mpc types. (Not complete, but the common operations are done.) ๐Ÿƒโ€โ™€๏ธ๐Ÿ’จ
  • Resolved a bug in mpfr โ†’ mpq conversion; 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 mpz and xmpz types; in-place operations on xmpz will only return an xmpz result. no switching up on us ๐Ÿ’€
  • Refactored conversion to C integer types. Some exception types changed to reflect Python types.
  • gcd() and lcm() 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 where long is 32-bits and the argument is >= 44787929. ๐Ÿšง
  • Fixed testing bugs with Python 2.7.
  • Fixed mpz(0) to C long or long 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 mpq and 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() and cmp_abs().
  • Improved compatibility with the numbers module protocol. ๐Ÿค
  • Many bug fixes.

โœจ Changes in gmpy2 2.1.a05

  • Fixed qdiv() not returning mpz when 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() and fmms().

โœจ 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 as root() except different sign when taking an even root of -0.0.

โœจ 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 involving mpz instances, 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 numbers module.
  • In previous versions of gmpy2, mpz() was a factory function that returned an mpz instance. 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 by mpz() 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.py to allow static linking.
  • Fixed a performance regression with mpmath and Python 3. ๐ŸŽ๏ธ

โœจ Changes in gmpy2 2.0.3

  • Fixed lucas2() and atanh(); 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.py to work in more situations.
  • Corrected exception handling in basic operations with the mpfr type.
  • Fixed InvalidOperation exception 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() and is_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 mpz to float now raises OverflowError instead of returning inf. (casevh)
  • Renamed min2()/max2() to minnum()/maxnum(). (casevh)
  • The build and install process (i.e. setup.py) has been completely rewritten. See the Installation section for more information. (casevh) ๐Ÿ› ๏ธ
  • get_context() no longer accepts keyword arguments. (casevh) ๐Ÿšซ

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 the mpz and mpq types. (casevh) ๐ŸŽ€
  • Added __complex__() to the mpc type. (casevh)
  • round(mpfr) now correctly returns an mpz type. (casevh)
  • Added mpz.denominator and mpz.numerator. (casevh)
  • If no arguments are given to mpz, mpq, mpfr, mpc, and xmpz, they return 0 of the appropriate type. (casevh) zero but make it โœจtypedโœจ
  • Fixed broken comparison between mpz and mpq when mpz is on the left. (casevh)
  • Added __sizeof__() to all types. Note: sys.getsizeof() calls __sizeof__() to get the memory size of a gmpy2 object. The returned value reflects the size of the allocated memory, which may be larger than the actual minimum memory required by the object. (casevh)

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(), and mpfr_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 Fraction type to mpq. (casevh) ๐Ÿƒโ€โ™€๏ธ
  • Improved conversion of the Decimal type to mpfr. (casevh)
  • Consistently return OverflowError when converting inf. (casevh)
  • Fixed mpz.__format__() when the format code includes "#". (casevh)
  • Added is_infinite() and deprecated is_inf(). (casevh)
  • Added is_finite() and deprecated is_number(). (casevh)
  • Fixed the various is_XXX() tests when used with mpc. (casevh)
  • Fixed error handling with mpc(); mpc(1,"nan") is properly handled. (casevh)
  • Added caching for mpc objects. (casevh) ๐Ÿ’พ
  • Faster code path for basic operations when both operands are mpfr or mpc. (casevh)
  • Fixed an mpfr + float segmentation fault. (casevh) ๐Ÿ’€

โœจ Changes in gmpy2 2.0.0b2

  • xmpz slice assignment can now increase the length of an xmpz instance by specifying a value for stop. (casevh)
  • Fixed a reference counting bug in several is_xxx_prp() tests. (casevh)
  • Added iter_bits(), iter_clear(), and iter_set() methods to xmpz. (casevh) ๐Ÿฆ‹
  • Added powmod() for easy access to three argument pow(). (casevh)
  • Removed addmul() and submul(), which were added in 2.0.0b1, since they're slower than just using Python code. (casevh) bye girlies โœŒ๏ธ
  • Bug fix in gcd_ext when both arguments are not mpz. (casevh)
  • Added ieee() to create contexts for 32, 64, or 128 bit floats. (casevh) ๐ŸŒˆ
  • Bug fix in context() not setting emax/emin correctly if they had been changed earlier. (casevh)
  • Contexts can now be used directly in a with statement without needing the set_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 with bit_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 (mutable mpz) type. (casevh)
  • โœจ Fix mpq formatting issue. (casevh)
  • โœจ Add read/write bit access using slices to xmpz. (casevh)
  • โœจ Add read-only bit access using slices to mpz. (casevh)
  • โœจ Add pack()/unpack() methods to split/join an integer into n-bit chunks. (casevh)
  • โœจ Add support for MPFR (casevh)
  • โœจ Removed fcoform float conversion modifier. (casevh)
  • โœจ Add support for MPC. (casevh)
  • โœจ Added context manager. (casevh)
  • โœจ Allow building with just GMP/MPIR if MPFR not available. (casevh)
  • โœจ Allow building with GMP/MPIR and MPFR if MPC not available. (casevh)
  • โœจ Removed most instance methods in favor of gmpy2.function. The general guideline is that properties of an instance can be done via instance methods but functions that return a new result are done using gmpy2.function. (casevh)
  • โœจ Added __ceil__(), __floor__(), and __trunc__() methods since they are called by math.ceil(), math.floor(), and math.trunc(). (casevh)
  • โœจ Removed gmpy2.pow() to avoid conflicts. (casevh)
  • โœจ Removed gmpy2._copy() and added xmpz.copy(). (casevh)
  • โœจ Added support for __format__(). (casevh)
  • โœจ Added as_integer_ratio(), as_mantissa_exp(), as_simple_fraction(). (casevh)
  • โœจ Updated rich_compare. (casevh)
  • โœจ Require MPFR 3.1.0+ to get divby0 support. (casevh)
  • โœจ Added fsum(), degrees(), radians(). (casevh)
  • โœจ Updated random number generation support. (casevh)
  • โœจ Changed license to LGPL 3+. (casevh)
  • โœจ Added lucasu(), lucasu_mod(), lucasv(), and lucasv_mod(). (casevh) Based on code contributed by David Cleaver.
  • โœจ Added probable-prime tests. (casevh) Based on code contributed by David Cleaver.
  • โœจ Added to_binary()/from_binary(). (casevh)
  • โœจ Renamed numdigits() to num_digits(). (casevh)
  • โœจ Added keyword precision to constants. (casevh)
  • โœจ Added addmul() and submul(). (casevh)
  • โœจ Added __round__(), round2(), round_away() for mpfr. (casevh)
  • โœจ round() is no longer a module level function. (casevh)
  • โœจ Renamed module functions min()/max() to min2()/max2(). (casevh) No longer conflicts with builtin min() and max()
  • โœจ Removed set_debug() and related functionality. (casevh)
  • โœจ Removed mpf.setprec(), use mpf.round() (casevh)
  • โœจ Fix test compatibility with Python 3.1.2 and 3.2 (casevh)
  • โœจ Remove old random number functions, to be replaced later (casevh)
  • โœจ Remove tagoff option (casevh)
  • โœจ Debug messages only available if compiled with -DDEBUG (casevh)
  • โœจ Renamed context() -> local_context(), new_context() -> context() (casevh)
  • โœจ Added get_context() (casevh)

๐ŸŒˆ Changes in gmpy 1.11 ๐ŸŒˆ

  • ๐Ÿซถ Recognize True/False (bug in 1.10) (casevh)
  • ๐Ÿซถ Optimize argument handling (casevh)
  • ๐Ÿซถ Added caching for mpz (casevh)

๐ŸŒˆ Changes in gmpy 1.10 ๐ŸŒˆ

  • ๐Ÿซถ Remove dependancy on pymemcompat.h (casevh)
  • ๐Ÿซถ Remove callback (casevh)
  • ๐Ÿซถ Added support for -DMPIR to include MPIR instead of GMP (casevh)
  • ๐Ÿซถ Major code revisions to add support for Python 3.x (casevh)
  • ๐Ÿซถ Fixed bug in binary() and qbinary() (casevh)
  • ๐Ÿซถ Fixed bug in rich comparisons (casevh)
  • ๐Ÿซถ Added % and divmod support to mpq and mpf (casevh)
  • ๐Ÿซถ Changed memory allocation functions to use PyMem (casevh)
  • ๐Ÿซถ Removed small number interning (casevh)
  • ๐Ÿซถ Added tdivmod, cdivmod, and fdivmod (casevh)
  • ๐Ÿซถ Added more helper functions for mpmath (casevh)
  • ๐Ÿซถ Faster mpz<>PyLong conversion (casevh)
  • ๐Ÿซถ Faster hash(mpz) (casevh)

๐Ÿ’œ Changes in gmpy 1.04 ๐Ÿ’œ

  • ๐Ÿ’… Avoid GMP/mingw32 bug when converting very small floats to mpz. (casevh)
  • ๐Ÿ’… Significant performance improvement for long->mpz and mpz->long. (casevh)
  • ๐Ÿ’… Added "rich comparisons" to mpz, mpq and mpf types (aleaxit)
  • ๐Ÿ’… Added additional tests (casevh, aleaxit)
  • ๐Ÿ’… Fixed bug when converting very large mpz to str (casevh)
  • ๐Ÿ’… Faster conversion from mpz->binary and binary->mpz (casevh)
  • ๐Ÿ’… Added support for pickling (casevh)
  • ๐Ÿ’… Added divexact (casevh)
  • ๐Ÿ’… Fixed mpf comparisons by rounding mpf results when GMP returns a longer result. Added fround() (casevh)
  • ๐Ÿ’… Added bit_length (Thanks Mario Pernici)
  • ๐Ÿ’… Added helper functions for mpmath (casevh)
  • ๐Ÿ’… Faster conversion from mpq->binary and binary->mpq (casevh)
  • ๐Ÿ’… Recognize MPIR, mpir_version() (casevh)

๐Ÿ’œ Changes in gmpy 1.03 ๐Ÿ’œ

  • ๐ŸŽ€ Fixed the bug that caused crashes on gmpy.mpf(float('inf')) and other such conversions, implicit and explicit
  • ๐ŸŽ€ Fixed a bug in get_zconst's prototype affecting 64-bit machines, thanks to Gary Bunting
  • ๐ŸŽ€ Fixed a bug in hashing on 64-bit systems. hash(long) now equals hash(mpz) for large values. (casevh)
  • ๐ŸŽ€ Changed int() to return a long value instead of OverFlowError. Complies with PEP 237. (casevh)
  • ๐ŸŽ€ Added support in setup.py for darwinports/macports build of GMP on MacOSX. (aleaxit)

๐Ÿ’œ Changes in gmpy 1.02 ๐Ÿ’œ

  • ๐Ÿฆ‹ fix warning in comparison of mpq's
  • ๐Ÿฆ‹ added support of mpq('12.34') [[string w/o a slash, but with a dot]]
  • ๐Ÿฆ‹ fixes for 64-bit build (thanks to a patch by dmcooke)
  • ๐Ÿฆ‹ added experimental support for decimal.Decimal (and user-coded types) via wider use of special conversion methods (if present) and their sly insertion on-the-fly into the decimal.Decimal class (!)
  • ๐Ÿฆ‹ two bugfixes, thanks to Simon Burton
  • ๐Ÿฆ‹ Brought back into C89 compliance (thanks to Chip Turner), had drifted to C99 (declarations in the middle of the code).
  • ๐Ÿฆ‹ Python 2.5 support (Py_ssize_t, __index__) thanks to Chip Turner
  • ๐Ÿฆ‹ Pushed coverage to 93.3% (missing only "sanity check" level error tests [mostly for out-of-memory conditions], output to stderr conditioned by global.debug, & a couple of very obscure cases)

๐Ÿฆ‹ Changes in gmpy 1.01 ๐Ÿฆ‹

  • ๐ŸŒธ cleanups, ensure support for Python 2.4.1 on MacOSX 10.4/XCode 2.1 as well as Python 2.2 and 2.3 (on MacOSX and Linux)
  • ๐ŸŒธ fixed memory leak on divm (thanks to <mensanator@aol.com>)
  • ๐ŸŒธ fixed bug on mpq('123') [[str2mpq on string w/o a slash]]
  • ๐ŸŒธ added floordiv and truediv operators, and tests for them
  • ๐ŸŒธ NOT tested on GMP 3 (have none left around...), ONLY on GMP 4.*

๐ŸŒธ Changes in gmpy 1.0 ๐ŸŒธ

  • โญ minor cleanups, ensure support for Python 2.3
  • โญ fixed misdiagnosis of some argument counts in macro
  • โญ SELF_ONE_ARG_CONVERTED (tx to Paul Rubin!)

๐ŸŒธ Changes in gmpy 0.9 ๐ŸŒธ

  • โญ change ValueError to OverflowError for 'too-large' errors
  • โญ fix bug in mpq_pow (negative base, exp. with odd denominator) (fix now corrected -- _even_ denominator is the error!)
  • โญ fixed gcc warnings reported by K. Briggs
  • โญ support GMP 4 (but added no GMP4-only functionality yet)
  • โญ updated tests to 0.9, better coverage

โญ Changes in gmpy 0.8 โญ

(again, requests & suggestions by great Pearu!)

  • ๐Ÿ“ raise test coverage 72.5% -> 90.0%
  • ๐Ÿ“ introduced callbacks (not documented/tested for now; Pearu will test/support/document in PySymbolic)
  • ๐Ÿ“ some errors went undiagnosed, caused crash: now fixed
  • ๐Ÿ“ workaround for GMP bug(?s?) in mpz_fits_... (?)
  • ๐Ÿ“ added exposure of mpf_ sqrt and pow_ui

โญ Changes in gmpy 0.7 โญ

Good feedback from Keith Briggs, some advice from Tim Peters and Fred Lundh --- thanks all!

  • ๐Ÿงš fixed bug of '"%d" where "%ld" was meant' in many places and other sundry minor warnings given by gcc
  • ๐Ÿงš fixed hash (delegating to Python) so mp[nqz](x) will produce the same value as hash(x) for any Python number x
  • ๐Ÿงš workaround for GMP 3.1.1 bug, mpz_root wrongly returning 'exact' for non-exact root if dest==source, which stopped needed value-error for inexact mpq**mpq operations
  • ๐Ÿงš determined correct 'actual precision' of floats
  • ๐Ÿงš explicitly stored precision with binary-form mpf's
  • ๐Ÿงš extended explicit-bits request to all ->mpf operations (good in itself, plus, preparing for future MPFR)
  • ๐Ÿงš removed the limitation of no binary-form for <0 mpz
  • ๐Ÿงš introduced macros to parse args, for conciseness

๐Ÿงš Changes in gmpy 0.6 ๐Ÿงš

(lots of good ideas from Pearu once more!-)

  • ๐Ÿ‘‘ fixed silly bugs in kronecker and mpq_abs
  • ๐Ÿ‘‘ gmpy-level workaround for scan0/scan1 bugs (?) in gmp 3.1.1
  • ๐Ÿ‘‘ added qdiv; anynum->mpq substituted for all such conversions (also anynum->mpz and anynum->mpf by analogy, with care!)
  • ๐Ÿ‘‘ added global.fcoform for optional use of intermediate string in float2mpf (used for any float->mpf conversion)
  • ๐Ÿ‘‘ added set_fcoform function for global.fcoform access
  • ๐Ÿ‘‘ general cleanup of sources; added alloca for msvc++; - many sundry minor bugfixes & uniformization; - a little useful refactoring (more would be good...)
  • ๐Ÿ‘‘ added caching of mpq objects
  • ๐Ÿ‘‘ power for mpq
  • ๐Ÿ‘‘ stern-brocot algorithm for mpf->mpq (also exposed as f2q) - also used for float->mpq - with stricter tracking of mpf's requested-precision - added getrprec method to mpf, getrprec module-function
  • ๐Ÿ‘‘ exposed ceil, floor and trunc methods/functions for mpf's
  • ๐Ÿ‘‘ changed a couple exceptions from value to zerodivision
  • ๐Ÿ‘‘ added 'qual' and 'floa' options to gmpy.rand

๐Ÿ‘‘ Changes in gmpy 0.5 ๐Ÿ‘‘

  • ๐Ÿ’– added jacobi, legendre, kronecker
  • ๐Ÿ’– added random-number generation, seed set/save, shuffling
  • ๐Ÿ’– added mpq (at last!-)

๐Ÿ’– Changes in gmpy 0.4 ๐Ÿ’–

  • ๐ŸŒˆ split gmpy.c/gmpy.h introducing C-API interface (Pearu's suggestion)
  • ๐ŸŒˆ cleanup some casts using Pearu's new macros
  • ๐ŸŒˆ further cache-tweaks at Pearu's suggestion (macros introduced)
  • ๐ŸŒˆ added sign (Pearu's request), getbit, setbit
  • ๐ŸŒˆ added docstrings
  • ๐ŸŒˆ renamed copy functions to start with _ ('internal, private')
  • ๐ŸŒˆ added .comb as a synonym of .bincoef

๐ŸŒˆ Changes in gmpy 0.3 ๐ŸŒˆ

  • ๐Ÿฆ‹ performance tweaks via mpz-caching & fixed-constants
  • ๐Ÿฆ‹ added get/set functions for zcache, zco min/max
  • ๐Ÿฆ‹ added get-only function for versions (of gmp, and of gmpy)
  • ๐Ÿฆ‹ removed all 'traces' of mutability (to be re-done... much later!)
  • ๐Ÿฆ‹ cleaned up all of the mpz_cmp_ui(X,0) to mpz_sgn(X)
  • ๐Ÿฆ‹ cleaned up Py_BuildValue usage (N vs O, explicit-() for tuples)
  • ๐Ÿฆ‹ added numdigits, lowbits, root, next_prime, invert, popcount,
  • ๐Ÿฆ‹ hamdist, scan0, scan1
  • ๐Ÿฆ‹ renamed bin to bincoef

๐Ÿฆ‹ Changes in gmpy 0.2 ๐Ÿฆ‹

15 Nov 2000

  • ๐ŸŽ€ pre-alpha: bugfixes re formatting (tx, Peanu!)
  • ๐ŸŽ€ no tags on oct() and hex() of mpz's
  • ๐ŸŽ€ insert 'tagoff' in options (gmpy.mpz() vs mpz() in repr) (for Peanu!)
  • speedups for _nonzero & _cmp โ€” 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


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