Contexts

context() creates a new context with all options set to default. set_context() will set the active context. get_context() will return a reference to the active context. Note that contexts are mutable: modifying the reference returned by get_context() will modify the active context until a new context is enabled with set_context(). The copy() method of a context will return a copy of the context.

Context Type

class gmpy2.context

GMPY2 Context Object

abs(x, /) mpz | mpq | mpfr

Return abs(x), the context is applied to the result.

acos(x, /) mpfr | mpc

Return inverse cosine of x; result in radians.

acosh(x, /) mpfr | mpc

Return inverse hyperbolic cosine of x.

add(x, y, /) mpz | mpq | mpfr | mpc

Return x + y.

agm(x, y, /) mpfr

Return arithmetic-geometric mean of x and y.

ai(x, /) mpfr

Return Airy function of x.

asin(x, /) mpfr | mpc

Return inverse sine of x; result in radians.

asinh(x, /) mpfr | mpc

Return inverse hyperbolic sine of x.

atan(x, /) mpfr | mpc

Return inverse tangent of x; result in radians.

atan2(y, x, /) mpfr

Return arc-tangent of (y/x); result in radians.

atanh(x, /) mpfr | mpc

Return inverse hyperbolic tanget of x.

cbrt(x, /) mpfr

Return the cube root of x.

ceil(x, /) mpfr

Return an mpfr that is the smallest integer >= x.

check_range(x, /) mpfr

Return a new mpfr with exponent that lies within the range of emin and emax specified by context.

clear_flags() None

Clear all MPFR exception flags.

const_catalan() mpfr

Return the catalan constant using the context’s precision.

const_euler() mpfr

Return the euler constant using the context’s precision.

const_log2() mpfr

Return the log2 constant using the context’s precision.

const_pi() mpfr

Return the constant pi using the context’s precision.

copy() context

Return a copy of a context.

cos(x, /) mpfr | mpc

Return cosine of x; x in radians.

cosh(x, /) mpfr | mpc

Return hyperbolic cosine of x.

cot(x, /) mpfr

Return cotangent of x; x in radians.

coth(x, /) mpfr

Return hyperbolic cotangent of x.

csc(x, /) mpfr

Return cosecant of x; x in radians.

csch(x, /) mpfr

Return hyperbolic cosecant of x.

degrees(x, /) mpfr

Convert angle x from radians to degrees. Note: In rare cases the result may not be correctly rounded.

digamma(x, /) mpfr

Return digamma of x.

div(x, y, /) mpz | mpq | mpfr | mpc

Return x / y; uses true division.

div_2exp(x, n, /) mpfr | mpc

Return mpfr or mpc divided by 2**n.

divmod(x, y, /) tuple[mpz | mpfr, mpz | mpq | mpfr]

Return divmod(x, y).

Note: overflow, underflow, and inexact exceptions are not supported for mpfr arguments.

eint(x, /) mpfr

Return exponential integral of x.

erf(x, /) mpfr

Return error function of x.

erfc(x, /) mpfr

Return complementary error function of x.

exp(x, /) mpfr | mpc

Return the exponential of x.

exp10(x, /) mpfr

Return 10**x.

exp2(x, /) mpfr

Return 2**x.

expm1(x, /) mpfr

Return exp(x) - 1.

factorial(n, /) mpfr

Return the floating-point approximation to the factorial of n.

See fac() to get the exact integer result.

floor(x, /) mpfr

Return an mpfr that is the largest integer <= x.

floor_div(x, y, /) mpz | mpfr

Return x // y; uses floor division.

fma(x, y, z, /) mpz | mpq | mpfr | mpc

Return correctly rounded result of (x * y) + z.

fmma(x, y, z, t, /) mpfr

Return correctly rounded result of (x * y) + (z * t).

fmms(x, y, z, t, /) mpfr

Return correctly rounded result of (x * y) - (z * t).

fmod(x, y, /) mpfr

Return x - n*y where n is the integer quotient of x/y, rounded to 0.

fms(x, y, z, /) mpz | mpq | mpfr | mpc

Return correctly rounded result of (x * y) - z.

frac(x, /) mpfr

Return fractional part of x.

