Contexts
A context
type is used to control the behavior
of mpfr
and mpc
arithmetic. 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.
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.
The following example just modifies the precision. The remaining options will be discussed later.
>>> import gmpy2
>>> from gmpy2 import mpfr
>>> 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,
allow_complex=False,
rational_division=False,
allow_release_gil=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)
>>> gmpy2.set_context(gmpy2.context())
Context Type
- class gmpy2.context
GMPY2 Context Object
- check_range(x, /) mpfr
Return a new
mpfr
with exponent that lies within the range of emin and emax specified by context.
- degrees(x, /) mpfr
Convert angle x from radians to degrees. Note: In rare cases the result may not be correctly rounded.
- 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.
- factorial(n, /) mpfr
Return the floating-point approximation to the factorial of n.
See
fac()
to get the exact integer result.
- is_finite(x, /) bool
Return
True
if x is an actual number (i.e. non NaN or Infinity). If x is anmpc
, returnTrue
if both x.real and x.imag are finite.
- is_infinite(x, /) bool
Return
True
if x is +Infinity or -Infinity. If x is anmpc
, returnTrue
if either x.real or x.imag is infinite. Otherwise returnFalse
.
- is_zero(x, /) bool
Return
True
if x is equal to 0. If x is anmpc
, returnTrue
if both x.real and x.imag are equal to 0.
- lgamma(x, /) tuple[mpfr, int]
Return a
tuple
containing the logarithm of the absolute value of gamma(x) and the sign of gamma(x)
- maxnum(x, y, /) mpfr
Return the maximum number of x and y. If x and y are not
mpfr
, they are converted tompfr
. 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 tompfr
. The result is rounded to match the specified context. If only one of x or y is a number, then that number is returned.
- mod(x, y, /) mpz | mpq | mpfr
Return mod(x, y). Note: overflow, underflow, and inexact exceptions are not supported for
mpfr
arguments.
- 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).
- polar(x, /) tuple[mpfr, mpfr]
Return the polar coordinate form of a complex x that is in rectangular form.
- radians(x, /) mpfr
Convert angle x from degrees to radians. Note: In rare cases the result may not be correctly rounded.
- rect(r, phi, /) mpc
Return the rectangular coordinate form of a complex number that is given in polar form.
- 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_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. Seecontext.rootn()
.
- rootn(x, n, /) mpfr
Return n-th root of x. The result always an
mpfr
. Note: this is IEEE 754-2008 compliant version ofcontext.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.
- sin_cos(x, /) tuple[mpfr | mpc, mpfr | mpc]
Return a tuple containing the sine and cosine of x; x in radians.
- 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.
- allow_complex
This attribute controls whether or not an
mpc
result can be returned if anmpfr
result would normally not be possible.
- allow_release_gil
If set to
True
, manympz
andmpq
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 withget_emax_max()
.
- emin
This attribute controls the minimum allowed exponent of an
mpfr
result. The minimum exponent is platform dependent and can be retrieved withget_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 ofreal_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 thereal_round
attribute is used. Note: RoundAwayZero is not a valid rounding mode formpc
.
- 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
isFalse
.
- 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 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_prec
This attribute controls the precision of the real part of an
mpc
result. If the value is Default, then the value of theprecision
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 formpc
.
- 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. TheDivisionByZeroError
is a sub-class of Python’sZeroDivisionError
.
- trap_erange
This attribute controls whether or not a
RangeError
exception is raised when certain operations are performed on NaN and/or Infinity values. Settingtrap_erange
toTrue
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 thempfr
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. TheInvalidOperationError
is a sub-class of Python’sValueError
.For example, gmpy2.sqrt(-2) will normally return mpfr(‘nan’). However, if
allow_complex
is set toTrue
, then anmpc
result will be returned.
- trap_overflow
If set to
False
, a result that is larger than the largest possiblempfr
given the current exponent range will be replaced by +/-Infinity. If set toTrue
, anOverflowResultError
exception is raised.
- trap_underflow
If set to
False
, a result that is smaller than the smallest possiblempfr
given the current exponent range will be replaced by +/-0.0. If set toTrue
, anUnderflowResultError
exception is raised.
- underflow
This flag is not user controllable. It is automatically set if a result underflowed to +/-0.0 and
trap_underflow
isFalse
.
Context Functions
- 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.
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.
>>> 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
.