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