frexp(x, /) tuple[int, mpfr]

Return a tuple containing the exponent and mantissa of x.

fsum(iterable, /) mpfr

Return an accurate sum of the values in the iterable.

gamma(x, /) mpfr

Return gamma of x.

gamma_inc(a, x, /) mpfr

Return (upper) incomplete gamma of a and x.

hypot(x, y, /) mpfr

Return square root of (x**2 + y**2).

is_finite(x, /) bool

Return True if x is an actual number (i.e. non NaN or Infinity). If x is an mpc, return True if both x.real and x.imag are finite.

is_infinite(x, /) bool

Return True if x is +Infinity or -Infinity. If x is an mpc, return True if either x.real or x.imag is infinite. Otherwise return False.

is_integer(x, /) bool

Return True if x is an integer; False otherwise.

is_nan(x, /) bool

Return True if x is NaN (Not-A-Number) else False.

is_regular(x, /) bool

Return True if x is not zero, NaN, or Infinity; False otherwise.

is_signed(x, /) bool

Return True if the sign bit of x is set.

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.

j0(x, /) mpfr

Return first kind Bessel function of order 0 of x.

j1(x, /) mpfr

Return first kind Bessel function of order 1 of x.

jn(n, x, /) mpfr

Return the first kind Bessel function of order n of x. Note: the order of the arguments changed in gmpy2 2.2.0a2

lgamma(x, /) tuple[mpfr, int]

Return a tuple containing the logarithm of the absolute value of gamma(x) and the sign of gamma(x)

li2(x, /) mpfr

Return real part of dilogarithm of x.

lngamma(x, /) mpfr

Return natural logarithm of gamma(x).

log(x, /) mpfr | mpc

Return the natural logarithm of x.

log10(x, /) mpfr | mpc

Return the base-10 logarithm of x.

log1p(x, /) mpfr

Return natural logarithm of (1+x).

log2(x, /) mpfr

Return base-2 logarithm of x.

maxnum(x, y, /) mpfr

Return the maximum number of x and y. If x and y are not mpfr, they are converted to mpfr. The result is rounded to match the specified context. If only one of x or y is a number, then that number is returned.

minnum(x, y, /) mpfr

Return the minimum number of x and y. If x and y are not mpfr, they are converted to mpfr. The result is rounded to match the specified context. If only one of x or y is a number, then that number is returned.

minus(x, /) mpz | mpq | mpfr | mpc

Return -x. The context is applied to the result.

mod(x, y, /) mpz | mpq | mpfr

Return mod(x, y). Note: overflow, underflow, and inexact exceptions are not supported for mpfr arguments.

modf(x, /) tuple[mpfr, mpfr]

Return a tuple containing the integer and fractional portions of x.

mul(x, y, /) mpz | mpq | mpfr | mpc

Return x * y.

mul_2exp(x, n, /) mpfr | mpc

Return mpfr or mpc multiplied by 2**n.

next_above(x, /) mpfr

Return the next mpfr from x toward +Infinity.

next_below(x, /) mpfr

Return the next mpfr from x toward -Infinity.

next_toward(x, y, /) mpfr

Return the next mpfr from x in the direction of y. The result has the same precision as x.

norm(x, /) mpfr

Return the norm of a complex x. The norm(x) is defined as x.real**2 + x.imag**2. abs(x) is the square root of norm(x).

phase(x, /) mpfr

Return the phase angle, also known as argument, of a complex x.

plus(x, /) mpz | mpq | mpfr | mpc

Return +x, the context is applied to the result.

polar(x, /) tuple[mpfr, mpfr]

Return the polar coordinate form of a complex x that is in rectangular form.

pow(x, y, /) mpz | mpq | mpfr | mpc

Return x ** y.

proj(x, /) mpc

Returns the projection of a complex x on to the Riemann sphere.

radians(x, /) mpfr

Convert angle x from degrees to radians. Note: In rare cases the result may not be correctly rounded.

rec_sqrt(x, /) mpfr

Return the reciprocal of the square root of x.

rect(r, phi, /) mpc

Return the rectangular coordinate form of a complex number that is given in polar form.

reldiff(x, y, /) mpfr

