MCPcopy Index your code
hub / github.com/RustPython/RustPython / sqrt

Method sqrt

Lib/_pydecimal.py:2679–2776  ·  view source on GitHub ↗

Return the square root of self.

(self, context=None)

Source from the content-addressed store, hash-verified

2677 to_integral = to_integral_value
2678
2679 def sqrt(self, context=None):
2680 """Return the square root of self."""
2681 if context is None:
2682 context = getcontext()
2683
2684 if self._is_special:
2685 ans = self._check_nans(context=context)
2686 if ans:
2687 return ans
2688
2689 if self._isinfinity() and self._sign == 0:
2690 return Decimal(self)
2691
2692 if not self:
2693 # exponent = self._exp // 2. sqrt(-0) = -0
2694 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
2695 return ans._fix(context)
2696
2697 if self._sign == 1:
2698 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2699
2700 # At this point self represents a positive number. Let p be
2701 # the desired precision and express self in the form c*100**e
2702 # with c a positive real number and e an integer, c and e
2703 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2704 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2705 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2706 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2707 # the closest integer to sqrt(c) with the even integer chosen
2708 # in the case of a tie.
2709 #
2710 # To ensure correct rounding in all cases, we use the
2711 # following trick: we compute the square root to an extra
2712 # place (precision p+1 instead of precision p), rounding down.
2713 # Then, if the result is inexact and its last digit is 0 or 5,
2714 # we increase the last digit to 1 or 6 respectively; if it's
2715 # exact we leave the last digit alone. Now the final round to
2716 # p places (or fewer in the case of underflow) will round
2717 # correctly and raise the appropriate flags.
2718
2719 # use an extra digit of precision
2720 prec = context.prec+1
2721
2722 # write argument in the form c*100**e where e = self._exp//2
2723 # is the 'ideal' exponent, to be used if the square root is
2724 # exactly representable. l is the number of 'digits' of c in
2725 # base 100, so that 100**(l-1) <= c < 100**l.
2726 op = _WorkRep(self)
2727 e = op.exp >> 1
2728 if op.exp & 1:
2729 c = op.int * 10
2730 l = (len(self._int) >> 1) + 1
2731 else:
2732 c = op.int
2733 l = len(self._int)+1 >> 1
2734
2735 # rescale so that c has exactly prec base 100 'digits'
2736 shift = prec-l

Callers 4

test_none_argsMethod · 0.95
_decimal_sqrt_of_fracFunction · 0.45
sqrtMethod · 0.45
normal_dist_inv_cdfFunction · 0.45

Calls 13

_check_nansMethod · 0.95
_isinfinityMethod · 0.95
getcontextFunction · 0.85
DecimalClass · 0.85
_dec_from_tripleFunction · 0.85
_WorkRepClass · 0.85
lenFunction · 0.85
strFunction · 0.85
_fixMethod · 0.80
_raise_errorMethod · 0.80
_shallow_copyMethod · 0.80
_set_roundingMethod · 0.80

Tested by 1

test_none_argsMethod · 0.76