Provided by: python-gmpy2-common_2.0.7-2build1_all

**NAME**

gmpy2 - gmpy2 Documentation Contents:

**INTRODUCTION** **TO** **GMPY2**

gmpy2 is a C-coded Python extension module that supports multiple-precision arithmetic. gmpy2 is the successor to the original gmpy module. The gmpy module only supported the GMP multiple-precision library. gmpy2 adds support for the MPFR (correctly rounded real floating-point arithmetic) and MPC (correctly rounded complex floating-point arithmetic) libraries. gmpy2 also updates the API and naming conventions to be more consistent and support the additional functionality. The following libraries are supported: · GMP for integer and rational arithmetic Home page:http://gmplib.org· MPIR is based on the GMP library but adds support for Microsoft's Visual Studio compiler. It is used to create the Windows binaries. Home page:http://www.mpir.org· MPFR for correctly rounded real floating-point arithmetic Home page:http://www.mpfr.org· MPC for correctly rounded complex floating-point arithmetic Home page:http://mpc.multiprecision.org· Generalized Lucas sequences and primality tests are based on the following code: mpz_lucas:http://sourceforge.net/projects/mpzlucas/mpz_prp:http://sourceforge.net/projects/mpzprp/Changesingmpy22.0.4· Fixed bit_scan0() for negative values. · Added option to setup.py (--static) to support static linking. · Manpage is now installed in section 3.Changesingmpy22.0.3· Fixed bugs in lucas2() and atanh() that caused incorrect results.Changesingmpy22.0.2· Rebuild the Windows binary installers due to a bug in MPIR. · Correct test in is_extra_strong_lucas_prp(). Note: The incorrect test is not known to cause any errors.Changesingmpy22.0.1· Updated setup.py to work in more situations. · Corrected exception handling in basic operations with mpfr type. · Correct InvalidOperation exception not raised in certain circumstances. · invert() now raises an exception if the modular inverse does not exist. · Fixed internal exception in is_bpsw_prp() and is_strong_bpsw_prp(). · Updated is_extra_strong_lucas_prp() to latest version.Changesingmpy22.0.0· Fix segmentation fault in _mpmath_normalize (an undocumented helper function specifically for mpmath.) · Improved setup.py See below for documentation on the changes. · Fix issues when compiled without support for MPFR. · Conversion of too large an mpz to float now raises OverflowError instead of returninginf. · Renamed min2()/max2() to minnum()/maxnum() · The build and install process (i.e. setup.py) has been completely rewritten. See the Installation section for more information. · get_context() no longer accepts keyword arguments.Knownissuesingmpy22.0.0· The test suite is still incomplete.Changesingmpy22.0.0b4· Added __ceil__, __floor__, __trunc__, and __round__ methods to mpz and mpq types. · Added __complex__ to mpc type. · round(mpfr) now correctly returns an mpz type. · If no arguments are given to mpz, mpq, mpfr, mpc, and xmpz, return 0 of the appropriate type. · Fix broken comparison between mpz and mpq when mpz is on the left. · Added __sizeof__ to all types.Note:sys.getsizeof()calls__sizeof__togetthememorysizeofagmpy2object.Thereturnedvaluereflectsthesizeoftheallocatedmemorywhichmaybelargerthantheactualminimummemoryrequiredbytheobject.Knownissuesingmpy22.0.0b4· The new test suite (test/runtest.py) is incomplete and some tests fail on Python 2.x due to formating issues.Changesingmpy22.0.0b3· mp_version(), mpc_version(), and mpfr_version() now return normal strings on Python 2.x instead of Unicode strings. · Faster conversion of the standard library Fraction type to mpq. · Improved conversion of the Decimal type to mpfr. · Consistently return OverflowError when converting "inf". · Fix mpz.__format__() when the format code includes "#". · Add is_infinite() and deprecate is_inf(). · Add is_finite() and deprecate is_number(). · Fixed the various is_XXX() tests when used with mpc. · Added caching for mpc objects. · Faster code path for basic operation is both operands are mpfr or mpc. · Fix mpfr + float segmentation fault.Changesingmpy22.0.0b2· Allow xmpz slice assignment to increase length of xmpz instance by specifying a value for stop. · Fixed reference counting bug in several is_xxx_prp() tests. · Added iter_bits(), iter_clear(), iter_set() methods to xmpz. · Added powmod() for easy access to three argument pow(). · Removed addmul() and submul() which were added in 2.0.0b1 since they are slower than just using Python code. · Bug fix in gcd_ext when both arguments are not mpz. · Added ieee() to create contexts for 32, 64, or 128 bit floats. · Bug fix in context() not setting emax/emin correctly if they had been changed earlier. · Contexts can be directly used in with statement without requiring set_context()/local_context() sequence. · local_context() now accepts an optional context.Changesingmpy22.0.0b1andearlier· Renamed functions that manipulate individual bits to bit_XXX() to align with bit_length(). · Added caching for mpq. · Added rootrem(), fib2(), lucas(), lucas2(). · Support changed hash function in Python 3.2. · Added is_even(), is_odd(). · Add caching of the calculated hash value. · Add xmpz (mutable mpz) type. · Fix mpq formatting issue. · Add read/write bit access using slices to xmpz. · Add read-only bit access using slices to mpz. · Add pack()/unpack() methods to split/join an integer into n-bit chunks. · Add support for MPFR (casevh) · Removed fcoform float conversion modifier. · Add support for MPC. · Added context manager. · Allow building with just GMP/MPIR if MPFR not available. · Allow building with GMP/MPIR and MPFR if MPC not available. · Removed most instance methods in favor of gmpy2.function. The general guideline is thatpropertiesof an instance can be done via instance methods butfunctionsthat return a new result are done using gmpy2.function. · Added __ceil__, __floor__, and __trunc__ methods since they are called by math.ceil(), math.floor(), and math.trunc(). · Removed gmpy2.pow() to avoid conflicts. · Removed gmpy2._copy and added xmpz.copy. · Added support for __format__. · Added as_integer_ratio, as_mantissa_exp, as_simple_fraction. · Updated rich_compare. · Require MPFR 3.1.0+ to get divby0 support. · Added fsum(), degrees(), radians(). · Updated random number generation support. · Changed license to LGPL 3+. · Added lucasu, lucasu_mod, lucasv, and lucasv_mod.BasedoncodecontributedbyDavidCleaver.· Added probable-prime tests.BasedoncodecontributedbyDavidCleaver.· Added to_binary()/from_binary. · Renamed numdigits() to num_digits(). · Added keyword precision to constants. · Added addmul() and submul(). · Added __round__(), round2(), round_away() for mpfr. · round() is no longer a module level function. · Renamed module functions min()/max() to min2()/max2(). · No longer conflicts with builtin min() and max() · Removed set_debug() and related functionality.

**INSTALLATION**