Return the relative difference between x and y. Result is equal to abs(x-y)/x.

remainder(x, y, /) mpfr

Return x - n*y where n is the integer quotient of x/y, rounded to the nearest integer and ties rounded to even.

remquo(x, y, /) tuple[mpfr, int]

Return a tuple containing the remainder(x,y) and the low bits of the quotient.

rint(x, /) mpfr

Return x rounded to the nearest integer using the context rounding mode.

rint_ceil(x, /) mpfr

Return x rounded to the nearest integer by first rounding to the next higher or equal integer and then, if needed, using the context rounding mode.

rint_floor(x, /) mpfr

Return x rounded to the nearest integer by first rounding to the next lower or equal integer and then, if needed, using the context rounding mode.

rint_round(x, /) mpfr

Return x rounded to the nearest integer by first rounding to the nearest integer (ties away from 0) and then, if needed, using the context rounding mode.

rint_trunc(x, /) mpfr

Return x rounded to the nearest integer by first rounding towards zero and then, if needed, using the context rounding mode.

root(x, n, /) mpfr

Return n-th root of x. The result always an mpfr. Note: not IEEE 754-2008 compliant; result differs when x = -0 and n is even. See context.rootn().

root_of_unity(n, k, /) mpc

Return the n-th root of mpc(1) raised to the k-th power..

rootn(x, n, /) mpfr

Return n-th root of x. The result always an mpfr. Note: this is IEEE 754-2008 compliant version of context.root().

round2(x, n=0, /) mpfr

Return x rounded to n bits. Uses default precision if n is not specified. See context.round_away() to access the mpfr_round() function of the MPFR.

round_away(x, /) mpfr

Return an mpfr that is x rounded to the nearest integer, with ties rounded away from 0.

sec(x, /) mpfr

Return secant of x; x in radians.

sech(x, /) mpfr

Return hyperbolic secant of x.

sin(x, /) mpfr | mpc

Return sine of x; x in radians.

sin_cos(x, /) tuple[mpfr | mpc, mpfr | mpc]

Return a tuple containing the sine and cosine of x; x in radians.

sinh(x, /) mpfr | mpc

Return hyperbolic sine of x.

sinh_cosh(x, /) tuple[mpfr, mpfr]

Return a tuple containing the hyperbolic sine and cosine of x.

sqrt(x, /) mpfr | mpc

Return the square root of x.

square(x, /) mpz | mpq | mpfr | mpc

Return x * x.

sub(x, y, /) mpz | mpq | mpfr | mpc

Return x - y.

tan(x, /) mpfr | mpc

Return tangent of x; x in radians.

tanh(x, /) mpfr | mpc

Return hyperbolic tangent of x.

trunc(x, /) mpfr

Return an mpfr that is x truncated towards 0. Same as x.floor() if x>=0 or x.ceil() if x<0.

y0(x, /) mpfr

Return second kind Bessel function of order 0 of x.

y1(x, /) mpfr

Return second kind Bessel function of order 1 of x.

yn(n, x, /) mpfr

Return the second kind Bessel function of order n of x. Note: the order of the arguments changed in gmpy2 2.2.0a2

zeta(x, /) mpfr

Return Riemann zeta of x.

allow_complex

This attribute controls whether or not an mpc result can be returned if an mpfr result would normally not be possible.

allow_release_gil

If set to True, many mpz and mpq computations will release the GIL.

This is considered an experimental feature.

divzero

This flag is not user controllable. It is automatically set if a division by zero occurred and NaN result was returned.

emax

This attribute controls the maximum allowed exponent of an mpfr result. The maximum exponent is platform dependent and can be retrieved with get_emax_max().

emin

This attribute controls the minimum allowed exponent of an mpfr result. The minimum exponent is platform dependent and can be retrieved with get_emin_min().

erange

This flag is not user controllable. It is automatically set if an erange error occurred.

imag_prec

This attribute controls the precision of the imaginary part of an mpc result. If the value is Default, then the value of real_prec is used.

imag_round

This attribute controls the rounding mode for the imaginary part of an mpc result. If the value is Default, then the value of the real_round attribute is used. Note: RoundAwayZero is not a valid rounding mode for mpc.

