Quantize self so its exponent is the same as that of exp. Similar to self._rescale(exp._exp) but with error checking.
(self, exp, rounding=None, context=None)
| 2499 | return _dec_from_triple(dup._sign, dup._int[:end], exp) |
| 2500 | |
| 2501 | def quantize(self, exp, rounding=None, context=None): |
| 2502 | """Quantize self so its exponent is the same as that of exp. |
| 2503 | |
| 2504 | Similar to self._rescale(exp._exp) but with error checking. |
| 2505 | """ |
| 2506 | exp = _convert_other(exp, raiseit=True) |
| 2507 | |
| 2508 | if context is None: |
| 2509 | context = getcontext() |
| 2510 | if rounding is None: |
| 2511 | rounding = context.rounding |
| 2512 | |
| 2513 | if self._is_special or exp._is_special: |
| 2514 | ans = self._check_nans(exp, context) |
| 2515 | if ans: |
| 2516 | return ans |
| 2517 | |
| 2518 | if exp._isinfinity() or self._isinfinity(): |
| 2519 | if exp._isinfinity() and self._isinfinity(): |
| 2520 | return Decimal(self) # if both are inf, it is OK |
| 2521 | return context._raise_error(InvalidOperation, |
| 2522 | 'quantize with one INF') |
| 2523 | |
| 2524 | # exp._exp should be between Etiny and Emax |
| 2525 | if not (context.Etiny() <= exp._exp <= context.Emax): |
| 2526 | return context._raise_error(InvalidOperation, |
| 2527 | 'target exponent out of bounds in quantize') |
| 2528 | |
| 2529 | if not self: |
| 2530 | ans = _dec_from_triple(self._sign, '0', exp._exp) |
| 2531 | return ans._fix(context) |
| 2532 | |
| 2533 | self_adjusted = self.adjusted() |
| 2534 | if self_adjusted > context.Emax: |
| 2535 | return context._raise_error(InvalidOperation, |
| 2536 | 'exponent of quantize result too large for current context') |
| 2537 | if self_adjusted - exp._exp + 1 > context.prec: |
| 2538 | return context._raise_error(InvalidOperation, |
| 2539 | 'quantize result has too many digits for current context') |
| 2540 | |
| 2541 | ans = self._rescale(exp._exp, rounding) |
| 2542 | if ans.adjusted() > context.Emax: |
| 2543 | return context._raise_error(InvalidOperation, |
| 2544 | 'exponent of quantize result too large for current context') |
| 2545 | if len(ans._int) > context.prec: |
| 2546 | return context._raise_error(InvalidOperation, |
| 2547 | 'quantize result has too many digits for current context') |
| 2548 | |
| 2549 | # raise appropriate flags |
| 2550 | if ans and ans.adjusted() < context.Emin: |
| 2551 | context._raise_error(Subnormal) |
| 2552 | if ans._exp > self._exp: |
| 2553 | if ans != self: |
| 2554 | context._raise_error(Inexact) |
| 2555 | context._raise_error(Rounded) |
| 2556 | |
| 2557 | # call to fix takes care of any necessary folddown, and |
| 2558 | # signals Clamped if necessary |