Installinggmpy2onWindowsPre-compiled versions of gmpy2 are available atPyPi. Please select the installer that corresponds to the version of Python installed on your computer. Note that either a 32 or 64-bit version of Python can be installed on a 64-bit version of Windows. If you get an error message stating that Python could not be found in the registry, you have the wrong version of the gmpy2 installer.Installinggmpy2onUnix/LinuxRequirementsgmpy2 has only been tested with recent versions of GMP, MPFR and MPC. Specifically, for integer and rational support, gmpy2 requires GMP 5.1.x or later. To support multiple-precision floating point arithmetic, MPFR 3.1.x or later is required. MPC 1.0.1 or later is required for complex arithmetic.ShortInstructionsYou will need to install the development libraries for Python, GMP, MPFR, and MPC. Different Linux distributions may the development packages differently. Typical names are libpython-dev, libgmp-dev, libmpfr-dev, and libmpc-dev. If your system includes recent versions of GMP, MPFR and MPC, and you have the development libraries installed, compiling should be as simple as: cd <gmpy2 source directory> python setup.py build sudo python setup.py install If this fails, read on.DetailedInstructionsIf your Linux distribution does not support recent versions of GMP, MPFR and MPC, you will need to compile your own versions. To avoid any possible conflict with existing libraries on your system, it is recommended to use a directory not normally used by your distribution. setup.py will automatically search the following directories for the required libraries: 1. /opt/local 2. /opt 3. /usr/local 4. /usr 5. /sw If you can't use one of these directories, you can use a directory located in your home directory. The examples will use /home/<username>/local. If you use one of standard directories (say /opt/local), then you won't need to specify --prefix=/home/case/local to setup.py but you will need to specify the prefix when compiling GMP, MPFR, and MPC. Please substitute your actual user name for <username>. Create the desired destination directory for GMP, MPFR, and MPC. $ mkdir /home/<username>/local Download and un-tar the GMP source code. Change to the GMP source directory and compile GMP. $ cd /home/<username>/local/src/gmp-6.0.0 $ ./configure --prefix=/home/<username>/local $ make $ make check $ make install Download and un-tar the MPFR source code. Change to the MPFR source directory and compile MPFR. $ cd /home/<username>/local/src/mpfr-3.1.2 $ ./configure --prefix=/home/<username>/local --with-gmp=/home/<username>/local $ make $ make check $ make install Download and un-tar the MPC source code. Change to the MPC source directory and compile MPC. $ cd /home/<username>/local/src/mpc-1.0.2 $ ./configure --prefix=/home/<username>/local --with-gmp=/home/<username>/local --with-mpfr=/home/<username>/local $ make $ make check $ make install Compile gmpy2 and specify the location of GMP, MPFR and MPC. The location of the GMP, MPFR, and MPC libraries is embedded into the gmpy2 library so the new versions of GMP, MPFR, and MPC do not need to be installed the system library directories. The prefix directory is added to the beginning of the directories that are checked so it will be found first. $ python setup.py install --prefix=/home/<username>/local If you get a "permission denied" error message, you may need to use: $ python setup.py build --prefix=/home/<username>/local $ sudo python setup.py install --prefix=/home/<username>/localOptionsforsetup.py--forceIgnore the timestamps on all files and recompile. Normally, the results of a previous compile are cached. To force gmpy2 to recognize external changes (updated version of GMP, etc.), you will need to use this option.--mpirForce the use of MPIR instead of GMP. GMP is the default library on non-Windows operating systems.--gmpForce the use of GMP instead of MPIR. MPIR is the default library on Windows operating systems.--prefix=<...>Specify the directory prefix where GMP/MPIR, MPFR, and MPC are located. For example,--prefix=/opt/localinstructs setup.py to search /opt/local/include for header files and /opt/local/lib for libraries.--nompfrDisables support for MPFR and MPC. This option is intended for testing purposes and is not offically supported. MPFR will be required for future versions of gmpy2.--nompcDisables support for MPC. This option is intended for testing purposes and is not officially supported. MPC will be required for future versions of gmpy2.--staticBuilds a statically linked library. This option will likely require the use of --prefix=<...> to specify the directory where the static libraries are located. To successfully link with gmpy2, the GMP, MPFR, and MPC libraries must be compiled with the --with-pic option.

**OVERVIEW** **OF** **GMPY2**

TutorialThempztype is compatible with Python's built-in int/long type but is significanly faster for large values. The cutover point for performance varies, but can be as low as 20 to 40 digits. A variety of additional integer functions are provided. >>> import gmpy2 >>> from gmpy2 import mpz,mpq,mpfr,mpc >>> mpz(99) * 43 mpz(4257) >>> pow(mpz(99), 37, 59) mpz(18) >>> gmpy2.isqrt(99) mpz(9) >>> gmpy2.isqrt_rem(99) (mpz(9), mpz(18)) >>> gmpy2.gcd(123,27) mpz(3) >>> gmpy2.lcm(123,27) mpz(1107) Thempqtype is compatible with thefractions.Fractiontype included with Python. >>> mpq(3,7)/7 mpq(3,49) >>> mpq(45,3) * mpq(11,8) mpq(165,8) The most significant new features in gmpy2 are support for correctly rounded arbitrary precision real and complex arithmetic based on the MPFR and MPC libraries. Floating point contexts are used to control exceptional conditions. For example, division by zero can either return an Infinity or raise an exception. >>> mpfr(1)/7 mpfr('0.14285714285714285') >>> gmpy2.get_context().precision=200 >>> mpfr(1)/7 mpfr('0.1428571428571428571428571428571428571428571428571428571428571',200) >>> gmpy2.get_context() context(precision=200, real_prec=Default, imag_prec=Default, round=RoundToNearest, real_round=Default, imag_round=Default, emax=1073741823, emin=-1073741823, subnormalize=False, trap_underflow=False, underflow=False, trap_overflow=False, overflow=False, trap_inexact=False, inexact=True, trap_invalid=False, invalid=False, trap_erange=False, erange=False, trap_divzero=False, divzero=False, trap_expbound=False, allow_complex=False) >>> mpfr(1)/0 mpfr('inf') >>> gmpy2.get_context().trap_divzero=True >>> mpfr(1)/0 Traceback (most recent call last): File "<stdin>", line 1, in <module> gmpy2.DivisionByZeroError: 'mpfr' division by zero in division >>> gmpy2.get_context() context(precision=200, real_prec=Default, imag_prec=Default, round=RoundToNearest, real_round=Default, imag_round=Default, emax=1073741823, emin=-1073741823, subnormalize=False, trap_underflow=False, underflow=False, trap_overflow=False, overflow=False, trap_inexact=False, inexact=True, trap_invalid=False, invalid=False, trap_erange=False, erange=False, trap_divzero=True, divzero=True, trap_expbound=False, allow_complex=False) >>> gmpy2.sqrt(mpfr(-2)) mpfr('nan') >>> gmpy2.get_context().allow_complex=True >>> gmpy2.get_context().precision=53 >>> gmpy2.sqrt(mpfr(-2)) mpc('0.0+1.4142135623730951j') >>> >>> gmpy2.set_context(gmpy2.context()) >>> with gmpy2.local_context() as ctx: ... print(gmpy2.const_pi()) ... ctx.precision+=20 ... print(gmpy2.const_pi()) ... ctx.precision+=20 ... print(gmpy2.const_pi()) ... 3.1415926535897931 3.1415926535897932384628 3.1415926535897932384626433831 >>> print(gmpy2.const_pi()) 3.1415926535897931 >>>Miscellaneousgmpy2Functionsfrom_binary(...)from_binary(bytes) returns a gmpy2 object from a byte sequence created by to_binary().get_cache(...)get_cache() returns the current cache size (number of objects) and the maximum size per object (number of limbs). gmpy2 maintains an internal list of freedmpz,xmpz,mpq,mpfr, andmpcobjects for reuse. The cache significantly improves performance but also increases the memory footprint.license(...)license() returns the gmpy2 license information.mp_limbsize(...)mp_limbsize() returns the number of bits per limb used by the GMP or MPIR libarary.mp_version(...)mp_version() returns the version of the GMP or MPIR library.mpc_version(...)mpc_version() returns the version of the MPC library.mpfr_version(...)mpfr_version() returns the version of the MPFR library.random_state(...)random_state([seed]) returns a new object containing state information for the random number generator. An optional integer argument can be specified as the seed value. Only the Mersenne Twister random number generator is supported.set_cache(...)set_cache(number, size) updates the maximum number of freed objects of each type that are cached and the maximum size (in limbs) of each object. The maximum number of objects of each type that can be cached is 1000. The maximum size of an object is 16384. The maximum size of an object is approximately 64K on 32-bit systems and 128K on 64-bit systems.NOTE:The caching options are global to gmpy2. Changes are not thread-safe. A change in one thread will impact all threads.to_binary(...)to_binary(x) returns a byte sequence from a gmpy2 object. All object types are supported.version(...)version() returns the version of gmpy2.

**MULTIPLE-PRECISION** **INTEGERS**