inexact

This flag is not user controllable. It is automatically set if an inexact result is returned.

invalid

This flag is not user controllable. It is automatically set if an invalid (Not-A-Number) result is returned.

overflow

This flag is not user controllable. It is automatically set if a result overflowed to +/-Infinity and trap_overflow is False.

precision

This attribute controls the precision of an mpfr result. The precision is specified in bits, not decimal digits. The maximum precision that can be specified is platform dependent and can be retrieved with get_max_precision().

Note: Specifying a value for precision that is too close to the maximum precision will cause the MPFR library to fail.

rational_division

If set to True, mpz / mpz will return an mpq instead of an mpfr.

real_prec

This attribute controls the precision of the real part of an mpc result. If the value is Default, then the value of the precision attribute is used.

real_round

This attribute controls the rounding mode for the real part of an mpc result. If the value is Default, then the value of the round attribute is used. Note: RoundAwayZero is not a valid rounding mode for mpc.

round

There are five rounding modes available to mpfr type:

  • RoundAwayZero - The result is rounded away from 0.0.

  • RoundDown - The result is rounded towards -Infinity.

  • RoundToNearest - Round to the nearest value; ties are rounded to an even value.

  • RoundToZero - The result is rounded towards 0.0.

  • RoundUp - The result is rounded towards +Infinity.

subnormalize

The usual IEEE-754 floating point representation supports gradual underflow when the minimum exponent is reached. The MFPR library does not enable gradual underflow by default but it can be enabled to precisely mimic the results of IEEE-754 floating point operations.

trap_divzero

This attribute controls whether or not a DivisionByZeroError exception is raised if division by 0 occurs. The DivisionByZeroError is a sub-class of Python’s ZeroDivisionError.

trap_erange

This attribute controls whether or not a RangeError exception is raised when certain operations are performed on NaN and/or Infinity values. Setting trap_erange to True can be used to raise an exception if comparisons are attempted with a NaN.

trap_inexact

This attribute controls whether or not an InexactResultError exception is raised if an inexact result is returned. To check if the result is greater or less than the exact result, check the rc attribute of the mpfr result.

trap_invalid

This attribute controls whether or not an InvalidOperationError exception is raised if a numerical result is not defined. A special NaN (Not-A-Number) value will be returned if an exception is not raised. The InvalidOperationError is a sub-class of Python’s ValueError.

For example, gmpy2.sqrt(-2) will normally return mpfr(‘nan’). However, if allow_complex is set to True, then an mpc result will be returned.

trap_overflow

If set to False, a result that is larger than the largest possible mpfr given the current exponent range will be replaced by +/-Infinity. If set to True, an OverflowResultError exception is raised.

trap_underflow

If set to False, a result that is smaller than the smallest possible mpfr given the current exponent range will be replaced by +/-0.0. If set to True, an UnderflowResultError exception is raised.

underflow

This flag is not user controllable. It is automatically set if a result underflowed to +/-0.0 and trap_underflow is False.

Context Functions

gmpy2.get_context() context

Return a reference to the current context.

gmpy2.ieee(size, /, subnormalize=True) context

Return a new context corresponding to a standard IEEE floating point format. The supported sizes are 16, 32, 64, 128, and multiples of 32 greater than 128.

gmpy2.local_context(**kwargs) context
gmpy2.local_context(context, /, **kwargs) context

Create a context manager object that will restore the current context when the ‘with …’ block terminates. The temporary context for the ‘with …’ block is based on the current context if no context is specified. Keyword arguments are supported and will modify the temporary new context.

gmpy2.set_context(context, /) None

Activate a context object controlling gmpy2 arithmetic.

Contexts and the with statement

Contexts can also be used in conjunction with Python’s with statement to temporarily change the context settings for a block of code and then restore the original settings when the block of code exits.

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 original active context is restored when the block completes.

In the following example, the current context is saved by 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.

>>> import gmpy2
>>> print(gmpy2.sqrt(2))
1.4142135623730951
>>> 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
>>> print(gmpy2.sqrt(2))
1.4142135623730951

Contexts that implement the standard single, double, and quadruple precision floating point types can be created using ieee.