MCPcopy Create free account
hub / github.com/RT-Thread/env-windows / sqrt

Method sqrt

tools/python-3.11.9-amd64/Lib/_pydecimal.py:2727–2824  ·  view source on GitHub ↗

Return the square root of self.

(self, context=None)

Source from the content-addressed store, hash-verified

2725 to_integral = to_integral_value
2726
2727 def sqrt(self, context=None):
2728 """Return the square root of self."""
2729 if context is None:
2730 context = getcontext()
2731
2732 if self._is_special:
2733 ans = self._check_nans(context=context)
2734 if ans:
2735 return ans
2736
2737 if self._isinfinity() and self._sign == 0:
2738 return Decimal(self)
2739
2740 if not self:
2741 # exponent = self._exp // 2. sqrt(-0) = -0
2742 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
2743 return ans._fix(context)
2744
2745 if self._sign == 1:
2746 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2747
2748 # At this point self represents a positive number. Let p be
2749 # the desired precision and express self in the form c*100**e
2750 # with c a positive real number and e an integer, c and e
2751 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2752 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2753 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2754 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2755 # the closest integer to sqrt(c) with the even integer chosen
2756 # in the case of a tie.
2757 #
2758 # To ensure correct rounding in all cases, we use the
2759 # following trick: we compute the square root to an extra
2760 # place (precision p+1 instead of precision p), rounding down.
2761 # Then, if the result is inexact and its last digit is 0 or 5,
2762 # we increase the last digit to 1 or 6 respectively; if it's
2763 # exact we leave the last digit alone. Now the final round to
2764 # p places (or fewer in the case of underflow) will round
2765 # correctly and raise the appropriate flags.
2766
2767 # use an extra digit of precision
2768 prec = context.prec+1
2769
2770 # write argument in the form c*100**e where e = self._exp//2
2771 # is the 'ideal' exponent, to be used if the square root is
2772 # exactly representable. l is the number of 'digits' of c in
2773 # base 100, so that 100**(l-1) <= c < 100**l.
2774 op = _WorkRep(self)
2775 e = op.exp >> 1
2776 if op.exp & 1:
2777 c = op.int * 10
2778 l = (len(self._int) >> 1) + 1
2779 else:
2780 c = op.int
2781 l = len(self._int)+1 >> 1
2782
2783 # rescale so that c has exactly prec base 100 'digits'
2784 shift = prec-l

Callers 3

_decimal_sqrt_of_fracFunction · 0.45
sqrtMethod · 0.45
test_sqrtMethod · 0.45

Calls 11

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

Tested by 1

test_sqrtMethod · 0.36