The gmpy2mpztype supports arbitrary precision integers. It should be a drop-in replacement for Python'slongtype. Depending on the platform and the specific operation, anmpzwill be faster than Python'slongonce the precision exceeds 20 to 50 digits. All the special integer functions in GMP are supported.Examples>>> import gmpy2 >>> from gmpy2 import mpz >>> mpz('123') + 1 mpz(124) >>> 10 - mpz(1) mpz(9) >>> gmpy2.is_prime(17) TrueNOTE:The use offromgmpy2import*is not recommended. 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.mpzMethodsbit_clear(...)x.bit_clear(n) returns a copy ofxwith bitnset to 0.bit_flip(...)x.bit_flip(n) returns a copy ofxwith bitninverted.bit_length(...)x.bit_length() returns the number of significant bits in the radix-2 representation ofx. For compatibility with Python, mpz(0).bit_length() returns 0.bit_scan0(...)x.bit_scan0(n) returns the index of the first 0-bit ofxwith index >=n. If there are no more 0-bits inxat or above indexn(which can only happen forx< 0, assuming an infinitely long 2's complement format), then None is returned.nmust be >= 0.bit_scan1(...)x.bit_scan1(n) returns the index of the first 1-bit ofxwith index >=n. If there are no more 1-bits inxat or above indexn(which can only happen forx>= 0, assuming an infinitely long 2's complement format), then None is returned.nmust be >= 0.bit_set(...)x.bit_set(n) returns a copy ofxwith bitnset to 0.bit_test(...)x.bit_test(n) returns True if bitnofxis set, and False if it is not set.denominator(...)x.denominator() returns mpz(1).digits(...)x.digits([base=10]) returns a string representingxin radixbase.numerator(...)x.numerator() returns a copy of x.num_digits(...)x.num_digits([base=10]) returns the length of the string representing the absolute value ofxin radixbase. The result is correct if base is a power of 2. For other other bases, the result is usually correct but may be 1 too large.basecan range between 2 and 62, inclusive.mpzFunctionsadd(...)add(x, y) returnsx+y. The result type depends on the input types.bincoef(...)bincoef(x, n) returns the binomial coefficient.nmust be >= 0.bit_clear(...)bit_clear(x, n) returns a copy ofxwith bitnset to 0.bit_flip(...)bit_flip(x, n) returns a copy ofxwith bitninverted.bit_length(...)bit_length(x) returns the number of significant bits in the radix-2 representation ofx. For compatibility with Python, mpz(0).bit_length() returns 0 while mpz(0).num_digits(2) returns 1.bit_mask(...)bit_mask(n) returns anmpzobject exactlynbits in length with all bits set.bit_scan0(...)bit_scan0(x, n) returns the index of the first 0-bit ofxwith index >=n. If there are no more 0-bits inxat or above indexn(which can only happen forx< 0, assuming an infinitely long 2's complement format), then None is returned.nmust be >= 0.bit_scan1(...)bit_scan1(x, n) returns the index of the first 1-bit ofxwith index >=n. If there are no more 1-bits inxat or above indexn(which can only happen forx>= 0, assuming an infinitely long 2's complement format), then None is returned.nmust be >= 0.bit_set(...)bit_set(x, n) returns a copy ofxwith bitnset to 0.bit_test(...)bit_test(x, n) returns True if bitnofxis set, and False if it is not set.c_div(...)c_div(x, y) returns the quotient ofxdivided byy. The quotient is rounded towards +Inf (ceiling rounding).xandymust be integers.c_div_2exp(...)c_div_2exp(x, n) returns the quotient ofxdivided by 2**n. The quotient is rounded towards +Inf (ceiling rounding).xmust be an integer andnmust be > 0.c_divmod(...)c_divmod(x, y) returns the quotient and remainder ofxdivided byy. The quotient is rounded towards +Inf (ceiling rounding) and the remainder will have the opposite sign ofy.xandymust be integers.c_divmod_2exp(...)c_divmod_2exp(x ,n) returns the quotient and remainder ofxdivided by 2**n. The quotient is rounded towards +Inf (ceiling rounding) and the remainder will be negative or zero.xmust be an integer andnmust be > 0.c_mod(...)c_mod(x, y) returns the remainder ofxdivided byy. The remainder will have the opposite sign ofy.xandymust be integers.c_mod_2exp(...)c_mod_2exp(x, n) returns the remainder ofxdivided by 2**n. The remainder will be negative.xmust be an integer andnmust be > 0.comb(...)comb(x, n) returns the number of combinations ofxthings, takingnat a time.nmust be >= 0.digits(...)digits(x[, base=10]) returns a string representingxin radixbase.div(...)div(x, y) returnsx/y. The result type depends on the input types.divexact(...)divexact(x, y) returns the quotient ofxdivided byy. Faster than standard division but requires the remainder is zero!divm(...)divm(a, b, m) returnsxsuch thatb*x==amodulom. Raises a ZeroDivisionError exception if no such valuexexists.f_div(...)f_div(x, y) returns the quotient ofxdivided byy. The quotient is rounded towards -Inf (floor rounding).xandymust be integers.f_div_2exp(...)f_div_2exp(x, n) returns the quotient ofxdivided by 2**n. The quotient is rounded towards -Inf (floor rounding).xmust be an integer andnmust be > 0.f_divmod(...)f_divmod(x, y) returns the quotient and remainder ofxdivided byy. The quotient is rounded towards -Inf (floor rounding) and the remainder will have the same sign asy.xandymust be integers.f_divmod_2exp(...)f_divmod_2exp(x, n) returns quotient and remainder after dividingxby 2**n. The quotient is rounded towards -Inf (floor rounding) and the remainder will be positive.xmust be an integer andnmust be > 0.f_mod(...)f_mod(x, y) returns the remainder ofxdivided byy. The remainder will have the same sign asy.xandymust be integers.f_mod_2exp(...)f_mod_2exp(x, n) returns remainder ofxdivided by 2**n. The remainder will be positive.xmust be an integer andnmust be > 0.fac(...)fac(n) returns the exact factorial ofn. Use factorial() to get the floating-point approximation.fib(...)fib(n) returns then-th Fibonacci number.fib2(...)fib2(n) returns a 2-tuple with the (n-1)-th andn-th Fibonacci numbers.gcd(...)gcd(a, b) returns the greatest common denominator of integersaandb.gcdext(...)gcdext(a, b) returns a 3-element tuple (g,s,t) such thatg== gcd(a,b) andg==a*s+b*thamdist(...)hamdist(x, y) returns the Hamming distance (number of bit-positions where the bits differ) between integersxandy.invert(...)invert(x, m) returnsysuch thatx*y== 1 modulom, or 0 if no suchyexists.iroot(...)iroot(x,n) returns a 2-element tuple (y,b) such thatyis the integern-th root ofxandbis True if the root is exact.xmust be >= 0 andnmust be > 0.iroot_rem(...)iroot_rem(x,n) returns a 2-element tuple (y,r) such thatyis the integern-th root ofxandx= y**n +r.xmust be >= 0 andnmust be > 0.is_even(...)is_even(x) returns True ifxis even, False otherwise.is_odd(...)is_odd(x) returns True ifxis odd, False otherwise.is_power(...)is_power(x) returns True ifxis a perfect power, False otherwise.is_prime(...)is_prime(x[, n=25]) returns True ifxisprobablyprime. False is returned ifxis definately composite.xis checked for small divisors and up tonMiller-Rabin tests are performed. The actual tests performed may vary based on version of GMP or MPIR used.is_square(...)is_square(x) returns True ifxis a perfect square, False otherwise.isqrt(...)isqrt(x) returns the integer square root of an integerx.xmust be >= 0.isqrt_rem(...)isqrt_rem(x) returns a 2-tuple (s,t) such thats= isqrt(x) andt=x-s*s.xmust be >= 0.jacobi(...)jacobi(x, y) returns the Jacobi symbol (x|y).ymust be odd and > 0.kronecker(...)kronecker(x, y) returns the Kronecker-Jacobi symbol (x|y).lcm(...)lcm(a, b) returns the lowest common multiple of integersaandb.legendre(...)legendre(x, y) returns the Legendre symbol (x|y).yis assumed to be an odd prime.lucas(...)lucas(n) returns then-th Lucas number.lucas2(...)lucas2(n) returns a 2-tuple with the (n-1)-th andn-th Lucas numbers.mpz(...)mpz() returns a newmpzobject set to 0. mpz(n) returns a newmpzobject from a numeric valuen. Ifnis not an integer, it will be truncated to an integer. mpz(s[, base=0]) returns a newmpzobject from a stringsmade of digits in the given base. If base = 0, thn binary, octal, or hex Python strings are recognized by leading 0b, 0o, or 0x characters. Otherwise the string is assumed to be decimal. Values for base can range between 2 and 62.mpz_random(...)mpz_random(random_state, n) returns a uniformly distributed random integer between 0 andn-1. The parameterrandom_statemust be created by random_state() first.mpz_rrandomb(...)mpz_rrandomb(random_state, b) returns a random integer between 0 and 2**b - 1 with long sequences of zeros and one in its binary representation. The parameterrandom_statemust be created by random_state() first.mpz_urandomb(...)mpz_urandomb(random_state, b) returns a uniformly distributed random integer between 0 and 2**b - 1. The parameterrandom_statemust be created by random_state() first.mul(...)mul(x, y) returnsx*y. The result type depends on the input types.next_prime(...)next_prime(x) returns the nextprobableprime number >x.num_digits(...)num_digits(x[, base=10]) returns the length of the string representing the absolute value ofxin radixbase. The result is correct if base is a power of 2. For other other bases, the result is usually correct but may be 1 too large.basecan range between 2 and 62, inclusive.popcount(...)popcount(x) returns the number of bits with value 1 inx. Ifx< 0, the number of bits with value 1 is infinite so -1 is returned in that case.powmod(...)powmod(x, y, m) returns (x**y) modm. The exponenentycan be negative, and the correct result will be returned if the inverse ofxmodmexists. Otherwise, a ValueError is raised.remove(...)remove(x, f) will remove the factorffromxas many times as possible and return a 2-tuple (y,m) wherey=x// (f**m).fdoes not dividey.mis the multiplicity of the factorfinx.fmust be > 1.sub(...)sub(x, y) returnsx-y. The result type depends on the input types.t_div(...)t_div(x, y) returns the quotient ofxdivided byy. The quotient is rounded towards zero (truncation).xandymust be integers.t_div_2exp(...)t_div_2exp(x, n) returns the quotient ofxdivided by 2**n. The quotient is rounded towards zero (truncation).nmust be > 0.t_divmod(...)t_divmod(x, y) returns the quotient and remainder ofxdivided byy. The quotient is rounded towards zero (truncation) and the remainder will have the same sign asx.xandymust be integers.t_divmod_2exp(...)t_divmod_2exp(x, n) returns the quotient and remainder ofxdivided by 2**n. The quotient is rounded towards zero (truncation) and the remainder will have the same sign asx.xmust be an integer andnmust be > 0.t_mod(...)t_mod(x, y) returns the remainder ofxdivided byy. The remainder will have the same sign asx.xandymust be integers.t_mod_2exp(...)t_mod_2exp(x, n) returns the remainder ofxdivided by 2**n. The remainder will have the same sign asx.xmust be an integer andnmust be > 0.

