code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def _format_finite(negative, digits, dot_pos): # strip leading zeros olddigits = digits digits = digits.lstrip('0') dot_pos -= len(olddigits) - len(digits) # value is 0.digits * 10**dot_pos use_exponent = dot_pos <= -4 or dot_pos > len(digits) if use_exponent: exp = dot_pos - 1 if digits else dot_pos dot_pos -= exp # left pad with zeros, insert decimal point, and add exponent if dot_pos <= 0: digits = '0' * (1 - dot_pos) + digits dot_pos += 1 - dot_pos assert 1 <= dot_pos <= len(digits) if dot_pos < len(digits): digits = digits[:dot_pos] + '.' + digits[dot_pos:] if use_exponent: digits += "e{0:+03d}".format(exp) return '-' + digits if negative else digits
Given a (possibly empty) string of digits and an integer dot_pos indicating the position of the decimal point relative to the start of that string, output a formatted numeric string with the same value and same implicit exponent.
def next_up(x, context=None): x = BigFloat._implicit_convert(x) # make sure we don't alter any flags with _saved_flags(): with (context if context is not None else EmptyContext): with RoundTowardPositive: # nan maps to itself if is_nan(x): return +x # round to current context; if value changes, we're done y = +x if y != x: return y # otherwise apply mpfr_nextabove bf = y.copy() mpfr.mpfr_nextabove(bf) # apply + one more time to deal with subnormals return +bf
next_up(x): return the least representable float that's strictly greater than x. This operation is quiet: flags are not affected.
def next_down(x, context=None): x = BigFloat._implicit_convert(x) # make sure we don't alter any flags with _saved_flags(): with (context if context is not None else EmptyContext): with RoundTowardNegative: # nan maps to itself if is_nan(x): return +x # round to current context; if value changes, we're done y = +x if y != x: return y # otherwise apply mpfr_nextabove bf = y.copy() mpfr.mpfr_nextbelow(bf) # apply + one more time to deal with subnormals return +bf
next_down(x): return the greatest representable float that's strictly less than x. This operation is quiet: flags are not affected.
def set_flagstate(flagset): if not flagset <= _all_flags: raise ValueError("unrecognized flags in flagset") for f in flagset: set_flag(f) for f in _all_flags - flagset: clear_flag(f)
Set all flags in ``flagset``, and clear all other flags.
def _set_from_whole_string(rop, s, base, rnd): s = s.strip() ternary, endindex = mpfr.mpfr_strtofr(rop, s, base, rnd) if len(s) != endindex: raise ValueError("not a valid numeric string") return ternary
Helper function for set_str2: accept a string, set rop, and return the appropriate ternary value. Raise ValueError if ``s`` doesn't represent a valid string in the given base.
def set_str2(s, base, context=None): return _apply_function_in_current_context( BigFloat, _set_from_whole_string, (s, base), context, )
Convert the string ``s`` in base ``base`` to a BigFloat instance, rounding according to the current context. Raise ValueError if ``s`` doesn't represent a valid string in the given base.
def pos(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_set, (BigFloat._implicit_convert(x),), context, )
Return ``x``. As usual, the result is rounded to the current context. The ``pos`` function can be useful for rounding an intermediate result, computed with a temporary increase in precision, back to the current context. For example:: >>> from bigfloat import precision >>> pow(3, 20) + 1.234 - pow(3, 20) # inaccurate due to precision loss BigFloat.exact('1.2340002059936523', precision=53) >>> with precision(100): # compute result with extra precision ... x = pow(3, 20) + 1.234 - pow(3, 20) ... >>> x BigFloat.exact('1.2339999999999999857891452847980', precision=100) >>> pos(x) # round back to original precision BigFloat.exact('1.2340000000000000', precision=53)
def add(x, y, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_add, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
Return ``x`` + ``y``.
def sub(x, y, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_sub, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
Return ``x`` - ``y``.
def mul(x, y, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_mul, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
Return ``x`` times ``y``.
def sqr(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_sqr, (BigFloat._implicit_convert(x),), context, )
Return the square of ``x``.
def div(x, y, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_div, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
Return ``x`` divided by ``y``.
def floordiv(x, y, context=None): return _apply_function_in_current_context( BigFloat, mpfr_floordiv, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
Return the floor of ``x`` divided by ``y``. The result is a ``BigFloat`` instance, rounded to the context if necessary. Special cases match those of the ``div`` function.
def mod(x, y, context=None): return _apply_function_in_current_context( BigFloat, mpfr_mod, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
Return the remainder of x divided by y, with sign matching that of y.
def divmod(x, y, context=None): return floordiv(x, y, context=context), mod(x, y, context=context)
Return the pair (floordiv(x, y, context), mod(x, y, context)). Semantics for negative inputs match those of Python's divmod function.
def sqrt(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_sqrt, (BigFloat._implicit_convert(x),), context, )
Return the square root of ``x``. Return -0 if x is -0, to be consistent with the IEEE 754 standard. Return NaN if x is negative.
def rec_sqrt(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_rec_sqrt, (BigFloat._implicit_convert(x),), context, )
Return the reciprocal square root of x. Return +Inf if x is ±0, +0 if x is +Inf, and NaN if x is negative.
def cbrt(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_cbrt, (BigFloat._implicit_convert(x),), context, )
Return the cube root of x. For x negative, return a negative number. The cube root of -0 is defined to be -0.
def root(x, k, context=None): if k < 0: raise ValueError("root function not implemented for negative k") return _apply_function_in_current_context( BigFloat, mpfr.mpfr_root, (BigFloat._implicit_convert(x), k), context, )
Return the kth root of x. For k odd and x negative (including -Inf), return a negative number. For k even and x negative (including -Inf), return NaN. The kth root of -0 is defined to be -0, whatever the parity of k. This function is only implemented for nonnegative k.
def pow(x, y, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_pow, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
Return ``x`` raised to the power ``y``. Special values are handled as described in the ISO C99 and IEEE 754-2008 standards for the pow function. * pow(±0, y) returns plus or minus infinity for y a negative odd integer. * pow(±0, y) returns plus infinity for y negative and not an odd integer. * pow(±0, y) returns plus or minus zero for y a positive odd integer. * pow(±0, y) returns plus zero for y positive and not an odd integer. * pow(-1, ±Inf) returns 1. * pow(+1, y) returns 1 for any y, even a NaN. * pow(x, ±0) returns 1 for any x, even a NaN. * pow(x, y) returns NaN for finite negative x and finite non-integer y. * pow(x, -Inf) returns plus infinity for 0 < abs(x) < 1, and plus zero for abs(x) > 1. * pow(x, +Inf) returns plus zero for 0 < abs(x) < 1, and plus infinity for abs(x) > 1. * pow(-Inf, y) returns minus zero for y a negative odd integer. * pow(-Inf, y) returns plus zero for y negative and not an odd integer. * pow(-Inf, y) returns minus infinity for y a positive odd integer. * pow(-Inf, y) returns plus infinity for y positive and not an odd integer. * pow(+Inf, y) returns plus zero for y negative, and plus infinity for y positive.
def neg(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_neg, (BigFloat._implicit_convert(x),), context, )
Return -x.
def abs(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_abs, (BigFloat._implicit_convert(x),), context, )
Return abs(x).
def dim(x, y, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_dim, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
Return max(x - y, 0). Return x - y if x > y, +0 if x <= y, and NaN if either x or y is NaN.
def cmp(op1, op2): op1 = BigFloat._implicit_convert(op1) op2 = BigFloat._implicit_convert(op2) if is_nan(op1) or is_nan(op2): raise ValueError("Cannot perform comparison with NaN.") return mpfr.mpfr_cmp(op1, op2)
Perform a three-way comparison of op1 and op2. Return a positive value if op1 > op2, zero if op1 = op2, and a negative value if op1 < op2. Both op1 and op2 are considered to their full own precision, which may differ. If one of the operands is NaN, raise ValueError. Note: This function may be useful to distinguish the three possible cases. If you need to distinguish two cases only, it is recommended to use the predicate functions like 'greaterequal'; they behave like the IEEE 754 comparisons, in particular when one or both arguments are NaN.
def cmpabs(op1, op2): op1 = BigFloat._implicit_convert(op1) op2 = BigFloat._implicit_convert(op2) if is_nan(op1) or is_nan(op2): raise ValueError("Cannot perform comparison with NaN.") return mpfr.mpfr_cmpabs(op1, op2)
Compare the absolute values of op1 and op2. Return a positive value if op1 > op2, zero if op1 = op2, and a negative value if op1 < op2. Both op1 and op2 are considered to their full own precision, which may differ. If one of the operands is NaN, raise ValueError. Note: This function may be useful to distinguish the three possible cases. If you need to distinguish two cases only, it is recommended to use the predicate functions like 'greaterequal'; they behave like the IEEE 754 comparisons, in particular when one or both arguments are NaN.
def sgn(x): x = BigFloat._implicit_convert(x) if is_nan(x): raise ValueError("Cannot take sign of a NaN.") return mpfr.mpfr_sgn(x)
Return the sign of x. Return a positive integer if x > 0, 0 if x == 0, and a negative integer if x < 0. Raise ValueError if x is a NaN. This function is equivalent to cmp(x, 0), but more efficient.
def greater(x, y): x = BigFloat._implicit_convert(x) y = BigFloat._implicit_convert(y) return mpfr.mpfr_greater_p(x, y)
Return True if x > y and False otherwise. This function returns False whenever x and/or y is a NaN.
def greaterequal(x, y): x = BigFloat._implicit_convert(x) y = BigFloat._implicit_convert(y) return mpfr.mpfr_greaterequal_p(x, y)
Return True if x >= y and False otherwise. This function returns False whenever x and/or y is a NaN.
def less(x, y): x = BigFloat._implicit_convert(x) y = BigFloat._implicit_convert(y) return mpfr.mpfr_less_p(x, y)
Return True if x < y and False otherwise. This function returns False whenever x and/or y is a NaN.
def lessequal(x, y): x = BigFloat._implicit_convert(x) y = BigFloat._implicit_convert(y) return mpfr.mpfr_lessequal_p(x, y)
Return True if x <= y and False otherwise. This function returns False whenever x and/or y is a NaN.
def equal(x, y): x = BigFloat._implicit_convert(x) y = BigFloat._implicit_convert(y) return mpfr.mpfr_equal_p(x, y)
Return True if x == y and False otherwise. This function returns False whenever x and/or y is a NaN.
def notequal(x, y): x = BigFloat._implicit_convert(x) y = BigFloat._implicit_convert(y) return not mpfr.mpfr_equal_p(x, y)
Return True if x != y and False otherwise. This function returns True whenever x and/or y is a NaN.
def lessgreater(x, y): x = BigFloat._implicit_convert(x) y = BigFloat._implicit_convert(y) return mpfr.mpfr_lessgreater_p(x, y)
Return True if x < y or x > y and False otherwise. This function returns False whenever x and/or y is a NaN.
def unordered(x, y): x = BigFloat._implicit_convert(x) y = BigFloat._implicit_convert(y) return mpfr.mpfr_unordered_p(x, y)
Return True if x or y is a NaN and False otherwise.
def log(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_log, (BigFloat._implicit_convert(x),), context, )
Return the natural logarithm of x.
def log2(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_log2, (BigFloat._implicit_convert(x),), context, )
Return the base-two logarithm of x.
def log10(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_log10, (BigFloat._implicit_convert(x),), context, )
Return the base-ten logarithm of x.
def exp(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_exp, (BigFloat._implicit_convert(x),), context, )
Return the exponential of x.
def exp2(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_exp2, (BigFloat._implicit_convert(x),), context, )
Return two raised to the power x.
def exp10(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_exp10, (BigFloat._implicit_convert(x),), context, )
Return ten raised to the power x.
def cos(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_cos, (BigFloat._implicit_convert(x),), context, )
Return the cosine of ``x``.
def sin(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_sin, (BigFloat._implicit_convert(x),), context, )
Return the sine of ``x``.
def tan(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_tan, (BigFloat._implicit_convert(x),), context, )
Return the tangent of ``x``.
def sec(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_sec, (BigFloat._implicit_convert(x),), context, )
Return the secant of ``x``.
def csc(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_csc, (BigFloat._implicit_convert(x),), context, )
Return the cosecant of ``x``.
def cot(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_cot, (BigFloat._implicit_convert(x),), context, )
Return the cotangent of ``x``.
def acos(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_acos, (BigFloat._implicit_convert(x),), context, )
Return the inverse cosine of ``x``. The mathematically exact result lies in the range [0, π]. However, note that as a result of rounding to the current context, it's possible for the actual value returned to be fractionally larger than π:: >>> from bigfloat import precision >>> with precision(12): ... x = acos(-1) ... >>> print(x) 3.1416 >>> x > const_pi() True
def asin(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_asin, (BigFloat._implicit_convert(x),), context, )
Return the inverse sine of ``x``. The mathematically exact result lies in the range [-π/2, π/2]. However, note that as a result of rounding to the current context, it's possible for the actual value to lie just outside this range.
def atan(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_atan, (BigFloat._implicit_convert(x),), context, )
Return the inverse tangent of ``x``. The mathematically exact result lies in the range [-π/2, π/2]. However, note that as a result of rounding to the current context, it's possible for the actual value to lie just outside this range.
def cosh(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_cosh, (BigFloat._implicit_convert(x),), context, )
Return the hyperbolic cosine of x.
def sinh(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_sinh, (BigFloat._implicit_convert(x),), context, )
Return the hyperbolic sine of x.
def tanh(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_tanh, (BigFloat._implicit_convert(x),), context, )
Return the hyperbolic tangent of x.
def sech(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_sech, (BigFloat._implicit_convert(x),), context, )
Return the hyperbolic secant of x.
def csch(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_csch, (BigFloat._implicit_convert(x),), context, )
Return the hyperbolic cosecant of x.
def coth(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_coth, (BigFloat._implicit_convert(x),), context, )
Return the hyperbolic cotangent of x.
def acosh(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_acosh, (BigFloat._implicit_convert(x),), context, )
Return the inverse hyperbolic cosine of x.
def asinh(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_asinh, (BigFloat._implicit_convert(x),), context, )
Return the inverse hyperbolic sine of x.
def atanh(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_atanh, (BigFloat._implicit_convert(x),), context, )
Return the inverse hyperbolic tangent of x.
def log1p(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_log1p, (BigFloat._implicit_convert(x),), context, )
Return the logarithm of one plus x.
def expm1(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_expm1, (BigFloat._implicit_convert(x),), context, )
Return one less than the exponential of x.
def eint(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_eint, (BigFloat._implicit_convert(x),), context, )
Return the exponential integral of x.
def li2(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_li2, (BigFloat._implicit_convert(x),), context, )
Return the real part of the dilogarithm of x.
def gamma(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_gamma, (BigFloat._implicit_convert(x),), context, )
Return the value of the Gamma function of x.
def lngamma(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_lngamma, (BigFloat._implicit_convert(x),), context, )
Return the value of the logarithm of the Gamma function of x.
def lgamma(x, context=None): return _apply_function_in_current_context( BigFloat, lambda rop, op, rnd: mpfr.mpfr_lgamma(rop, op, rnd)[0], (BigFloat._implicit_convert(x),), context, )
Return the logarithm of the absolute value of the Gamma function at x.
def digamma(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_digamma, (BigFloat._implicit_convert(x),), context, )
Return the value of the digamma (sometimes also called Psi) function on op.
def zeta(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_zeta, (BigFloat._implicit_convert(x),), context, )
Return the value of the Riemann zeta function on x.
def erf(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_erf, (BigFloat._implicit_convert(x),), context, )
Return the value of the error function at x.
def erfc(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_erfc, (BigFloat._implicit_convert(x),), context, )
Return the value of the complementary error function at x.
def j0(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_j0, (BigFloat._implicit_convert(x),), context, )
Return the value of the first kind Bessel function of order 0 at x.
def j1(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_j1, (BigFloat._implicit_convert(x),), context, )
Return the value of the first kind Bessel function of order 1 at x.
def jn(n, x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_jn, (n, BigFloat._implicit_convert(x)), context, )
Return the value of the first kind Bessel function of order ``n`` at ``x``. ``n`` should be a Python integer.
def y0(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_y0, (BigFloat._implicit_convert(x),), context, )
Return the value of the second kind Bessel function of order 0 at x.
def y1(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_y1, (BigFloat._implicit_convert(x),), context, )
Return the value of the second kind Bessel function of order 1 at x.
def yn(n, x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_yn, (n, BigFloat._implicit_convert(x)), context, )
Return the value of the second kind Bessel function of order ``n`` at ``x``. ``n`` should be a Python integer.
def fma(x, y, z, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_fma, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), BigFloat._implicit_convert(z), ), context, )
Return (x * y) + z, with a single rounding according to the current context.
def fms(x, y, z, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_fms, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), BigFloat._implicit_convert(z), ), context, )
Return (x * y) - z, with a single rounding according to the current context.
def agm(x, y, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_agm, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
Return the arithmetic geometric mean of x and y.
def hypot(x, y, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_hypot, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
Return the Euclidean norm of x and y, i.e., the square root of the sum of the squares of x and y.
def ai(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_ai, (BigFloat._implicit_convert(x),), context, )
Return the Airy function of x.
def ceil(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_rint_ceil, (BigFloat._implicit_convert(x),), context, )
Return the next higher or equal integer to x. If the result is not exactly representable, it will be rounded according to the current context. Note that the rounding step means that it's possible for the result to be smaller than ``x``. For example:: >>> x = 2**100 + 1 >>> ceil(2**100 + 1) >= x False One way to be sure of getting a result that's greater than or equal to ``x`` is to use the ``RoundTowardPositive`` rounding mode:: >>> with RoundTowardPositive: ... x = 2**100 + 1 ... ceil(x) >= x ... True Similar comments apply to the :func:`floor`, :func:`round` and :func:`trunc` functions. .. note:: This function corresponds to the MPFR function ``mpfr_rint_ceil``, not to ``mpfr_ceil``.
def floor(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_rint_floor, (BigFloat._implicit_convert(x),), context, )
Return the next lower or equal integer to x. If the result is not exactly representable, it will be rounded according to the current context. Note that it's possible for the result to be larger than ``x``. See the documentation of the :func:`ceil` function for more information. .. note:: This function corresponds to the MPFR function ``mpfr_rint_floor``, not to ``mpfr_floor``.
def round(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_rint_round, (BigFloat._implicit_convert(x),), context, )
Return the nearest integer to x, rounding halfway cases *away from zero*. If the result is not exactly representable, it will be rounded according to the current context. .. note:: This function corresponds to the MPFR function ``mpfr_rint_round``, not to ``mpfr_round``.
def trunc(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_rint_trunc, (BigFloat._implicit_convert(x),), context, )
Return the next integer towards zero. If the result is not exactly representable, it will be rounded according to the current context. .. note:: This function corresponds to the MPFR function ``mpfr_rint_trunc``, not to ``mpfr_trunc``.
def frac(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_frac, (BigFloat._implicit_convert(x),), context, )
Return the fractional part of ``x``. The result has the same sign as ``x``.
def fmod(x, y, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_fmod, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
Return ``x`` reduced modulo ``y``. Returns the value of x - n * y, where n is the integer quotient of x divided by y, rounded toward zero. Special values are handled as described in Section F.9.7.1 of the ISO C99 standard: If x is infinite or y is zero, the result is NaN. If y is infinite and x is finite, the result is x rounded to the current context. If the result is zero, it has the sign of x.
def remainder(x, y, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_remainder, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
Return x reduced modulo y. Returns the value of x - n * y, where n is the integer quotient of x divided by y, rounded to the nearest integer (ties rounded to even). Special values are handled as described in Section F.9.7.1 of the ISO C99 standard: If x is infinite or y is zero, the result is NaN. If y is infinite and x is finite, the result is x (rounded to the current context). If the result is zero, it has the sign of x.
def min(x, y, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_min, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
Return the minimum of x and y. If x and y are both NaN, return NaN. If exactly one of x and y is NaN, return the non-NaN value. If x and y are zeros of different signs, return −0.
def max(x, y, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_max, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
Return the maximum of x and y. If x and y are both NaN, return NaN. If exactly one of x and y is NaN, return the non-NaN value. If x and y are zeros of different signs, return +0.
def copysign(x, y, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_copysign, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
Return a new BigFloat object with the magnitude of x but the sign of y.
def exact(cls, value, precision=None): # figure out precision to use if isinstance(value, six.string_types): if precision is None: raise TypeError("precision must be supplied when " "converting from a string") else: if precision is not None: raise TypeError("precision argument should not be " "specified except when converting " "from a string") if isinstance(value, float): precision = _builtin_max(DBL_PRECISION, PRECISION_MIN) elif isinstance(value, six.integer_types): precision = _builtin_max(_bit_length(value), PRECISION_MIN) elif isinstance(value, BigFloat): precision = value.precision else: raise TypeError("Can't convert argument %s of type %s " "to BigFloat" % (value, type(value))) # Use unlimited exponents, with given precision. with _saved_flags(): set_flagstate(set()) # clear all flags context = ( WideExponentContext + Context(precision=precision) + RoundTiesToEven ) with context: result = BigFloat(value) if test_flag(Overflow): raise ValueError("value too large to represent as a BigFloat") if test_flag(Underflow): raise ValueError("value too small to represent as a BigFloat") if test_flag(Inexact) and not isinstance(value, six.string_types): # since this is supposed to be an exact conversion, the # inexact flag should never be set except when converting # from a string. assert False, ("Inexact conversion in BigFloat.exact. " "This shouldn't ever happen. Please report.") return result
Convert an integer, float or BigFloat with no loss of precision. Also convert a string with given precision. This constructor makes no use of the current context.
def _significand(self): m = self.copy() if self and is_finite(self): mpfr.mpfr_set_exp(m, 0) mpfr.mpfr_setsign(m, m, False, ROUND_TIES_TO_EVEN) return m
Return the significand of self, as a BigFloat. If self is a nonzero finite number, return a BigFloat m with the same precision as self, such that 0.5 <= m < 1. and self = +/-m * 2**e for some exponent e. If self is zero, infinity or nan, return a copy of self with the sign set to 0.
def _exponent(self): if self and is_finite(self): return mpfr.mpfr_get_exp(self) if not self: return '0' elif is_inf(self): return 'inf' elif is_nan(self): return 'nan' else: assert False, "shouldn't ever get here"
Return the exponent of self, as an integer. The exponent is defined as the unique integer k such that 2**(k-1) <= abs(self) < 2**k. If self is not finite and nonzero, return a string: one of '0', 'inf' or 'nan'.
def copy(self): result = mpfr.Mpfr_t.__new__(BigFloat) mpfr.mpfr_init2(result, self.precision) mpfr.mpfr_set(result, self, ROUND_TIES_TO_EVEN) return result
Return a copy of self. This function does not make use of the context. The result has the same precision as the original.
def copy_neg(self): result = mpfr.Mpfr_t.__new__(BigFloat) mpfr.mpfr_init2(result, self.precision) new_sign = not self._sign() mpfr.mpfr_setsign(result, self, new_sign, ROUND_TIES_TO_EVEN) return result
Return a copy of self with the opposite sign bit. Unlike -self, this does not make use of the context: the result has the same precision as the original.
def copy_abs(self): result = mpfr.Mpfr_t.__new__(BigFloat) mpfr.mpfr_init2(result, self.precision) mpfr.mpfr_setsign(result, self, False, ROUND_TIES_TO_EVEN) return result
Return a copy of self with the sign bit unset. Unlike abs(self), this does not make use of the context: the result has the same precision as the original.
def hex(self): sign = '-' if self._sign() else '' e = self._exponent() if isinstance(e, six.string_types): return sign + e m = self._significand() _, digits, _ = _mpfr_get_str2( 16, 0, m, ROUND_TIES_TO_EVEN, ) # only print the number of digits that are actually necessary n = 1 + (self.precision - 1) // 4 assert all(c == '0' for c in digits[n:]) result = '%s0x0.%sp%+d' % (sign, digits[:n], e) return result
Return a hexadecimal representation of a BigFloat.
def as_integer_ratio(self): if not is_finite(self): raise ValueError("Can't express infinity or nan as " "an integer ratio") elif not self: return 0, 1 # convert to a hex string, and from there to a fraction negative, digits, e = _mpfr_get_str2( 16, 0, self, ROUND_TIES_TO_EVEN, ) digits = digits.rstrip('0') # find number of trailing 0 bits in last hex digit v = int(digits[-1], 16) v &= -v n, d = int(digits, 16) // v, 1 e = (e - len(digits) << 2) + {1: 0, 2: 1, 4: 2, 8: 3}[v] # abs(number) now has value n * 2**e, and n is odd if e >= 0: n <<= e else: d <<= -e return (-n if negative else n), d
Return pair n, d of integers such that the value of self is exactly equal to n/d, n and d are relatively prime, and d >= 1.
def _format_to_floating_precision(self, precision): if precision <= 0: raise ValueError("precision argument should be at least 1") sign, digits, exp = _mpfr_get_str2( 10, precision, self, ROUND_TIES_TO_EVEN, ) return sign, digits, exp - len(digits)
Format a nonzero finite BigFloat instance to a given number of significant digits. Returns a triple (negative, digits, exp) where: - negative is a boolean, True for a negative number, else False - digits is a string giving the digits of the output - exp represents the exponent of the output, The normalization of the exponent is such that <digits>E<exp> represents the decimal approximation to self. Rounding is always round-to-nearest.
def _implicit_convert(cls, arg): # ints, long and floats mix freely with BigFloats, and are # converted exactly. if isinstance(arg, six.integer_types) or isinstance(arg, float): return cls.exact(arg) elif isinstance(arg, BigFloat): return arg else: raise TypeError("Unable to convert argument %s of type %s " "to BigFloat" % (arg, type(arg)))
Implicit conversion used for binary operations, comparisons, functions, etc. Return value should be an instance of BigFloat.