**MULTIPLE-PRECISION** **INTEGERS** **(ADVANCED** **TOPICS)**

Thexmpztypegmpy2 provides access to an experimental integer type calledxmpz. Thexmpztype is a mutable integer type. In-place operations (+=, //=, etc.) modify the orignal object and do not create a new object. Instances ofxmpzcannot be used as dictionary keys. >>> import gmpy2 >>> from gmpy2 import xmpz >>> a = xmpz(123) >>> b = a >>> a += 1 >>> a xmpz(124) >>> b xmpz(124) The ability to change anxmpzobject in-place allows for efficient and rapid bit manipulation. Individual bits can be set or cleared: >>> a[10]=1 >>> a xmpz(1148) Slice notation is supported. The bits referenced by a slice can be either 'read from' or 'written to'. To clear a slice of bits, use a source value of 0. In 2s-complement format, 0 is represented by an arbitrary number of 0-bits. To set a slice of bits, use a source value of ~0. Thetildeoperator 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 forstopis specified in a slice assignment and the actual bit-length of thexmpzis less thanstop, then the destinationxmpzis logically padded with 0-bits to lengthstop. >>> a=xmpz(0) >>> a[8:16] = ~0 >>> bin(a) '0b1111111100000000' >>> a[4:12] = ~a[4:12] >>> bin(a) '0b1111000011110000' Bits can be reversed: >>> bin(a) '0b10001111100' >>> a[::] = a[::-1] >>> bin(a) '0b111110001' Theiter_bits()method returns a generator that returns True or False for each bit position. The methodsiter_clear(), anditer_set()return generators that return the bit positions that are 1 or 0. The methods support argumentsstartandstopthat define the beginning and ending bit positions that are used. To mimic the behavior of slices. the bit positions checked includestartbut the last position checked isstop- 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. from __future__ import print_function 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))AdvancedNumberTheoryFunctionsThe following functions are based on mpz_lucas.c and mpz_prp.c by David Cleaver. A good reference for probable prime testing ishttp://www.pseudoprime.com/pseudo.htmlis_bpsw_prp(...)is_bpsw_prp(n) will return True ifnis 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.is_euler_prp(...)is_euler_prp(n,a) will return True ifnis an Euler (also known as Solovay-Strassen) probable prime to the basea. Assuming: gcd(n, a) == 1 n is odd Then an Euler probable prime requires: a**((n-1)/2) == 1 (mod n)is_extra_strong_lucas_prp(...)is_extra_strong_lucas_prp(n,p) will return True ifnis 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) or lucasv(p,1,s) == +/-2 (mod n) or lucasv(p,1,s*(2**t)) == 0 (mod n) for some t, 0 <= t < ris_fermat_prp(...)is_fermat_prp(n,a) will return True ifnis 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)is_fibonacci_prp(...)is_fibonacci_prp(n,p,q) will return True ifnis an 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).is_lucas_prp(...)is_lucas_prp(n,p,q) will return True ifnis 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)is_selfridge_prp(...)is_selfridge_prp(n) will return True ifnis a Lucas probable prime with Selfidge parameters (p,q). The Selfridge parameters are chosen by finding the first element D in the sequence {5, -7, 9, -11, 13, ...} such that Jacobi(D,n) == -1. Let p=1 and q = (1-D)/4 and then perform a Lucas probable prime test.is_strong_bpsw_prp(...)is_strong_bpsw_prp(n) will return True ifnis a strong Baillie-Pomerance-Selfridge-Wagstaff probable prime. A strong BPSW probable prime passes the is_strong_prp() test with base 2 and the is_strongselfridge_prp() test.is_strong_lucas_prp(...)is_strong_lucas_prp(n,p,q) will return True ifnis 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 < ris_strong_prp(...)is_strong_prp(n,a) will return True ifnis an strong (also known as Miller-Rabin) probable prime to the base a. Assuming: gcd(n,a) == 1 n is odd n = s*(2**r) + 1, with s odd Then a strong probable prime requires one of the following is true: a**s == 1 (mod n) or a**(s*(2**t)) == -1 (mod n) for some t, 0 <= t < r.is_strong_selfridge_prp(...)is_strong_selfridge_prp(n) will return True ifnis a strong Lucas probable prime with Selfidge parameters (p,q). The Selfridge parameters are chosen by finding the first element D in the sequence {5, -7, 9, -11, 13, ...} such that Jacobi(D,n) == -1. Let p=1 and q = (1-D)/4 and then perform a strong Lucas probable prime test.lucasu(...)lucasu(p,q,k) will 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.lucasu_mod(...)lucasu_mod(p,q,k,n) will return the k-th element of the Lucas U sequence defined by p,q (mod n). p*p - 4*q must not equal 0; k must be greater than or equal to 0; n must be greater than 0.lucasv(...)lucasv(p,q,k) will return the k-th element of the Lucas V sequence defined by parameters (p,q). p*p - 4*q must not equal 0; k must be greater than or equal to 0.lucasv_mod(...)lucasv_mod(p,q,k,n) will return the k-th element of the Lucas V sequence defined by parameters (p,q) (mod n). p*p - 4*q must not equal 0; k must be greater than or equal to 0; n must be greater than 0.

**MULTIPLE-PRECISION** **RATIONALS**

gmpy2 provides a rational type callmpq. It should be a replacement for Python's fractions.Fraction module. >>> import gmpy2 >>> from gmpy2 import mpq >>> mpq(1,7) mpq(1,7) >>> mpq(1,7) * 11 mpq(11,7) >>> mpq(11,7)/13 mpq(11,91)mpqMethodsdigits(...)x.digits([base=10]) returns a Python string representingxin the given base (2 to 62, default is 10). A leading '-' is present ifx< 0, but no leading '+' is present ifx>= 0.mpqAttributesdenominatorx.denomintor returns the denominator ofx.numeratorx.numerator returns the numerator ofx.mpqFunctionsadd(...)add(x, y) returnsx+y. The result type depends on the input types.div(...)div(x, y) returnsx/y. The result type depends on the input types.f2q(...)f2q(x[, err]) returns the bestmpqapproximatingxto within relative errorerr. Default is the precision ofx. Ifxis not anmpfr, it is converted to anmpfr. Uses Stern-Brocot tree to find the best approximation. Anmpzis returned if the the denominator is 1. Iferr< 0, then the relative error sought is 2.0 **err.mpq(...)mpq() returns anmpqobject set to 0/1. mpq(n) returns anmpqobject with a numeric valuen. Decimal and Fraction values are converted exactly. mpq(n, m) returns anmpqobject with a numeric valuen/m. mpq(s[, base=10]) returns anmpqobject from a stringsmade up of digits in the given base.smay be made up of two numbers in the same base separated by a '/' character. Ifbase== 10, then an embedded '.' indicates a number with a decimal fractional part.mul(...)mul(x, y) returnsx*y. The result type depends on the input types.qdiv(...)qdiv(x[, y=1]) returnsx/yasmpzif possible, or asmpqifxis not exactly divisible byy.sub(...)sub(x, y) returnsx-y. The result type depends on the input types.

**MULTIPLE-PRECISION** **REALS**

gmpy2 replaces thempftype from gmpy 1.x with a newmpfrtype based on the MPFR library. The newmpfrtype supports correct rounding, selectable rounding modes, and many trigonometric, exponential, and special functions. Acontextmanageris used to control precision, rounding modes, and the behavior of exceptions. The default precision of anmpfris 53 bits - the same precision as Python'sfloattype. If the precison is changed, thenmpfr(float('1.2'))differs frommpfr('1.2'). To take advantage of the higher precision provided by thempfrtype, always pass constants as strings. >>> import gmpy2 >>> from gmpy2 import mpfr >>> mpfr('1.2') mpfr('1.2') >>> mpfr(float('1.2')) mpfr('1.2') >>> gmpy2.get_context().precision=100 >>> mpfr('1.2') mpfr('1.2000000000000000000000000000006',100) >>> mpfr(float('1.2')) mpfr('1.1999999999999999555910790149937',100) >>>ContextsWARNING:Contexts and context managers are not thread-safe! Modifying the context in one thread will impact all other threads. Acontextis used to control the behavior ofmpfrandmpcarithmetic. In addition to controlling the precision, the rounding mode can be specified, minimum and maximum exponent values can be changed, various exceptions can be raised or ignored, gradual underflow can be enabled, and returning complex results can be enabled.gmpy2.context()creates a new context with all options set to default.gmpy2.set_context(ctx)will set the active context toctx.gmpy2.get_context()will return a reference to the active context. Note that contexts are mutable: modifying the reference returned by get_context() will modify the active context until a new context is enabled with set_context(). Thecopy()method of a context will return a copy of the context. The following example just modifies the precision. The remaining options will be discussed later. >>> gmpy2.set_context(gmpy2.context()) >>> gmpy2.get_context() context(precision=53, real_prec=Default, imag_prec=Default, round=RoundToNearest, real_round=Default, imag_round=Default, emax=1073741823, emin=-1073741823, subnormalize=False, trap_underflow=False, underflow=False, trap_overflow=False, overflow=False, trap_inexact=False, inexact=False, trap_invalid=False, invalid=False, trap_erange=False, erange=False, trap_divzero=False, divzero=False, trap_expbound=False, allow_complex=False) >>> gmpy2.sqrt(5) mpfr('2.2360679774997898') >>> gmpy2.get_context().precision=100 >>> gmpy2.sqrt(5) mpfr('2.2360679774997896964091736687316',100) >>> gmpy2.get_context().precision+=20 >>> gmpy2.sqrt(5) mpfr('2.2360679774997896964091736687312762351',120) >>> ctx=gmpy2.get_context() >>> ctx.precision+=20 >>> gmpy2.sqrt(5) mpfr('2.2360679774997896964091736687312762354406182',140) >>> gmpy2.set_context(gmpy2.context()) >>> gmpy2.sqrt(5) mpfr('2.2360679774997898') >>> ctx.precision+=20 >>> gmpy2.sqrt(5) mpfr('2.2360679774997898') >>> gmpy2.set_context(ctx) >>> gmpy2.sqrt(5) mpfr('2.2360679774997896964091736687312762354406183596116',160) >>>ContextAttributesprecisionThis attribute controls the precision of anmpfrresult. The precision is specified in bits, not decimal digits. The maximum precision that can be specified is platform dependent and can be retrieved withget_max_precision().NOTE:Specifying a value for precision that is too close to the maximum precision will cause the MPFR library to fail.real_precThis attribute controls the precision of the real part of anmpcresult. If the value isDefault, then the value of the precision attribute is used.imag_precThis attribute controls the precision of the imaginary part of anmpcresult. If the value isDefault, then the value of real_prec is used.roundThere are five rounding modes availble tompfrtypes:RoundAwayZeroThe result is rounded away from 0.0.RoundDownThe result is rounded towards -Infinity.RoundToNearestRound to the nearest value; ties are rounded to an even value.RoundToZeroThe result is rounded towards 0.0.RoundUpThe result is rounded towards +Infinity.real_roundThis attribute controls the rounding mode for the real part of anmpcresult. If the value isDefault, then the value of the round attribute is used. Note:RoundAwayZerois not a valid rounding mode formpc.imag_roundThis attribute controls the rounding mode for the imaginary part of anmpcresult. If the value isDefault, then the value of the real_round attribute is used. Note:RoundAwayZerois not a valid rounding mode formpc.emaxThis attribute controls the maximum allowed exponent of anmpfrresult. The maximum exponent is platform dependent and can be retrieved withget_emax_max().eminThis attribute controls the minimum allowed exponent of anmpfrresult. The minimum exponent is platform dependent and can be retrieved withget_emin_min().NOTE:It is possible to change the values of emin/emax such that previousmpfrvalues are no longer valid numbers but should either underflow to +/-0.0 or overflow to +/-Infinity. To raise an exception if this occurs, seetrap_expbound.subnormalizeThe usual IEEE-754 floating point representation supports gradual underflow when the minimum exponent is reached. The MFPR library does not enable gradual underflow by default but it can be enabled to precisely mimic the results of IEEE-754 floating point operations.trap_underflowIf set toFalse, a result that is smaller than the smallest possiblempfrgiven the current exponent range will be replaced by +/-0.0. If set toTrue, anUnderflowResultErrorexception is raised.underflowThis flag is not user controllable. It is automatically set if a result underflowed to +/-0.0 and trap_underflow isFalse.trap_overflowIf set toFalse, a result that is larger than the largest possiblempfrgiven the current exponent range will be replaced by +/-Infinity. If set toTrue, anOverflowResultErrorexception is raised.overflowThis flag is not user controllable. It is automatically set if a result overflowed to +/-Infinity and trap_overflow isFalse.trap_inexactThis attribute controls whether or not anInexactResultErrorexception is raised if an inexact result is returned. To check if the result is greater or less than the exact result, check thercattribute of thempfrresult.inexactThis flag is not user controllable. It is automatically set if an inexact result is returned.trap_invalidThis attribute controls whether or not anInvalidOperationErrorexception is raised if a numerical result is not defined. A special NaN (Not-A-Number) value will be returned if an exception is not raised. TheInvalidOperationErroris a sub-class of Python'sValueError. For example,gmpy2.sqrt(-2)will normally returnmpfr('nan'). However, if allow_complex is set toTrue, then anmpcresult will be returned.invalidThis flag is not user controllable. It is automatically set if an invalid (Not-A-Number) result is returned.trap_erangeThis attribute controls whether or not aRangeErrorexception is raised when certain operations are performed on NaN and/or Infinity values. Setting trap_erange toTruecan be used to raise an exception if comparisons are attempted with a NaN. >>> gmpy2.set_context(gmpy2.context()) >>> mpfr('nan') == mpfr('nan') False >>> gmpy2.get_context().trap_erange=True >>> mpfr('nan') == mpfr('nan') Traceback (most recent call last): File "<stdin>", line 1, in <module> gmpy2.RangeError: comparison with NaN >>>erangeThis flag is not user controllable. It is automatically set if an erange error occurred.trap_divzeroThis attribute controls whether or not aDivisionByZeroErrorexception is raised if division by 0 occurs. TheDivisionByZeroErroris a sub-class of Python'sZeroDivisionError.divzeroThis flag is not user controllable. It is automatically set if a division by zero occurred and NaN result was returned.trap_expboundThis attribute controls whether or not anExponentOutOfBoundsErrorexception is raised if exponents in an operand are outside the current emin/emax limits.allow_complexThis attribute controls whether or not anmpcresult can be returned if anmpfrresult would normally not be possible.ContextMethodsclear_flags()Clear the underflow, overflow, inexact, invalid, erange, and divzero flags.copy()Return a copy of the context.ContextsandthewithstatementContexts can also be used in conjunction with Python'swith...statement to temporarily change the context settings for a block of code and then restore the original settings when the block of code exits.gmpy2.local_context()first save the current context and then creates a new context based on a context passed as the first argument, or the current context if no context is passed. The new context is modified if any optional keyword arguments are given. The orginal active context is restored when the block completes. In the following example, the current context is saved bygmpy2.local_context()and then the block begins with a copy of the default context and the precision set to 100. When the block is finished, the original context is restored. >>> with gmpy2.local_context(gmpy2.context(), precision=100) as ctx: ... print(gmpy2.sqrt(2)) ... ctx.precision += 100 ... print(gmpy2.sqrt(2)) ... 1.4142135623730950488016887242092 1.4142135623730950488016887242096980785696718753769480731766796 >>> A context object can also be used directly to create a context manager block. However, instead of restoring the context to the active context when thewith...statement is executed, the restored context is the context used before any keyword argument modifications. The code:::with gmpy2.ieee(64) as ctx: is equivalent to:::gmpy2.set_context(gmpy2.ieee(64)) with gmpy2.local_context() as ctx: Contexts that implement the standardsingle,double, andquadrupleprecision floating point types can be created usingieee().mpfrMethodsas_integer_ratio()Returns a 2-tuple containing the numerator and denominator after converting thempfrobject into the exact rational equivalent. The return 2-tuple is equivalent to Python's as_integer_ratio() method of built-in float objects.as_mantissa_exp()Returns a 2-tuple containing the mantissa and exponent.as_simple_fraction()Returns anmpqcontaining the simpliest rational value that approximates thempfrvalue with an error less than 1/(2**precision).conjugate()Returns the complex conjugate. Formpfrobjects, returns a copy of the original object.digits()Returns a 3-tuple containing the mantissa, the exponent, and the number of bits of precision. The mantissa is represented as a string in the specified base with up to 'prec' digits. If 'prec' is 0, as many digits that are available are returned. No more digits than available given x's precision are returned. 'base' must be between 2 and 62, inclusive.is_integer()Returns True if thempfrobject is an integer.mpfrAttributesimagReturns the imaginary component. Formpfrobjects, returns 0.precisionReturns the precision of thempfrobject.rcThe result code (also known as ternary value in the MPFR documentation) is 0 if the value of thempfrobject is exactly equal to the exact, infinite precision value. If the result code is 1, then the value of thempfrobject is greater than the exact value. If the result code is -1, then the value of thempfrobject is less than the exact, infinite precision value.realReturns the real component. Formpfrobjects, returns a copy of the original object.mpfrFunctionsacos(...)acos(x) returns the arc-cosine of x. x is measured in radians. If context.allow_complex is True, then anmpcresult will be returned for abs(x) > 1.acosh(...)acosh(x) returns the inverse hyperbolic cosine of x.add(...)add(x, y) returns x + y. The type of the result is based on the types of the arguments.agm(...)agm(x, y) returns the arithmetic-geometric mean of x and y.ai(...)ai(x) returns the Airy function of x.asin(...)asin(x) returns the arc-sine of x. x is measured in radians. If context.allow_complex is True, then anmpcresult will be returned for abs(x) > 1.asinh(...)asinh(x) return the inverse hyperbolic sine of x.atan(...)atan(x) returns the arc-tangent of x. x is measured in radians.atan2(...)atan2(y, x) returns the arc-tangent of (y/x).atanh(...)atanh(x) returns the inverse hyperbolic tangent of x. If context.allow_complex is True, then anmpcresult will be returned for abs(x) > 1.cbrt(...)cbrt(x) returns the cube root of x.ceil(...)ceil(x) returns the 'mpfr' that is the smallest integer >= x.check_range(...)check_range(x) return a new 'mpfr' with exponent that lies within the current range of emin and emax.const_catalan(...)const_catalan([precision=0]) returns the catalan constant using the specified precision. If no precision is specified, the default precision is used.const_euler(...)const_euler([precision=0]) returns the euler constant using the specified precision. If no precision is specified, the default precision is used.const_log2(...)const_log2([precision=0]) returns the log2 constant using the specified precision. If no precision is specified, the default precision is used.const_pi(...)const_pi([precision=0]) returns the constant pi using the specified precision. If no precision is specified, the default precision is used.context(...)context() returns a new context manager controlling MPFR and MPC arithmetic.cos(...)cos(x) seturns the cosine of x. x is measured in radians.cosh(...)cosh(x) returns the hyperbolic cosine of x.cot(...)cot(x) returns the cotangent of x. x is measured in radians.coth(...)coth(x) returns the hyperbolic cotangent of x.csc(...)csc(x) returns the cosecant of x. x is measured in radians.csch(...)csch(x) returns the hyperbolic cosecant of x.degrees(...)degrees(x) converts an angle measurement x from radians to degrees.digamma(...)digamma(x) returns the digamma of x.div(...)div(x, y) returns x / y. The type of the result is based on the types of the arguments.div_2exp(...)div_2exp(x, n) returns an 'mpfr' or 'mpc' divided by 2**n.eint(...)eint(x) returns the exponential integral of x.erf(...)erf(x) returns the error function of x.erfc(...)erfc(x) returns the complementary error function of x.exp(...)exp(x) returns e**x.exp10(...)exp10(x) returns 10**x.exp2(...)exp2(x) returns 2**x.expm1(...)expm1(x) returns e**x - 1. expm1() is more accurate than exp(x) - 1 when x is small.f2q(...)f2q(x[,err]) returns the simplestmpqapproximating x to within relative error err. Default is the precision of x. Uses Stern-Brocot tree to find the simplist approximation. Anmpzis returned if the the denominator is 1. If err<0, error sought is 2.0 ** err.factorial(...)factorial(n) returns the floating-point approximation to the factorial of n. See fac(n) to get the exact integer result.floor(...)floor(x) returns the 'mpfr' that is the smallest integer <= x.fma(...)fma(x, y, z) returns correctly rounded result of (x * y) + z.fmod(...)fmod(x, y) returns x - n*y where n is the integer quotient of x/y, rounded to 0.fms(...)fms(x, y, z) returns correctly rounded result of (x * y) - z.frac(...)frac(x) returns the fractional part of x.frexp(...)frexp(x) returns a tuple containing the exponent and mantissa of x.fsum(...)fsum(iterable) returns the accurate sum of the values in the iterable.gamma(...)gamma(x) returns the gamma of x.get_exp(...)get_exp(mpfr) returns the exponent of anmpfr. Returns 0 for NaN or Infinity and sets the erange flag and will raise an exception if trap_erange is set.hypot(...)hypot(y, x) returns square root of (x**2 + y**2).ieee(...)ieee(bitwidth) returns a context with settings for 32-bit (aka single), 64-bit (aka double), or 128-bit (aka quadruple) precision floating point types.inf(...)inf(n) returns anmpfrinitialized to Infinity with the same sign as n. If n is not given, +Infinity is returned.is_finite(...)is_finite(x) returns True if x is an actual number (i.e. not NaN or Infinity).is_inf(...)is_inf(x) returns True if x is Infinity or -Infinity.NOTE:is_inf()is deprecated; please useif_infinite().is_infinite(...)is_infinite(x) returns True if x Infinity or -Infinity.is_nan(...)is_nan(x) returns True if x is NaN (Not-A-Number).is_number(...)is_number(x) returns True if x is an actual number (i.e. not NaN or Infinity).NOTE:is_number()is deprecated; please useis_finite().is_regular(...)is_regular(x) returns True if x is not zero, NaN, or Infinity.is_signed(...)is_signed(x) returns True if the sign bit of x is set.is_unordered(...)is_unordered(x,y) returns True if either x and/or y is NaN.is_zero(...)is_zero(x) returns True if x is zero.j0(...)j0(x) returns the Bessel function of the first kind of order 0 of x.j1(...)j1(x) returns the Bessel function of the first kind of order 1 of x.jn(...)jn(x,n) returns the Bessel function of the first kind of order n of x.lgamma(...)lgamma(x) returns a tuple containing the logarithm of the absolute value of gamma(x) and the sign of gamma(x)li2(...)li2(x) returns the real part of dilogarithm of x.lngamma(...)lngamma(x) returns the logarithm of gamma(x).log(...)log(x) returns the natural logarithm of x.log10(...)log10(x) returns the base-10 logarithm of x.log1p(...)log1p(x) returns the natural logarithm of (1+x).log2(...)log2(x) returns the base-2 logarithm of x.max2(...)max2(x, y) returns the maximum of x and y. The result may be rounded to match the current context. Use the builtin max() to get an exact copy of the largest object without any rounding.min2(...)min2(x, y) returns the minimum of x and y. The result may be rounded to match the current context. Use the builtin min() to get an exact copy of the smallest object without any rounding.modf(...)modf(x) returns a tuple containing the integer and fractional portions of x.mpfr(...)mpfr() returns andmpfrobject set to 0.0. mpfr(n[, precison=0]) returns anmpfrobject after converting a numeric value n. If no precision, or a precision of 0, is specified; the precision is taken from the current context. mpfr(s[, precision=0[, [base=0]]) returns anmpfrobject after converting a string 's' made up of digits in the given base, possibly with fractional part (with period as a separator) and/or exponent (with exponent marker 'e' for base<=10, else '@'). If no precision, or a precision of 0, is specified; the precison is taken from the current context. The base of the string representation must be 0 or in the interval 2 ... 62. If the base is 0, the leading digits of the string are used to identify the base: 0b implies base=2, 0x implies base=16, otherwise base=10 is assumed.mpfr_from_old_binary(...)mpfr_from_old_binary(string) returns anmpfrfrom a GMPY 1.x binary mpf format. Please use to_binary()/from_binary() to convert GMPY2 objects to or from a binary format.mpfr_grandom(...)mpfr_grandom(random_state) returns two random numbers with gaussian distribution. The parameterrandom_statemust be created by random_state() first.mpfr_random(...)mpfr_random(random_state) returns a uniformly distributed number between [0,1]. The parameterrandom_statemust be created by random_state() first.mul(...)mul(x, y) returns x * y. The type of the result is based on the types of the arguments.mul_2exp(...)mul_2exp(x, n) returns 'mpfr' or 'mpc' multiplied by 2**n.nan(...)nan() returns an 'mpfr' initialized to NaN (Not-A-Number).next_above(...)next_above(x) returns the next 'mpfr' from x toward +Infinity.next_below(...)next_below(x) returns the next 'mpfr' from x toward -Infinity.radians(...)radians(x) converts an angle measurement x from degrees to radians.rec_sqrt(...)rec_sqrt(x) returns the reciprocal of the square root of x.reldiff(...)reldiff(x, y) returns the relative difference between x and y. Result is equal to abs(x-y)/x.remainder(...)remainder(x, y) returns x - n*y where n is the integer quotient of x/y, rounded to the nearest integer and ties rounded to even.remquo(...)remquo(x, y) returns a tuple containing the remainder(x,y) and the low bits of the quotient.rint(...)rint(x) returns x rounded to the nearest integer using the current rounding mode.rint_ceil(...)rint_ceil(x) 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.rint_floor(...)rint_floor(x) 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.rint_round(...)rint_round(x) 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.rint_trunc(...)rint_trunc(x) returns x rounded to the nearest integer by first rounding towards zero and then, if needed, using the current rounding mode.root(...)root(x, n) returns n-th root of x. The result always anmpfr.round2(...)round2(x[, n]) returns x rounded to n bits. Uses default precision if n is not specified. See round_away() to access the mpfr_round() function. Use the builtin round() to round x to n decimal digits.round_away(...)round_away(x) returns anmpfrby rounding x the nearest integer, with ties rounded away from 0.sec(...)sec(x) returns the secant of x. x is measured in radians.sech(...)sech(x) returns the hyperbolic secant of x.set_exp(...)set_exp(x, n) sets the exponent of a givenmpfrto n. If n is outside the range of valid exponents, set_exp() will set the erange flag and either return the original value or raise an exception if trap_erange is set.set_sign(...)set_sign(x, bool) returns a copy of x with it's sign bit set ifboolevaluates to True.sign(...)sign(x) returns -1 if x < 0, 0 if x == 0, or +1 if x >0.sin(...)sin(x) returns the sine of x. x is measured in radians.sin_cos(...)sin_cos(x) returns a tuple containing the sine and cosine of x. x is measured in radians.sinh(...)sinh(x) returns the hyberbolic sine of x.sinh_cosh(...)sinh_cosh(x) returns a tuple containing the hyperbolic sine and cosine of x.sqrt(...)sqrt(x) returns the square root of x. If x is integer, rational, or real, then anmpfrwill be returned. If x is complex, then anmpcwill be returned. If context.allow_complex is True, negative values of x will return anmpc.square(...)square(x) returns x * x. The type of the result is based on the types of the arguments.sub(...)sub(x, y) returns x - y. The type of the result is based on the types of the arguments.tan(...)tan(x) returns the tangent of x. x is measured in radians.tanh(...)tanh(x) returns the hyperbolic tangent of x.trunc(...)trunc(x) returns an 'mpfr' that is x truncated towards 0. Same as x.floor() if x>=0 or x.ceil() if x<0.y0(...)y0(x) returns the Bessel function of the second kind of order 0 of x.y1(...)y1(x) returns the Bessel function of the second kind of order 1 of x.yn(...)yn(x,n) returns the Bessel function of the second kind of order n of x.zero(...)zero(n) returns anmpfrinialized to 0.0 with the same sign as n. If n is not given, +0.0 is returned.zeta(...)zeta(x) returns the Riemann zeta of x.mpfrFormattingThempfrtype supports the __format__() special method to allow custom output formatting.__format__(...)x.__format__(fmt) 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 scientific formatNOTE:The formatting codes must be specified in the order shown above. >>> import gmpy2 >>> from gmpy2 import mpfr >>> 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'

**MULTIPLE-PRECISION** **COMPLEX**

gmpy2 adds a multiple-precision complex type calledmpcthat is based on the MPC library. The context manager settings formpfrarithmetic are applied tompcarithmetic by default. It is possible to specifiy different precision and rounding modes for both the real and imaginary components of anmpc. >>> import gmpy2 >>> from gmpy2 import mpc >>> gmpy2.sqrt(mpc("1+2j")) mpc('1.272019649514069+0.78615137775742328j') >>> gmpy2.get_context(real_prec=100,imag_prec=200) context(precision=53, real_prec=100, imag_prec=200, round=RoundToNearest, real_round=Default, imag_round=Default, emax=1073741823, emin=-1073741823, subnormalize=False, trap_underflow=False, underflow=False, trap_overflow=False, overflow=False, trap_inexact=False, inexact=True, trap_invalid=False, invalid=False, trap_erange=False, erange=False, trap_divzero=False, divzero=False, trap_expbound=False, allow_complex=False) >>> gmpy2.sqrt(mpc("1+2j")) mpc('1.2720196495140689642524224617376+0.78615137775742328606955858584295892952312205783772323766490213j',(100,200)) Exceptions are normally raised in Python when the result of a real operation is not defined over the reals; for example,sqrt(-4)will raise an exception. The default context in gmpy2 implements the same behavior but by setting allow_complex to True, complex results will be returned. >>> import gmpy2 >>> from gmpy2 import mpc >>> gmpy2.sqrt(-4) mpfr('nan') >>> gmpy2.get_context(allow_complex=True) context(precision=53, real_prec=Default, imag_prec=Default, round=RoundToNearest, real_round=Default, imag_round=Default, emax=1073741823, emin=-1073741823, subnormalize=False, trap_underflow=False, underflow=False, trap_overflow=False, overflow=False, trap_inexact=False, inexact=False, trap_invalid=False, invalid=True, trap_erange=False, erange=False, trap_divzero=False, divzero=False, trap_expbound=False, allow_complex=True) >>> gmpy2.sqrt(-4) mpc('0.0+2.0j')mpcMethodsconjugate()Returns the complex conjugate.digits()Returns a two element tuple where each element represents the real and imaginary components as a 3-tuple containing the mantissa, the exponent, and the number of bits of precision. The mantissa is represented as a string in the specified base with up to 'prec' digits. If 'prec' is 0, as many digits that are available are returned. No more digits than available given x's precision are returned. 'base' must be between 2 and 62, inclusive.mpcAttributesimagReturns the imaginary component.precisionReturns a 2-tuple containing the the precision of the real and imaginary components.rcReturns a 2-tuple containing the ternary value of the real and imaginary components. The ternary value is 0 if the value of the component is exactly equal to the exact, infinite precision value. If the result code is 1, then the value of the component is greater than the exact value. If the result code is -1, then the value of the component is less than the exact, infinite precision value.realReturns the real component.mpcFunctionsacos(...)acos(x) returns the arc-cosine of x.acosh(...)acosh(x) returns the inverse hyperbolic cosine of x.add(...)add(x, y) returns x + y. The type of the result is based on the types of the arguments.asin(...)asin(x) returns the arc-sine of x.asinh(...)asinh(x) return the inverse hyperbolic sine of x.atan(...)atan(x) returns the arc-tangent of x.atanh(...)atanh(x) returns the inverse hyperbolic tangent of x.cos(...)cos(x) seturns the cosine of x.cosh(...)cosh(x) returns the hyperbolic cosine of x.div(...)div(x, y) returns x / y. The type of the result is based on the types of the arguments.div_2exp(...)div_2exp(x, n) returns an 'mpfr' or 'mpc' divided by 2**n.exp(...)exp(x) returns e**x.fma(...)fma(x, y, z) returns correctly rounded result of (x * y) + z.fms(...)fms(x, y, z) returns correctly rounded result of (x * y) - z.is_inf(...)is_inf(x) returns True if either the real or imaginary component of x is Infinity or -Infinity.is_nan(...)is_nan(x) returns True if either the real or imaginary component of x is NaN (Not-A-Number).is_zero(...)is_zero(x) returns True if x is zero.log(...)log(x) returns the natural logarithm of x.log10(...)log10(x) returns the base-10 logarithm of x.mpc(...)mpc() returns anmpcobject set to 0.0+0.0j. mpc(c[, precision=0]) returns a new 'mpc' object from an existing complex number (either a Python complex object or another 'mpc' object). If the precision is not specified, then the precision is taken from the current context. The rounding mode is always taken from the current context. mpc(r[, i=0[, precision=0]]) returns a new 'mpc' object by converting two non-complex numbers into the real and imaginary components of an 'mpc' object. If the precision is not specified, then the precision is taken from the current context. The rounding mode is always taken from the current context. mpc(s[, [precision=0[, base=10]]) returns a new 'mpc' object by converting a string s into a complex number. If base is omitted, then a base-10 representation is assumed otherwise a base between 2 and 36 can be specified. If the precision is not specified, then the precision is taken from the current context. The rounding mode is always taken from the current context. In addition to the standard Python string representation of a complex number:"1+2j", the string representation used by the MPC library:"(12)"is also supported.NOTE:The precision can be specified either a single number that is used for both the real and imaginary components, or as a 2-tuple that can specify different precisions for the real and imaginary components.mpc_random(...)mpfc_random(random_state) returns a uniformly distributed number in the unit square [0,1]x[0,1]. The parameterrandom_statemust be created by random_state() first.mul(...)mul(x, y) returns x * y. The type of the result is based on the types of the arguments.mul_2exp(...)mul_2exp(x, n) returns 'mpfr' or 'mpc' multiplied by 2**n.norm(...)norm(x) returns the norm of a complex x. The norm(x) is defined as x.real**2 + x.imag**2. abs(x) is the square root of norm(x).phase(...)phase(x) returns the phase angle, also known as argument, of a complex x.polar(...)polar(x) returns the polar coordinate form of a complex x that is in rectangular form.proj(...)proj(x) returns the projection of a complex x on to the Riemann sphere.rect(...)rect(x) returns the polar coordinate form of a complex x that is in rectangular form.sin(...)sin(x) returns the sine of x.sinh(...)sinh(x) returns the hyberbolic sine of x.sqrt(...)sqrt(x) returns the square root of x. If x is integer, rational, or real, then anmpfrwill be returned. If x is complex, then anmpcwill be returned. If context.allow_complex is True, negative values of x will return anmpc.square(...)square(x) returns x * x. The type of the result is based on the types of the arguments.sub(...)sub(x, y) returns x - y. The type of the result is based on the types of the arguments.tan(...)tan(x) returns the tangent of x. x is measured in radians.tanh(...)tanh(x) returns the hyperbolic tangent of x.mpcFormattingThempctype supports the __format__() special method to allow custom output formatting.__format__(...)x.__format__(fmt) 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 formatNOTE:The formatting codes must be specified in the order shown above. >>> import gmpy2 >>> from gmpy2 import mpc >>> a=gmpy2.sqrt(mpc("1+2j")) >>> a mpc('1.272019649514069+0.78615137775742328j') >>> "{0:.4.4Mf}".format(a) '(1.2720 0.7862)' >>> "{0:.4.4f}".format(a) '1.2720+0.7862j' >>> "{0:^20.4.4U}".format(a) ' 1.2721+0.7862j ' >>> "{0:^20.4.4D}".format(a) ' 1.2720+0.7861j ' · genindex · modindex · search

**AUTHOR**

Case Van Horsen

**COPYRIGHT**

2012, 2013, 2014 Case Van Horsen