| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1 | # Copyright (c) 2004 Python Software Foundation. | 
 | 2 | # All rights reserved. | 
 | 3 |  | 
 | 4 | # Written by Eric Price <eprice at tjhsst.edu> | 
 | 5 | #    and Facundo Batista <facundo at taniquetil.com.ar> | 
 | 6 | #    and Raymond Hettinger <python at rcn.com> | 
| Fred Drake | 1f34eb1 | 2004-07-01 14:28:36 +0000 | [diff] [blame] | 7 | #    and Aahz <aahz at pobox.com> | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 8 | #    and Tim Peters | 
 | 9 |  | 
| Raymond Hettinger | 27dbcf2 | 2004-08-19 22:39:55 +0000 | [diff] [blame] | 10 | # This module is currently Py2.3 compatible and should be kept that way | 
 | 11 | # unless a major compelling advantage arises.  IOW, 2.3 compatibility is | 
 | 12 | # strongly preferred, but not guaranteed. | 
 | 13 |  | 
 | 14 | # Also, this module should be kept in sync with the latest updates of | 
 | 15 | # the IBM specification as it evolves.  Those updates will be treated | 
 | 16 | # as bug fixes (deviation from the spec is a compatibility, usability | 
 | 17 | # bug) and will be backported.  At this point the spec is stabilizing | 
 | 18 | # and the updates are becoming fewer, smaller, and less significant. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 19 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 20 | """ | 
 | 21 | This is a Py2.3 implementation of decimal floating point arithmetic based on | 
 | 22 | the General Decimal Arithmetic Specification: | 
 | 23 |  | 
 | 24 |     www2.hursley.ibm.com/decimal/decarith.html | 
 | 25 |  | 
| Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 26 | and IEEE standard 854-1987: | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 27 |  | 
 | 28 |     www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html | 
 | 29 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 30 | Decimal floating point has finite precision with arbitrarily large bounds. | 
 | 31 |  | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 32 | The purpose of this module is to support arithmetic using familiar | 
 | 33 | "schoolhouse" rules and to avoid some of the tricky representation | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 34 | issues associated with binary floating point.  The package is especially | 
 | 35 | useful for financial applications or for contexts where users have | 
 | 36 | expectations that are at odds with binary floating point (for instance, | 
 | 37 | in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 38 | of the expected Decimal('0.00') returned by decimal floating point). | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 39 |  | 
 | 40 | Here are some examples of using the decimal module: | 
 | 41 |  | 
 | 42 | >>> from decimal import * | 
| Raymond Hettinger | bd7f76d | 2004-07-08 00:49:18 +0000 | [diff] [blame] | 43 | >>> setcontext(ExtendedContext) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 44 | >>> Decimal(0) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 45 | Decimal('0') | 
 | 46 | >>> Decimal('1') | 
 | 47 | Decimal('1') | 
 | 48 | >>> Decimal('-.0123') | 
 | 49 | Decimal('-0.0123') | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 50 | >>> Decimal(123456) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 51 | Decimal('123456') | 
 | 52 | >>> Decimal('123.45e12345678901234567890') | 
 | 53 | Decimal('1.2345E+12345678901234567892') | 
 | 54 | >>> Decimal('1.33') + Decimal('1.27') | 
 | 55 | Decimal('2.60') | 
 | 56 | >>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41') | 
 | 57 | Decimal('-2.20') | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 58 | >>> dig = Decimal(1) | 
| Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 59 | >>> print(dig / Decimal(3)) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 60 | 0.333333333 | 
 | 61 | >>> getcontext().prec = 18 | 
| Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 62 | >>> print(dig / Decimal(3)) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 63 | 0.333333333333333333 | 
| Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 64 | >>> print(dig.sqrt()) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 65 | 1 | 
| Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 66 | >>> print(Decimal(3).sqrt()) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 67 | 1.73205080756887729 | 
| Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 68 | >>> print(Decimal(3) ** 123) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 69 | 4.85192780976896427E+58 | 
 | 70 | >>> inf = Decimal(1) / Decimal(0) | 
| Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 71 | >>> print(inf) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 72 | Infinity | 
 | 73 | >>> neginf = Decimal(-1) / Decimal(0) | 
| Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 74 | >>> print(neginf) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 75 | -Infinity | 
| Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 76 | >>> print(neginf + inf) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 77 | NaN | 
| Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 78 | >>> print(neginf * inf) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 79 | -Infinity | 
| Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 80 | >>> print(dig / 0) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 81 | Infinity | 
| Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 82 | >>> getcontext().traps[DivisionByZero] = 1 | 
| Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 83 | >>> print(dig / 0) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 84 | Traceback (most recent call last): | 
 | 85 |   ... | 
 | 86 |   ... | 
 | 87 |   ... | 
| Guido van Rossum | 6a2a2a0 | 2006-08-26 20:37:44 +0000 | [diff] [blame] | 88 | decimal.DivisionByZero: x / 0 | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 89 | >>> c = Context() | 
| Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 90 | >>> c.traps[InvalidOperation] = 0 | 
| Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 91 | >>> print(c.flags[InvalidOperation]) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 92 | 0 | 
 | 93 | >>> c.divide(Decimal(0), Decimal(0)) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 94 | Decimal('NaN') | 
| Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 95 | >>> c.traps[InvalidOperation] = 1 | 
| Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 96 | >>> print(c.flags[InvalidOperation]) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 97 | 1 | 
| Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 98 | >>> c.flags[InvalidOperation] = 0 | 
| Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 99 | >>> print(c.flags[InvalidOperation]) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 100 | 0 | 
| Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 101 | >>> print(c.divide(Decimal(0), Decimal(0))) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 102 | Traceback (most recent call last): | 
 | 103 |   ... | 
 | 104 |   ... | 
 | 105 |   ... | 
| Guido van Rossum | 6a2a2a0 | 2006-08-26 20:37:44 +0000 | [diff] [blame] | 106 | decimal.InvalidOperation: 0 / 0 | 
| Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 107 | >>> print(c.flags[InvalidOperation]) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 108 | 1 | 
| Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 109 | >>> c.flags[InvalidOperation] = 0 | 
| Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 110 | >>> c.traps[InvalidOperation] = 0 | 
| Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 111 | >>> print(c.divide(Decimal(0), Decimal(0))) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 112 | NaN | 
| Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 113 | >>> print(c.flags[InvalidOperation]) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 114 | 1 | 
 | 115 | >>> | 
 | 116 | """ | 
 | 117 |  | 
 | 118 | __all__ = [ | 
 | 119 |     # Two major classes | 
 | 120 |     'Decimal', 'Context', | 
 | 121 |  | 
 | 122 |     # Contexts | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 123 |     'DefaultContext', 'BasicContext', 'ExtendedContext', | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 124 |  | 
 | 125 |     # Exceptions | 
| Raymond Hettinger | d87ac8f | 2004-07-09 10:52:54 +0000 | [diff] [blame] | 126 |     'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero', | 
 | 127 |     'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow', | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 128 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 129 |     # Constants for use in setting up contexts | 
 | 130 |     'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING', | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 131 |     'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP', | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 132 |  | 
 | 133 |     # Functions for manipulating contexts | 
| Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 134 |     'setcontext', 'getcontext', 'localcontext' | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 135 | ] | 
 | 136 |  | 
| Raymond Hettinger | eb26084 | 2005-06-07 18:52:34 +0000 | [diff] [blame] | 137 | import copy as _copy | 
| Raymond Hettinger | 771ed76 | 2009-01-03 19:20:32 +0000 | [diff] [blame] | 138 | import math as _math | 
| Raymond Hettinger | 82417ca | 2009-02-03 03:54:28 +0000 | [diff] [blame^] | 139 | import numbers as _numbers | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 140 |  | 
| Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 141 | try: | 
 | 142 |     from collections import namedtuple as _namedtuple | 
 | 143 |     DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent') | 
 | 144 | except ImportError: | 
 | 145 |     DecimalTuple = lambda *args: args | 
 | 146 |  | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 147 | # Rounding | 
| Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 148 | ROUND_DOWN = 'ROUND_DOWN' | 
 | 149 | ROUND_HALF_UP = 'ROUND_HALF_UP' | 
 | 150 | ROUND_HALF_EVEN = 'ROUND_HALF_EVEN' | 
 | 151 | ROUND_CEILING = 'ROUND_CEILING' | 
 | 152 | ROUND_FLOOR = 'ROUND_FLOOR' | 
 | 153 | ROUND_UP = 'ROUND_UP' | 
 | 154 | ROUND_HALF_DOWN = 'ROUND_HALF_DOWN' | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 155 | ROUND_05UP = 'ROUND_05UP' | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 156 |  | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 157 | # Errors | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 158 |  | 
 | 159 | class DecimalException(ArithmeticError): | 
| Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 160 |     """Base exception class. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 161 |  | 
 | 162 |     Used exceptions derive from this. | 
 | 163 |     If an exception derives from another exception besides this (such as | 
 | 164 |     Underflow (Inexact, Rounded, Subnormal) that indicates that it is only | 
 | 165 |     called if the others are present.  This isn't actually used for | 
 | 166 |     anything, though. | 
 | 167 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 168 |     handle  -- Called when context._raise_error is called and the | 
 | 169 |                trap_enabler is set.  First argument is self, second is the | 
 | 170 |                context.  More arguments can be given, those being after | 
 | 171 |                the explanation in _raise_error (For example, | 
 | 172 |                context._raise_error(NewError, '(-x)!', self._sign) would | 
 | 173 |                call NewError().handle(context, self._sign).) | 
 | 174 |  | 
 | 175 |     To define a new exception, it should be sufficient to have it derive | 
 | 176 |     from DecimalException. | 
 | 177 |     """ | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 178 |     def handle(self, context, *args): | 
 | 179 |         pass | 
 | 180 |  | 
 | 181 |  | 
 | 182 | class Clamped(DecimalException): | 
 | 183 |     """Exponent of a 0 changed to fit bounds. | 
 | 184 |  | 
 | 185 |     This occurs and signals clamped if the exponent of a result has been | 
 | 186 |     altered in order to fit the constraints of a specific concrete | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 187 |     representation.  This may occur when the exponent of a zero result would | 
 | 188 |     be outside the bounds of a representation, or when a large normal | 
 | 189 |     number would have an encoded exponent that cannot be represented.  In | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 190 |     this latter case, the exponent is reduced to fit and the corresponding | 
 | 191 |     number of zero digits are appended to the coefficient ("fold-down"). | 
 | 192 |     """ | 
 | 193 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 194 | class InvalidOperation(DecimalException): | 
 | 195 |     """An invalid operation was performed. | 
 | 196 |  | 
 | 197 |     Various bad things cause this: | 
 | 198 |  | 
 | 199 |     Something creates a signaling NaN | 
 | 200 |     -INF + INF | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 201 |     0 * (+-)INF | 
 | 202 |     (+-)INF / (+-)INF | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 203 |     x % 0 | 
 | 204 |     (+-)INF % x | 
 | 205 |     x._rescale( non-integer ) | 
 | 206 |     sqrt(-x) , x > 0 | 
 | 207 |     0 ** 0 | 
 | 208 |     x ** (non-integer) | 
 | 209 |     x ** (+-)INF | 
 | 210 |     An operand is invalid | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 211 |  | 
 | 212 |     The result of the operation after these is a quiet positive NaN, | 
 | 213 |     except when the cause is a signaling NaN, in which case the result is | 
 | 214 |     also a quiet NaN, but with the original sign, and an optional | 
 | 215 |     diagnostic information. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 216 |     """ | 
 | 217 |     def handle(self, context, *args): | 
 | 218 |         if args: | 
| Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 219 |             ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True) | 
 | 220 |             return ans._fix_nan(context) | 
| Mark Dickinson | f923641 | 2009-01-02 23:23:21 +0000 | [diff] [blame] | 221 |         return _NaN | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 222 |  | 
 | 223 | class ConversionSyntax(InvalidOperation): | 
 | 224 |     """Trying to convert badly formed string. | 
 | 225 |  | 
 | 226 |     This occurs and signals invalid-operation if an string is being | 
 | 227 |     converted to a number and it does not conform to the numeric string | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 228 |     syntax.  The result is [0,qNaN]. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 229 |     """ | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 230 |     def handle(self, context, *args): | 
| Mark Dickinson | f923641 | 2009-01-02 23:23:21 +0000 | [diff] [blame] | 231 |         return _NaN | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 232 |  | 
 | 233 | class DivisionByZero(DecimalException, ZeroDivisionError): | 
 | 234 |     """Division by 0. | 
 | 235 |  | 
 | 236 |     This occurs and signals division-by-zero if division of a finite number | 
 | 237 |     by zero was attempted (during a divide-integer or divide operation, or a | 
 | 238 |     power operation with negative right-hand operand), and the dividend was | 
 | 239 |     not zero. | 
 | 240 |  | 
 | 241 |     The result of the operation is [sign,inf], where sign is the exclusive | 
 | 242 |     or of the signs of the operands for divide, or is 1 for an odd power of | 
 | 243 |     -0, for power. | 
 | 244 |     """ | 
 | 245 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 246 |     def handle(self, context, sign, *args): | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 247 |         return _SignedInfinity[sign] | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 248 |  | 
 | 249 | class DivisionImpossible(InvalidOperation): | 
 | 250 |     """Cannot perform the division adequately. | 
 | 251 |  | 
 | 252 |     This occurs and signals invalid-operation if the integer result of a | 
 | 253 |     divide-integer or remainder operation had too many digits (would be | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 254 |     longer than precision).  The result is [0,qNaN]. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 255 |     """ | 
 | 256 |  | 
 | 257 |     def handle(self, context, *args): | 
| Mark Dickinson | f923641 | 2009-01-02 23:23:21 +0000 | [diff] [blame] | 258 |         return _NaN | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 259 |  | 
 | 260 | class DivisionUndefined(InvalidOperation, ZeroDivisionError): | 
 | 261 |     """Undefined result of division. | 
 | 262 |  | 
 | 263 |     This occurs and signals invalid-operation if division by zero was | 
 | 264 |     attempted (during a divide-integer, divide, or remainder operation), and | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 265 |     the dividend is also zero.  The result is [0,qNaN]. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 266 |     """ | 
 | 267 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 268 |     def handle(self, context, *args): | 
| Mark Dickinson | f923641 | 2009-01-02 23:23:21 +0000 | [diff] [blame] | 269 |         return _NaN | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 270 |  | 
 | 271 | class Inexact(DecimalException): | 
 | 272 |     """Had to round, losing information. | 
 | 273 |  | 
 | 274 |     This occurs and signals inexact whenever the result of an operation is | 
 | 275 |     not exact (that is, it needed to be rounded and any discarded digits | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 276 |     were non-zero), or if an overflow or underflow condition occurs.  The | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 277 |     result in all cases is unchanged. | 
 | 278 |  | 
 | 279 |     The inexact signal may be tested (or trapped) to determine if a given | 
 | 280 |     operation (or sequence of operations) was inexact. | 
 | 281 |     """ | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 282 |  | 
 | 283 | class InvalidContext(InvalidOperation): | 
 | 284 |     """Invalid context.  Unknown rounding, for example. | 
 | 285 |  | 
 | 286 |     This occurs and signals invalid-operation if an invalid context was | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 287 |     detected during an operation.  This can occur if contexts are not checked | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 288 |     on creation and either the precision exceeds the capability of the | 
 | 289 |     underlying concrete representation or an unknown or unsupported rounding | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 290 |     was specified.  These aspects of the context need only be checked when | 
 | 291 |     the values are required to be used.  The result is [0,qNaN]. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 292 |     """ | 
 | 293 |  | 
 | 294 |     def handle(self, context, *args): | 
| Mark Dickinson | f923641 | 2009-01-02 23:23:21 +0000 | [diff] [blame] | 295 |         return _NaN | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 296 |  | 
 | 297 | class Rounded(DecimalException): | 
 | 298 |     """Number got rounded (not  necessarily changed during rounding). | 
 | 299 |  | 
 | 300 |     This occurs and signals rounded whenever the result of an operation is | 
 | 301 |     rounded (that is, some zero or non-zero digits were discarded from the | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 302 |     coefficient), or if an overflow or underflow condition occurs.  The | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 303 |     result in all cases is unchanged. | 
 | 304 |  | 
 | 305 |     The rounded signal may be tested (or trapped) to determine if a given | 
 | 306 |     operation (or sequence of operations) caused a loss of precision. | 
 | 307 |     """ | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 308 |  | 
 | 309 | class Subnormal(DecimalException): | 
 | 310 |     """Exponent < Emin before rounding. | 
 | 311 |  | 
 | 312 |     This occurs and signals subnormal whenever the result of a conversion or | 
 | 313 |     operation is subnormal (that is, its adjusted exponent is less than | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 314 |     Emin, before any rounding).  The result in all cases is unchanged. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 315 |  | 
 | 316 |     The subnormal signal may be tested (or trapped) to determine if a given | 
 | 317 |     or operation (or sequence of operations) yielded a subnormal result. | 
 | 318 |     """ | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 319 |  | 
 | 320 | class Overflow(Inexact, Rounded): | 
 | 321 |     """Numerical overflow. | 
 | 322 |  | 
 | 323 |     This occurs and signals overflow if the adjusted exponent of a result | 
 | 324 |     (from a conversion or from an operation that is not an attempt to divide | 
 | 325 |     by zero), after rounding, would be greater than the largest value that | 
 | 326 |     can be handled by the implementation (the value Emax). | 
 | 327 |  | 
 | 328 |     The result depends on the rounding mode: | 
 | 329 |  | 
 | 330 |     For round-half-up and round-half-even (and for round-half-down and | 
 | 331 |     round-up, if implemented), the result of the operation is [sign,inf], | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 332 |     where sign is the sign of the intermediate result.  For round-down, the | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 333 |     result is the largest finite number that can be represented in the | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 334 |     current precision, with the sign of the intermediate result.  For | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 335 |     round-ceiling, the result is the same as for round-down if the sign of | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 336 |     the intermediate result is 1, or is [0,inf] otherwise.  For round-floor, | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 337 |     the result is the same as for round-down if the sign of the intermediate | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 338 |     result is 0, or is [1,inf] otherwise.  In all cases, Inexact and Rounded | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 339 |     will also be raised. | 
| Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 340 |     """ | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 341 |  | 
 | 342 |     def handle(self, context, sign, *args): | 
 | 343 |         if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN, | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 344 |                                 ROUND_HALF_DOWN, ROUND_UP): | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 345 |             return _SignedInfinity[sign] | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 346 |         if sign == 0: | 
 | 347 |             if context.rounding == ROUND_CEILING: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 348 |                 return _SignedInfinity[sign] | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 349 |             return _dec_from_triple(sign, '9'*context.prec, | 
 | 350 |                             context.Emax-context.prec+1) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 351 |         if sign == 1: | 
 | 352 |             if context.rounding == ROUND_FLOOR: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 353 |                 return _SignedInfinity[sign] | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 354 |             return _dec_from_triple(sign, '9'*context.prec, | 
 | 355 |                              context.Emax-context.prec+1) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 356 |  | 
 | 357 |  | 
 | 358 | class Underflow(Inexact, Rounded, Subnormal): | 
 | 359 |     """Numerical underflow with result rounded to 0. | 
 | 360 |  | 
 | 361 |     This occurs and signals underflow if a result is inexact and the | 
 | 362 |     adjusted exponent of the result would be smaller (more negative) than | 
 | 363 |     the smallest value that can be handled by the implementation (the value | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 364 |     Emin).  That is, the result is both inexact and subnormal. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 365 |  | 
 | 366 |     The result after an underflow will be a subnormal number rounded, if | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 367 |     necessary, so that its exponent is not less than Etiny.  This may result | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 368 |     in 0 with the sign of the intermediate result and an exponent of Etiny. | 
 | 369 |  | 
 | 370 |     In all cases, Inexact, Rounded, and Subnormal will also be raised. | 
 | 371 |     """ | 
 | 372 |  | 
| Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 373 | # List of public traps and flags | 
| Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 374 | _signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded, | 
| Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 375 |            Underflow, InvalidOperation, Subnormal] | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 376 |  | 
| Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 377 | # Map conditions (per the spec) to signals | 
 | 378 | _condition_map = {ConversionSyntax:InvalidOperation, | 
 | 379 |                   DivisionImpossible:InvalidOperation, | 
 | 380 |                   DivisionUndefined:InvalidOperation, | 
 | 381 |                   InvalidContext:InvalidOperation} | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 382 |  | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 383 | ##### Context Functions ################################################## | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 384 |  | 
| Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 385 | # The getcontext() and setcontext() function manage access to a thread-local | 
 | 386 | # current context.  Py2.4 offers direct support for thread locals.  If that | 
| Georg Brandl | f992640 | 2008-06-13 06:32:25 +0000 | [diff] [blame] | 387 | # is not available, use threading.current_thread() which is slower but will | 
| Raymond Hettinger | 7e71fa5 | 2004-12-18 19:07:19 +0000 | [diff] [blame] | 388 | # work for older Pythons.  If threads are not part of the build, create a | 
 | 389 | # mock threading object with threading.local() returning the module namespace. | 
 | 390 |  | 
 | 391 | try: | 
 | 392 |     import threading | 
 | 393 | except ImportError: | 
 | 394 |     # Python was compiled without threads; create a mock object instead | 
 | 395 |     import sys | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 396 |     class MockThreading(object): | 
| Raymond Hettinger | 7e71fa5 | 2004-12-18 19:07:19 +0000 | [diff] [blame] | 397 |         def local(self, sys=sys): | 
 | 398 |             return sys.modules[__name__] | 
 | 399 |     threading = MockThreading() | 
 | 400 |     del sys, MockThreading | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 401 |  | 
| Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 402 | try: | 
 | 403 |     threading.local | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 404 |  | 
| Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 405 | except AttributeError: | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 406 |  | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 407 |     # To fix reloading, force it to create a new context | 
 | 408 |     # Old contexts have different exceptions in their dicts, making problems. | 
| Georg Brandl | f992640 | 2008-06-13 06:32:25 +0000 | [diff] [blame] | 409 |     if hasattr(threading.current_thread(), '__decimal_context__'): | 
 | 410 |         del threading.current_thread().__decimal_context__ | 
| Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 411 |  | 
 | 412 |     def setcontext(context): | 
 | 413 |         """Set this thread's context to context.""" | 
 | 414 |         if context in (DefaultContext, BasicContext, ExtendedContext): | 
| Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 415 |             context = context.copy() | 
| Raymond Hettinger | 61992ef | 2004-08-06 23:42:16 +0000 | [diff] [blame] | 416 |             context.clear_flags() | 
| Georg Brandl | f992640 | 2008-06-13 06:32:25 +0000 | [diff] [blame] | 417 |         threading.current_thread().__decimal_context__ = context | 
| Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 418 |  | 
 | 419 |     def getcontext(): | 
 | 420 |         """Returns this thread's context. | 
 | 421 |  | 
 | 422 |         If this thread does not yet have a context, returns | 
 | 423 |         a new context and sets this thread's context. | 
 | 424 |         New contexts are copies of DefaultContext. | 
 | 425 |         """ | 
 | 426 |         try: | 
| Georg Brandl | f992640 | 2008-06-13 06:32:25 +0000 | [diff] [blame] | 427 |             return threading.current_thread().__decimal_context__ | 
| Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 428 |         except AttributeError: | 
 | 429 |             context = Context() | 
| Georg Brandl | f992640 | 2008-06-13 06:32:25 +0000 | [diff] [blame] | 430 |             threading.current_thread().__decimal_context__ = context | 
| Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 431 |             return context | 
 | 432 |  | 
 | 433 | else: | 
 | 434 |  | 
 | 435 |     local = threading.local() | 
| Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 436 |     if hasattr(local, '__decimal_context__'): | 
 | 437 |         del local.__decimal_context__ | 
| Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 438 |  | 
 | 439 |     def getcontext(_local=local): | 
 | 440 |         """Returns this thread's context. | 
 | 441 |  | 
 | 442 |         If this thread does not yet have a context, returns | 
 | 443 |         a new context and sets this thread's context. | 
 | 444 |         New contexts are copies of DefaultContext. | 
 | 445 |         """ | 
 | 446 |         try: | 
 | 447 |             return _local.__decimal_context__ | 
 | 448 |         except AttributeError: | 
 | 449 |             context = Context() | 
 | 450 |             _local.__decimal_context__ = context | 
 | 451 |             return context | 
 | 452 |  | 
 | 453 |     def setcontext(context, _local=local): | 
 | 454 |         """Set this thread's context to context.""" | 
 | 455 |         if context in (DefaultContext, BasicContext, ExtendedContext): | 
| Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 456 |             context = context.copy() | 
| Raymond Hettinger | 61992ef | 2004-08-06 23:42:16 +0000 | [diff] [blame] | 457 |             context.clear_flags() | 
| Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 458 |         _local.__decimal_context__ = context | 
 | 459 |  | 
 | 460 |     del threading, local        # Don't contaminate the namespace | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 461 |  | 
| Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 462 | def localcontext(ctx=None): | 
 | 463 |     """Return a context manager for a copy of the supplied context | 
 | 464 |  | 
 | 465 |     Uses a copy of the current context if no context is specified | 
 | 466 |     The returned context manager creates a local decimal context | 
 | 467 |     in a with statement: | 
 | 468 |         def sin(x): | 
 | 469 |              with localcontext() as ctx: | 
 | 470 |                  ctx.prec += 2 | 
 | 471 |                  # Rest of sin calculation algorithm | 
 | 472 |                  # uses a precision 2 greater than normal | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 473 |              return +s  # Convert result to normal precision | 
| Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 474 |  | 
 | 475 |          def sin(x): | 
 | 476 |              with localcontext(ExtendedContext): | 
 | 477 |                  # Rest of sin calculation algorithm | 
 | 478 |                  # uses the Extended Context from the | 
 | 479 |                  # General Decimal Arithmetic Specification | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 480 |              return +s  # Convert result to normal context | 
| Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 481 |  | 
| Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 482 |     >>> setcontext(DefaultContext) | 
| Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 483 |     >>> print(getcontext().prec) | 
| Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 484 |     28 | 
 | 485 |     >>> with localcontext(): | 
 | 486 |     ...     ctx = getcontext() | 
| Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 487 |     ...     ctx.prec += 2 | 
| Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 488 |     ...     print(ctx.prec) | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 489 |     ... | 
| Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 490 |     30 | 
 | 491 |     >>> with localcontext(ExtendedContext): | 
| Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 492 |     ...     print(getcontext().prec) | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 493 |     ... | 
| Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 494 |     9 | 
| Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 495 |     >>> print(getcontext().prec) | 
| Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 496 |     28 | 
 | 497 |     """ | 
 | 498 |     if ctx is None: ctx = getcontext() | 
 | 499 |     return _ContextManager(ctx) | 
 | 500 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 501 |  | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 502 | ##### Decimal class ####################################################### | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 503 |  | 
| Raymond Hettinger | a0fd888 | 2009-01-20 07:24:44 +0000 | [diff] [blame] | 504 | # Do not subclass Decimal from numbers.Real and do not register it as such | 
 | 505 | # (because Decimals are not interoperable with floats).  See the notes in | 
 | 506 | # numbers.py for more detail. | 
 | 507 |  | 
 | 508 | class Decimal(object): | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 509 |     """Floating point class for decimal arithmetic.""" | 
 | 510 |  | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 511 |     __slots__ = ('_exp','_int','_sign', '_is_special') | 
 | 512 |     # Generally, the value of the Decimal instance is given by | 
 | 513 |     #  (-1)**_sign * _int * 10**_exp | 
 | 514 |     # Special values are signified by _is_special == True | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 515 |  | 
| Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 516 |     # We're immutable, so use __new__ not __init__ | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 517 |     def __new__(cls, value="0", context=None): | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 518 |         """Create a decimal point instance. | 
 | 519 |  | 
 | 520 |         >>> Decimal('3.14')              # string input | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 521 |         Decimal('3.14') | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 522 |         >>> Decimal((0, (3, 1, 4), -2))  # tuple (sign, digit_tuple, exponent) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 523 |         Decimal('3.14') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 524 |         >>> Decimal(314)                 # int | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 525 |         Decimal('314') | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 526 |         >>> Decimal(Decimal(314))        # another decimal instance | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 527 |         Decimal('314') | 
| Christian Heimes | a62da1d | 2008-01-12 19:39:10 +0000 | [diff] [blame] | 528 |         >>> Decimal('  3.14  \\n')        # leading and trailing whitespace okay | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 529 |         Decimal('3.14') | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 530 |         """ | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 531 |  | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 532 |         # Note that the coefficient, self._int, is actually stored as | 
 | 533 |         # a string rather than as a tuple of digits.  This speeds up | 
 | 534 |         # the "digits to integer" and "integer to digits" conversions | 
 | 535 |         # that are used in almost every arithmetic operation on | 
 | 536 |         # Decimals.  This is an internal detail: the as_tuple function | 
 | 537 |         # and the Decimal constructor still deal with tuples of | 
 | 538 |         # digits. | 
 | 539 |  | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 540 |         self = object.__new__(cls) | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 541 |  | 
| Christian Heimes | d59c64c | 2007-11-30 19:27:20 +0000 | [diff] [blame] | 542 |         # From a string | 
 | 543 |         # REs insist on real strings, so we can too. | 
 | 544 |         if isinstance(value, str): | 
| Christian Heimes | a62da1d | 2008-01-12 19:39:10 +0000 | [diff] [blame] | 545 |             m = _parser(value.strip()) | 
| Christian Heimes | d59c64c | 2007-11-30 19:27:20 +0000 | [diff] [blame] | 546 |             if m is None: | 
 | 547 |                 if context is None: | 
 | 548 |                     context = getcontext() | 
 | 549 |                 return context._raise_error(ConversionSyntax, | 
 | 550 |                                 "Invalid literal for Decimal: %r" % value) | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 551 |  | 
| Christian Heimes | d59c64c | 2007-11-30 19:27:20 +0000 | [diff] [blame] | 552 |             if m.group('sign') == "-": | 
 | 553 |                 self._sign = 1 | 
 | 554 |             else: | 
 | 555 |                 self._sign = 0 | 
 | 556 |             intpart = m.group('int') | 
 | 557 |             if intpart is not None: | 
 | 558 |                 # finite number | 
 | 559 |                 fracpart = m.group('frac') | 
 | 560 |                 exp = int(m.group('exp') or '0') | 
 | 561 |                 if fracpart is not None: | 
 | 562 |                     self._int = (intpart+fracpart).lstrip('0') or '0' | 
 | 563 |                     self._exp = exp - len(fracpart) | 
 | 564 |                 else: | 
 | 565 |                     self._int = intpart.lstrip('0') or '0' | 
 | 566 |                     self._exp = exp | 
 | 567 |                 self._is_special = False | 
 | 568 |             else: | 
 | 569 |                 diag = m.group('diag') | 
 | 570 |                 if diag is not None: | 
 | 571 |                     # NaN | 
 | 572 |                     self._int = diag.lstrip('0') | 
 | 573 |                     if m.group('signal'): | 
 | 574 |                         self._exp = 'N' | 
 | 575 |                     else: | 
 | 576 |                         self._exp = 'n' | 
 | 577 |                 else: | 
 | 578 |                     # infinity | 
 | 579 |                     self._int = '0' | 
 | 580 |                     self._exp = 'F' | 
 | 581 |                 self._is_special = True | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 582 |             return self | 
 | 583 |  | 
 | 584 |         # From an integer | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 585 |         if isinstance(value, int): | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 586 |             if value >= 0: | 
 | 587 |                 self._sign = 0 | 
 | 588 |             else: | 
 | 589 |                 self._sign = 1 | 
 | 590 |             self._exp = 0 | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 591 |             self._int = str(abs(value)) | 
| Christian Heimes | d59c64c | 2007-11-30 19:27:20 +0000 | [diff] [blame] | 592 |             self._is_special = False | 
 | 593 |             return self | 
 | 594 |  | 
 | 595 |         # From another decimal | 
 | 596 |         if isinstance(value, Decimal): | 
 | 597 |             self._exp  = value._exp | 
 | 598 |             self._sign = value._sign | 
 | 599 |             self._int  = value._int | 
 | 600 |             self._is_special  = value._is_special | 
 | 601 |             return self | 
 | 602 |  | 
 | 603 |         # From an internal working value | 
 | 604 |         if isinstance(value, _WorkRep): | 
 | 605 |             self._sign = value.sign | 
 | 606 |             self._int = str(value.int) | 
 | 607 |             self._exp = int(value.exp) | 
 | 608 |             self._is_special = False | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 609 |             return self | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 610 |  | 
 | 611 |         # tuple/list conversion (possibly from as_tuple()) | 
 | 612 |         if isinstance(value, (list,tuple)): | 
 | 613 |             if len(value) != 3: | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 614 |                 raise ValueError('Invalid tuple size in creation of Decimal ' | 
 | 615 |                                  'from list or tuple.  The list or tuple ' | 
 | 616 |                                  'should have exactly three elements.') | 
 | 617 |             # process sign.  The isinstance test rejects floats | 
 | 618 |             if not (isinstance(value[0], int) and value[0] in (0,1)): | 
 | 619 |                 raise ValueError("Invalid sign.  The first value in the tuple " | 
 | 620 |                                  "should be an integer; either 0 for a " | 
 | 621 |                                  "positive number or 1 for a negative number.") | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 622 |             self._sign = value[0] | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 623 |             if value[2] == 'F': | 
 | 624 |                 # infinity: value[1] is ignored | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 625 |                 self._int = '0' | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 626 |                 self._exp = value[2] | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 627 |                 self._is_special = True | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 628 |             else: | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 629 |                 # process and validate the digits in value[1] | 
 | 630 |                 digits = [] | 
 | 631 |                 for digit in value[1]: | 
 | 632 |                     if isinstance(digit, int) and 0 <= digit <= 9: | 
 | 633 |                         # skip leading zeros | 
 | 634 |                         if digits or digit != 0: | 
 | 635 |                             digits.append(digit) | 
 | 636 |                     else: | 
 | 637 |                         raise ValueError("The second value in the tuple must " | 
 | 638 |                                          "be composed of integers in the range " | 
 | 639 |                                          "0 through 9.") | 
 | 640 |                 if value[2] in ('n', 'N'): | 
 | 641 |                     # NaN: digits form the diagnostic | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 642 |                     self._int = ''.join(map(str, digits)) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 643 |                     self._exp = value[2] | 
 | 644 |                     self._is_special = True | 
 | 645 |                 elif isinstance(value[2], int): | 
 | 646 |                     # finite number: digits give the coefficient | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 647 |                     self._int = ''.join(map(str, digits or [0])) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 648 |                     self._exp = value[2] | 
 | 649 |                     self._is_special = False | 
 | 650 |                 else: | 
 | 651 |                     raise ValueError("The third value in the tuple must " | 
 | 652 |                                      "be an integer, or one of the " | 
 | 653 |                                      "strings 'F', 'n', 'N'.") | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 654 |             return self | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 655 |  | 
| Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 656 |         if isinstance(value, float): | 
 | 657 |             raise TypeError("Cannot convert float to Decimal.  " + | 
 | 658 |                             "First convert the float to a string") | 
 | 659 |  | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 660 |         raise TypeError("Cannot convert %r to Decimal" % value) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 661 |  | 
| Mark Dickinson | ba298e4 | 2009-01-04 21:17:43 +0000 | [diff] [blame] | 662 |     # @classmethod, but @decorator is not valid Python 2.3 syntax, so | 
 | 663 |     # don't use it (see notes on Py2.3 compatibility at top of file) | 
| Raymond Hettinger | 771ed76 | 2009-01-03 19:20:32 +0000 | [diff] [blame] | 664 |     def from_float(cls, f): | 
 | 665 |         """Converts a float to a decimal number, exactly. | 
 | 666 |  | 
 | 667 |         Note that Decimal.from_float(0.1) is not the same as Decimal('0.1'). | 
 | 668 |         Since 0.1 is not exactly representable in binary floating point, the | 
 | 669 |         value is stored as the nearest representable value which is | 
 | 670 |         0x1.999999999999ap-4.  The exact equivalent of the value in decimal | 
 | 671 |         is 0.1000000000000000055511151231257827021181583404541015625. | 
 | 672 |  | 
 | 673 |         >>> Decimal.from_float(0.1) | 
 | 674 |         Decimal('0.1000000000000000055511151231257827021181583404541015625') | 
 | 675 |         >>> Decimal.from_float(float('nan')) | 
 | 676 |         Decimal('NaN') | 
 | 677 |         >>> Decimal.from_float(float('inf')) | 
 | 678 |         Decimal('Infinity') | 
 | 679 |         >>> Decimal.from_float(-float('inf')) | 
 | 680 |         Decimal('-Infinity') | 
 | 681 |         >>> Decimal.from_float(-0.0) | 
 | 682 |         Decimal('-0') | 
 | 683 |  | 
 | 684 |         """ | 
 | 685 |         if isinstance(f, int):                # handle integer inputs | 
 | 686 |             return cls(f) | 
 | 687 |         if _math.isinf(f) or _math.isnan(f):  # raises TypeError if not a float | 
 | 688 |             return cls(repr(f)) | 
| Mark Dickinson | ba298e4 | 2009-01-04 21:17:43 +0000 | [diff] [blame] | 689 |         if _math.copysign(1.0, f) == 1.0: | 
 | 690 |             sign = 0 | 
 | 691 |         else: | 
 | 692 |             sign = 1 | 
| Raymond Hettinger | 771ed76 | 2009-01-03 19:20:32 +0000 | [diff] [blame] | 693 |         n, d = abs(f).as_integer_ratio() | 
 | 694 |         k = d.bit_length() - 1 | 
 | 695 |         result = _dec_from_triple(sign, str(n*5**k), -k) | 
| Mark Dickinson | ba298e4 | 2009-01-04 21:17:43 +0000 | [diff] [blame] | 696 |         if cls is Decimal: | 
 | 697 |             return result | 
 | 698 |         else: | 
 | 699 |             return cls(result) | 
 | 700 |     from_float = classmethod(from_float) | 
| Raymond Hettinger | 771ed76 | 2009-01-03 19:20:32 +0000 | [diff] [blame] | 701 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 702 |     def _isnan(self): | 
 | 703 |         """Returns whether the number is not actually one. | 
 | 704 |  | 
 | 705 |         0 if a number | 
| Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 706 |         1 if NaN | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 707 |         2 if sNaN | 
 | 708 |         """ | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 709 |         if self._is_special: | 
 | 710 |             exp = self._exp | 
 | 711 |             if exp == 'n': | 
 | 712 |                 return 1 | 
 | 713 |             elif exp == 'N': | 
 | 714 |                 return 2 | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 715 |         return 0 | 
 | 716 |  | 
 | 717 |     def _isinfinity(self): | 
 | 718 |         """Returns whether the number is infinite | 
 | 719 |  | 
 | 720 |         0 if finite or not a number | 
 | 721 |         1 if +INF | 
 | 722 |         -1 if -INF | 
 | 723 |         """ | 
 | 724 |         if self._exp == 'F': | 
 | 725 |             if self._sign: | 
 | 726 |                 return -1 | 
 | 727 |             return 1 | 
 | 728 |         return 0 | 
 | 729 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 730 |     def _check_nans(self, other=None, context=None): | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 731 |         """Returns whether the number is not actually one. | 
 | 732 |  | 
 | 733 |         if self, other are sNaN, signal | 
 | 734 |         if self, other are NaN return nan | 
 | 735 |         return 0 | 
 | 736 |  | 
 | 737 |         Done before operations. | 
 | 738 |         """ | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 739 |  | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 740 |         self_is_nan = self._isnan() | 
 | 741 |         if other is None: | 
 | 742 |             other_is_nan = False | 
 | 743 |         else: | 
 | 744 |             other_is_nan = other._isnan() | 
 | 745 |  | 
 | 746 |         if self_is_nan or other_is_nan: | 
 | 747 |             if context is None: | 
 | 748 |                 context = getcontext() | 
 | 749 |  | 
 | 750 |             if self_is_nan == 2: | 
 | 751 |                 return context._raise_error(InvalidOperation, 'sNaN', | 
| Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 752 |                                         self) | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 753 |             if other_is_nan == 2: | 
 | 754 |                 return context._raise_error(InvalidOperation, 'sNaN', | 
| Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 755 |                                         other) | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 756 |             if self_is_nan: | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 757 |                 return self._fix_nan(context) | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 758 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 759 |             return other._fix_nan(context) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 760 |         return 0 | 
 | 761 |  | 
| Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 762 |     def _compare_check_nans(self, other, context): | 
 | 763 |         """Version of _check_nans used for the signaling comparisons | 
 | 764 |         compare_signal, __le__, __lt__, __ge__, __gt__. | 
 | 765 |  | 
 | 766 |         Signal InvalidOperation if either self or other is a (quiet | 
 | 767 |         or signaling) NaN.  Signaling NaNs take precedence over quiet | 
 | 768 |         NaNs. | 
 | 769 |  | 
 | 770 |         Return 0 if neither operand is a NaN. | 
 | 771 |  | 
 | 772 |         """ | 
 | 773 |         if context is None: | 
 | 774 |             context = getcontext() | 
 | 775 |  | 
 | 776 |         if self._is_special or other._is_special: | 
 | 777 |             if self.is_snan(): | 
 | 778 |                 return context._raise_error(InvalidOperation, | 
 | 779 |                                             'comparison involving sNaN', | 
 | 780 |                                             self) | 
 | 781 |             elif other.is_snan(): | 
 | 782 |                 return context._raise_error(InvalidOperation, | 
 | 783 |                                             'comparison involving sNaN', | 
 | 784 |                                             other) | 
 | 785 |             elif self.is_qnan(): | 
 | 786 |                 return context._raise_error(InvalidOperation, | 
 | 787 |                                             'comparison involving NaN', | 
 | 788 |                                             self) | 
 | 789 |             elif other.is_qnan(): | 
 | 790 |                 return context._raise_error(InvalidOperation, | 
 | 791 |                                             'comparison involving NaN', | 
 | 792 |                                             other) | 
 | 793 |         return 0 | 
 | 794 |  | 
| Jack Diederich | 4dafcc4 | 2006-11-28 19:15:13 +0000 | [diff] [blame] | 795 |     def __bool__(self): | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 796 |         """Return True if self is nonzero; otherwise return False. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 797 |  | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 798 |         NaNs and infinities are considered nonzero. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 799 |         """ | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 800 |         return self._is_special or self._int != '0' | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 801 |  | 
| Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 802 |     def _cmp(self, other): | 
 | 803 |         """Compare the two non-NaN decimal instances self and other. | 
 | 804 |  | 
 | 805 |         Returns -1 if self < other, 0 if self == other and 1 | 
 | 806 |         if self > other.  This routine is for internal use only.""" | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 807 |  | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 808 |         if self._is_special or other._is_special: | 
| Mark Dickinson | e6aad75 | 2009-01-25 10:48:51 +0000 | [diff] [blame] | 809 |             self_inf = self._isinfinity() | 
 | 810 |             other_inf = other._isinfinity() | 
 | 811 |             if self_inf == other_inf: | 
 | 812 |                 return 0 | 
 | 813 |             elif self_inf < other_inf: | 
 | 814 |                 return -1 | 
 | 815 |             else: | 
 | 816 |                 return 1 | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 817 |  | 
| Mark Dickinson | e6aad75 | 2009-01-25 10:48:51 +0000 | [diff] [blame] | 818 |         # check for zeros;  Decimal('0') == Decimal('-0') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 819 |         if not self: | 
 | 820 |             if not other: | 
 | 821 |                 return 0 | 
 | 822 |             else: | 
 | 823 |                 return -((-1)**other._sign) | 
 | 824 |         if not other: | 
 | 825 |             return (-1)**self._sign | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 826 |  | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 827 |         # If different signs, neg one is less | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 828 |         if other._sign < self._sign: | 
 | 829 |             return -1 | 
 | 830 |         if self._sign < other._sign: | 
 | 831 |             return 1 | 
 | 832 |  | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 833 |         self_adjusted = self.adjusted() | 
 | 834 |         other_adjusted = other.adjusted() | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 835 |         if self_adjusted == other_adjusted: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 836 |             self_padded = self._int + '0'*(self._exp - other._exp) | 
 | 837 |             other_padded = other._int + '0'*(other._exp - self._exp) | 
| Mark Dickinson | e6aad75 | 2009-01-25 10:48:51 +0000 | [diff] [blame] | 838 |             if self_padded == other_padded: | 
 | 839 |                 return 0 | 
 | 840 |             elif self_padded < other_padded: | 
 | 841 |                 return -(-1)**self._sign | 
 | 842 |             else: | 
 | 843 |                 return (-1)**self._sign | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 844 |         elif self_adjusted > other_adjusted: | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 845 |             return (-1)**self._sign | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 846 |         else: # self_adjusted < other_adjusted | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 847 |             return -((-1)**self._sign) | 
 | 848 |  | 
| Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 849 |     # Note: The Decimal standard doesn't cover rich comparisons for | 
 | 850 |     # Decimals.  In particular, the specification is silent on the | 
 | 851 |     # subject of what should happen for a comparison involving a NaN. | 
 | 852 |     # We take the following approach: | 
 | 853 |     # | 
 | 854 |     #   == comparisons involving a NaN always return False | 
 | 855 |     #   != comparisons involving a NaN always return True | 
 | 856 |     #   <, >, <= and >= comparisons involving a (quiet or signaling) | 
 | 857 |     #      NaN signal InvalidOperation, and return False if the | 
| Christian Heimes | 3feef61 | 2008-02-11 06:19:17 +0000 | [diff] [blame] | 858 |     #      InvalidOperation is not trapped. | 
| Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 859 |     # | 
 | 860 |     # This behavior is designed to conform as closely as possible to | 
 | 861 |     # that specified by IEEE 754. | 
 | 862 |  | 
| Raymond Hettinger | 0aeac10 | 2004-07-05 22:53:03 +0000 | [diff] [blame] | 863 |     def __eq__(self, other): | 
| Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 864 |         other = _convert_other(other) | 
 | 865 |         if other is NotImplemented: | 
 | 866 |             return other | 
 | 867 |         if self.is_nan() or other.is_nan(): | 
 | 868 |             return False | 
 | 869 |         return self._cmp(other) == 0 | 
| Raymond Hettinger | 0aeac10 | 2004-07-05 22:53:03 +0000 | [diff] [blame] | 870 |  | 
 | 871 |     def __ne__(self, other): | 
| Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 872 |         other = _convert_other(other) | 
 | 873 |         if other is NotImplemented: | 
 | 874 |             return other | 
 | 875 |         if self.is_nan() or other.is_nan(): | 
 | 876 |             return True | 
 | 877 |         return self._cmp(other) != 0 | 
| Raymond Hettinger | 0aeac10 | 2004-07-05 22:53:03 +0000 | [diff] [blame] | 878 |  | 
| Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 879 |  | 
| Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 880 |     def __lt__(self, other, context=None): | 
 | 881 |         other = _convert_other(other) | 
 | 882 |         if other is NotImplemented: | 
 | 883 |             return other | 
 | 884 |         ans = self._compare_check_nans(other, context) | 
 | 885 |         if ans: | 
 | 886 |             return False | 
 | 887 |         return self._cmp(other) < 0 | 
| Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 888 |  | 
| Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 889 |     def __le__(self, other, context=None): | 
 | 890 |         other = _convert_other(other) | 
 | 891 |         if other is NotImplemented: | 
 | 892 |             return other | 
 | 893 |         ans = self._compare_check_nans(other, context) | 
 | 894 |         if ans: | 
 | 895 |             return False | 
 | 896 |         return self._cmp(other) <= 0 | 
| Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 897 |  | 
| Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 898 |     def __gt__(self, other, context=None): | 
 | 899 |         other = _convert_other(other) | 
 | 900 |         if other is NotImplemented: | 
 | 901 |             return other | 
 | 902 |         ans = self._compare_check_nans(other, context) | 
 | 903 |         if ans: | 
 | 904 |             return False | 
 | 905 |         return self._cmp(other) > 0 | 
 | 906 |  | 
 | 907 |     def __ge__(self, other, context=None): | 
 | 908 |         other = _convert_other(other) | 
 | 909 |         if other is NotImplemented: | 
 | 910 |             return other | 
 | 911 |         ans = self._compare_check_nans(other, context) | 
 | 912 |         if ans: | 
 | 913 |             return False | 
 | 914 |         return self._cmp(other) >= 0 | 
| Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 915 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 916 |     def compare(self, other, context=None): | 
 | 917 |         """Compares one to another. | 
 | 918 |  | 
 | 919 |         -1 => a < b | 
 | 920 |         0  => a = b | 
 | 921 |         1  => a > b | 
 | 922 |         NaN => one is NaN | 
 | 923 |         Like __cmp__, but returns Decimal instances. | 
 | 924 |         """ | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 925 |         other = _convert_other(other, raiseit=True) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 926 |  | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 927 |         # Compare(NaN, NaN) = NaN | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 928 |         if (self._is_special or other and other._is_special): | 
 | 929 |             ans = self._check_nans(other, context) | 
 | 930 |             if ans: | 
 | 931 |                 return ans | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 932 |  | 
| Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 933 |         return Decimal(self._cmp(other)) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 934 |  | 
 | 935 |     def __hash__(self): | 
 | 936 |         """x.__hash__() <==> hash(x)""" | 
 | 937 |         # Decimal integers must hash the same as the ints | 
| Christian Heimes | 2380ac7 | 2008-01-09 00:17:24 +0000 | [diff] [blame] | 938 |         # | 
 | 939 |         # The hash of a nonspecial noninteger Decimal must depend only | 
 | 940 |         # on the value of that Decimal, and not on its representation. | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 941 |         # For example: hash(Decimal('100E-1')) == hash(Decimal('10')). | 
| Raymond Hettinger | bea3f6f | 2005-03-15 04:59:17 +0000 | [diff] [blame] | 942 |         if self._is_special: | 
 | 943 |             if self._isnan(): | 
 | 944 |                 raise TypeError('Cannot hash a NaN value.') | 
 | 945 |             return hash(str(self)) | 
| Thomas Wouters | 8ce81f7 | 2007-09-20 18:22:40 +0000 | [diff] [blame] | 946 |         if not self: | 
 | 947 |             return 0 | 
 | 948 |         if self._isinteger(): | 
 | 949 |             op = _WorkRep(self.to_integral_value()) | 
 | 950 |             # to make computation feasible for Decimals with large | 
 | 951 |             # exponent, we use the fact that hash(n) == hash(m) for | 
 | 952 |             # any two nonzero integers n and m such that (i) n and m | 
 | 953 |             # have the same sign, and (ii) n is congruent to m modulo | 
 | 954 |             # 2**64-1.  So we can replace hash((-1)**s*c*10**e) with | 
 | 955 |             # hash((-1)**s*c*pow(10, e, 2**64-1). | 
 | 956 |             return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1)) | 
| Christian Heimes | 2380ac7 | 2008-01-09 00:17:24 +0000 | [diff] [blame] | 957 |         # The value of a nonzero nonspecial Decimal instance is | 
 | 958 |         # faithfully represented by the triple consisting of its sign, | 
 | 959 |         # its adjusted exponent, and its coefficient with trailing | 
 | 960 |         # zeros removed. | 
 | 961 |         return hash((self._sign, | 
 | 962 |                      self._exp+len(self._int), | 
 | 963 |                      self._int.rstrip('0'))) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 964 |  | 
 | 965 |     def as_tuple(self): | 
 | 966 |         """Represents the number as a triple tuple. | 
 | 967 |  | 
 | 968 |         To show the internals exactly as they are. | 
 | 969 |         """ | 
| Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 970 |         return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 971 |  | 
 | 972 |     def __repr__(self): | 
 | 973 |         """Represents the number as an instance of Decimal.""" | 
 | 974 |         # Invariant:  eval(repr(d)) == d | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 975 |         return "Decimal('%s')" % str(self) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 976 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 977 |     def __str__(self, eng=False, context=None): | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 978 |         """Return string representation of the number in scientific notation. | 
 | 979 |  | 
 | 980 |         Captures all of the information in the underlying representation. | 
 | 981 |         """ | 
 | 982 |  | 
| Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 983 |         sign = ['', '-'][self._sign] | 
| Raymond Hettinger | e5a0a96 | 2005-06-20 09:49:42 +0000 | [diff] [blame] | 984 |         if self._is_special: | 
| Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 985 |             if self._exp == 'F': | 
 | 986 |                 return sign + 'Infinity' | 
 | 987 |             elif self._exp == 'n': | 
 | 988 |                 return sign + 'NaN' + self._int | 
 | 989 |             else: # self._exp == 'N' | 
 | 990 |                 return sign + 'sNaN' + self._int | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 991 |  | 
| Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 992 |         # number of digits of self._int to left of decimal point | 
 | 993 |         leftdigits = self._exp + len(self._int) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 994 |  | 
| Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 995 |         # dotplace is number of digits of self._int to the left of the | 
 | 996 |         # decimal point in the mantissa of the output string (that is, | 
 | 997 |         # after adjusting the exponent) | 
 | 998 |         if self._exp <= 0 and leftdigits > -6: | 
 | 999 |             # no exponent required | 
 | 1000 |             dotplace = leftdigits | 
 | 1001 |         elif not eng: | 
 | 1002 |             # usual scientific notation: 1 digit on left of the point | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1003 |             dotplace = 1 | 
| Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1004 |         elif self._int == '0': | 
 | 1005 |             # engineering notation, zero | 
 | 1006 |             dotplace = (leftdigits + 1) % 3 - 1 | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1007 |         else: | 
| Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1008 |             # engineering notation, nonzero | 
 | 1009 |             dotplace = (leftdigits - 1) % 3 + 1 | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1010 |  | 
| Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1011 |         if dotplace <= 0: | 
 | 1012 |             intpart = '0' | 
 | 1013 |             fracpart = '.' + '0'*(-dotplace) + self._int | 
 | 1014 |         elif dotplace >= len(self._int): | 
 | 1015 |             intpart = self._int+'0'*(dotplace-len(self._int)) | 
 | 1016 |             fracpart = '' | 
 | 1017 |         else: | 
 | 1018 |             intpart = self._int[:dotplace] | 
 | 1019 |             fracpart = '.' + self._int[dotplace:] | 
 | 1020 |         if leftdigits == dotplace: | 
 | 1021 |             exp = '' | 
 | 1022 |         else: | 
 | 1023 |             if context is None: | 
 | 1024 |                 context = getcontext() | 
 | 1025 |             exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace) | 
 | 1026 |  | 
 | 1027 |         return sign + intpart + fracpart + exp | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1028 |  | 
 | 1029 |     def to_eng_string(self, context=None): | 
 | 1030 |         """Convert to engineering-type string. | 
 | 1031 |  | 
 | 1032 |         Engineering notation has an exponent which is a multiple of 3, so there | 
 | 1033 |         are up to 3 digits left of the decimal place. | 
 | 1034 |  | 
 | 1035 |         Same rules for when in exponential and when as a value as in __str__. | 
 | 1036 |         """ | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1037 |         return self.__str__(eng=True, context=context) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1038 |  | 
 | 1039 |     def __neg__(self, context=None): | 
 | 1040 |         """Returns a copy with the sign switched. | 
 | 1041 |  | 
 | 1042 |         Rounds, if it has reason. | 
 | 1043 |         """ | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1044 |         if self._is_special: | 
 | 1045 |             ans = self._check_nans(context=context) | 
 | 1046 |             if ans: | 
 | 1047 |                 return ans | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1048 |  | 
 | 1049 |         if not self: | 
 | 1050 |             # -Decimal('0') is Decimal('0'), not Decimal('-0') | 
| Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 1051 |             ans = self.copy_abs() | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1052 |         else: | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1053 |             ans = self.copy_negate() | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1054 |  | 
 | 1055 |         if context is None: | 
 | 1056 |             context = getcontext() | 
| Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1057 |         return ans._fix(context) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1058 |  | 
 | 1059 |     def __pos__(self, context=None): | 
 | 1060 |         """Returns a copy, unless it is a sNaN. | 
 | 1061 |  | 
 | 1062 |         Rounds the number (if more then precision digits) | 
 | 1063 |         """ | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1064 |         if self._is_special: | 
 | 1065 |             ans = self._check_nans(context=context) | 
 | 1066 |             if ans: | 
 | 1067 |                 return ans | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1068 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1069 |         if not self: | 
 | 1070 |             # + (-0) = 0 | 
| Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 1071 |             ans = self.copy_abs() | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1072 |         else: | 
 | 1073 |             ans = Decimal(self) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1074 |  | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1075 |         if context is None: | 
 | 1076 |             context = getcontext() | 
| Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1077 |         return ans._fix(context) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1078 |  | 
| Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1079 |     def __abs__(self, round=True, context=None): | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1080 |         """Returns the absolute value of self. | 
 | 1081 |  | 
| Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1082 |         If the keyword argument 'round' is false, do not round.  The | 
 | 1083 |         expression self.__abs__(round=False) is equivalent to | 
 | 1084 |         self.copy_abs(). | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1085 |         """ | 
| Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1086 |         if not round: | 
 | 1087 |             return self.copy_abs() | 
 | 1088 |  | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1089 |         if self._is_special: | 
 | 1090 |             ans = self._check_nans(context=context) | 
 | 1091 |             if ans: | 
 | 1092 |                 return ans | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1093 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1094 |         if self._sign: | 
 | 1095 |             ans = self.__neg__(context=context) | 
 | 1096 |         else: | 
 | 1097 |             ans = self.__pos__(context=context) | 
 | 1098 |  | 
 | 1099 |         return ans | 
 | 1100 |  | 
 | 1101 |     def __add__(self, other, context=None): | 
 | 1102 |         """Returns self + other. | 
 | 1103 |  | 
 | 1104 |         -INF + INF (or the reverse) cause InvalidOperation errors. | 
 | 1105 |         """ | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1106 |         other = _convert_other(other) | 
| Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1107 |         if other is NotImplemented: | 
 | 1108 |             return other | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1109 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1110 |         if context is None: | 
 | 1111 |             context = getcontext() | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1112 |  | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1113 |         if self._is_special or other._is_special: | 
 | 1114 |             ans = self._check_nans(other, context) | 
 | 1115 |             if ans: | 
 | 1116 |                 return ans | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1117 |  | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1118 |             if self._isinfinity(): | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1119 |                 # If both INF, same sign => same as both, opposite => error. | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1120 |                 if self._sign != other._sign and other._isinfinity(): | 
 | 1121 |                     return context._raise_error(InvalidOperation, '-INF + INF') | 
 | 1122 |                 return Decimal(self) | 
 | 1123 |             if other._isinfinity(): | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1124 |                 return Decimal(other)  # Can't both be infinity here | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1125 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1126 |         exp = min(self._exp, other._exp) | 
 | 1127 |         negativezero = 0 | 
 | 1128 |         if context.rounding == ROUND_FLOOR and self._sign != other._sign: | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1129 |             # If the answer is 0, the sign should be negative, in this case. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1130 |             negativezero = 1 | 
 | 1131 |  | 
 | 1132 |         if not self and not other: | 
 | 1133 |             sign = min(self._sign, other._sign) | 
 | 1134 |             if negativezero: | 
 | 1135 |                 sign = 1 | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1136 |             ans = _dec_from_triple(sign, '0', exp) | 
| Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1137 |             ans = ans._fix(context) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1138 |             return ans | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1139 |         if not self: | 
| Facundo Batista | 99b5548 | 2004-10-26 23:38:46 +0000 | [diff] [blame] | 1140 |             exp = max(exp, other._exp - context.prec-1) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1141 |             ans = other._rescale(exp, context.rounding) | 
| Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1142 |             ans = ans._fix(context) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1143 |             return ans | 
 | 1144 |         if not other: | 
| Facundo Batista | 99b5548 | 2004-10-26 23:38:46 +0000 | [diff] [blame] | 1145 |             exp = max(exp, self._exp - context.prec-1) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1146 |             ans = self._rescale(exp, context.rounding) | 
| Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1147 |             ans = ans._fix(context) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1148 |             return ans | 
 | 1149 |  | 
 | 1150 |         op1 = _WorkRep(self) | 
 | 1151 |         op2 = _WorkRep(other) | 
| Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1152 |         op1, op2 = _normalize(op1, op2, context.prec) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1153 |  | 
 | 1154 |         result = _WorkRep() | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1155 |         if op1.sign != op2.sign: | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1156 |             # Equal and opposite | 
| Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1157 |             if op1.int == op2.int: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1158 |                 ans = _dec_from_triple(negativezero, '0', exp) | 
| Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1159 |                 ans = ans._fix(context) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1160 |                 return ans | 
| Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1161 |             if op1.int < op2.int: | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1162 |                 op1, op2 = op2, op1 | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1163 |                 # OK, now abs(op1) > abs(op2) | 
| Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1164 |             if op1.sign == 1: | 
 | 1165 |                 result.sign = 1 | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1166 |                 op1.sign, op2.sign = op2.sign, op1.sign | 
 | 1167 |             else: | 
| Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1168 |                 result.sign = 0 | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1169 |                 # So we know the sign, and op1 > 0. | 
| Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1170 |         elif op1.sign == 1: | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1171 |             result.sign = 1 | 
| Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1172 |             op1.sign, op2.sign = (0, 0) | 
 | 1173 |         else: | 
 | 1174 |             result.sign = 0 | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1175 |         # Now, op1 > abs(op2) > 0 | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1176 |  | 
| Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1177 |         if op2.sign == 0: | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1178 |             result.int = op1.int + op2.int | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1179 |         else: | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1180 |             result.int = op1.int - op2.int | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1181 |  | 
 | 1182 |         result.exp = op1.exp | 
 | 1183 |         ans = Decimal(result) | 
| Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1184 |         ans = ans._fix(context) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1185 |         return ans | 
 | 1186 |  | 
 | 1187 |     __radd__ = __add__ | 
 | 1188 |  | 
 | 1189 |     def __sub__(self, other, context=None): | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1190 |         """Return self - other""" | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1191 |         other = _convert_other(other) | 
| Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1192 |         if other is NotImplemented: | 
 | 1193 |             return other | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1194 |  | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1195 |         if self._is_special or other._is_special: | 
 | 1196 |             ans = self._check_nans(other, context=context) | 
 | 1197 |             if ans: | 
 | 1198 |                 return ans | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1199 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1200 |         # self - other is computed as self + other.copy_negate() | 
 | 1201 |         return self.__add__(other.copy_negate(), context=context) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1202 |  | 
 | 1203 |     def __rsub__(self, other, context=None): | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1204 |         """Return other - self""" | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1205 |         other = _convert_other(other) | 
| Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1206 |         if other is NotImplemented: | 
 | 1207 |             return other | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1208 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1209 |         return other.__sub__(self, context=context) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1210 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1211 |     def __mul__(self, other, context=None): | 
 | 1212 |         """Return self * other. | 
 | 1213 |  | 
 | 1214 |         (+-) INF * 0 (or its reverse) raise InvalidOperation. | 
 | 1215 |         """ | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1216 |         other = _convert_other(other) | 
| Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1217 |         if other is NotImplemented: | 
 | 1218 |             return other | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1219 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1220 |         if context is None: | 
 | 1221 |             context = getcontext() | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1222 |  | 
| Raymond Hettinger | d87ac8f | 2004-07-09 10:52:54 +0000 | [diff] [blame] | 1223 |         resultsign = self._sign ^ other._sign | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1224 |  | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1225 |         if self._is_special or other._is_special: | 
 | 1226 |             ans = self._check_nans(other, context) | 
 | 1227 |             if ans: | 
 | 1228 |                 return ans | 
 | 1229 |  | 
 | 1230 |             if self._isinfinity(): | 
 | 1231 |                 if not other: | 
 | 1232 |                     return context._raise_error(InvalidOperation, '(+-)INF * 0') | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 1233 |                 return _SignedInfinity[resultsign] | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1234 |  | 
 | 1235 |             if other._isinfinity(): | 
 | 1236 |                 if not self: | 
 | 1237 |                     return context._raise_error(InvalidOperation, '0 * (+-)INF') | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 1238 |                 return _SignedInfinity[resultsign] | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1239 |  | 
 | 1240 |         resultexp = self._exp + other._exp | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1241 |  | 
 | 1242 |         # Special case for multiplying by zero | 
 | 1243 |         if not self or not other: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1244 |             ans = _dec_from_triple(resultsign, '0', resultexp) | 
| Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1245 |             # Fixing in case the exponent is out of bounds | 
 | 1246 |             ans = ans._fix(context) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1247 |             return ans | 
 | 1248 |  | 
 | 1249 |         # Special case for multiplying by power of 10 | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1250 |         if self._int == '1': | 
 | 1251 |             ans = _dec_from_triple(resultsign, other._int, resultexp) | 
| Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1252 |             ans = ans._fix(context) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1253 |             return ans | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1254 |         if other._int == '1': | 
 | 1255 |             ans = _dec_from_triple(resultsign, self._int, resultexp) | 
| Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1256 |             ans = ans._fix(context) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1257 |             return ans | 
 | 1258 |  | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1259 |         op1 = _WorkRep(self) | 
 | 1260 |         op2 = _WorkRep(other) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1261 |  | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1262 |         ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp) | 
| Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1263 |         ans = ans._fix(context) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1264 |  | 
 | 1265 |         return ans | 
 | 1266 |     __rmul__ = __mul__ | 
 | 1267 |  | 
| Neal Norwitz | bcc0db8 | 2006-03-24 08:14:36 +0000 | [diff] [blame] | 1268 |     def __truediv__(self, other, context=None): | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1269 |         """Return self / other.""" | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1270 |         other = _convert_other(other) | 
| Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1271 |         if other is NotImplemented: | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1272 |             return NotImplemented | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1273 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1274 |         if context is None: | 
 | 1275 |             context = getcontext() | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1276 |  | 
| Raymond Hettinger | d87ac8f | 2004-07-09 10:52:54 +0000 | [diff] [blame] | 1277 |         sign = self._sign ^ other._sign | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1278 |  | 
 | 1279 |         if self._is_special or other._is_special: | 
 | 1280 |             ans = self._check_nans(other, context) | 
 | 1281 |             if ans: | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1282 |                 return ans | 
 | 1283 |  | 
 | 1284 |             if self._isinfinity() and other._isinfinity(): | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1285 |                 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF') | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1286 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1287 |             if self._isinfinity(): | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 1288 |                 return _SignedInfinity[sign] | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1289 |  | 
 | 1290 |             if other._isinfinity(): | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1291 |                 context._raise_error(Clamped, 'Division by infinity') | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1292 |                 return _dec_from_triple(sign, '0', context.Etiny()) | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1293 |  | 
 | 1294 |         # Special cases for zeroes | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1295 |         if not other: | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1296 |             if not self: | 
 | 1297 |                 return context._raise_error(DivisionUndefined, '0 / 0') | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1298 |             return context._raise_error(DivisionByZero, 'x / 0', sign) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1299 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1300 |         if not self: | 
 | 1301 |             exp = self._exp - other._exp | 
 | 1302 |             coeff = 0 | 
 | 1303 |         else: | 
 | 1304 |             # OK, so neither = 0, INF or NaN | 
 | 1305 |             shift = len(other._int) - len(self._int) + context.prec + 1 | 
 | 1306 |             exp = self._exp - other._exp - shift | 
 | 1307 |             op1 = _WorkRep(self) | 
 | 1308 |             op2 = _WorkRep(other) | 
 | 1309 |             if shift >= 0: | 
 | 1310 |                 coeff, remainder = divmod(op1.int * 10**shift, op2.int) | 
 | 1311 |             else: | 
 | 1312 |                 coeff, remainder = divmod(op1.int, op2.int * 10**-shift) | 
 | 1313 |             if remainder: | 
 | 1314 |                 # result is not exact; adjust to ensure correct rounding | 
 | 1315 |                 if coeff % 5 == 0: | 
 | 1316 |                     coeff += 1 | 
 | 1317 |             else: | 
 | 1318 |                 # result is exact; get as close to ideal exponent as possible | 
 | 1319 |                 ideal_exp = self._exp - other._exp | 
 | 1320 |                 while exp < ideal_exp and coeff % 10 == 0: | 
 | 1321 |                     coeff //= 10 | 
 | 1322 |                     exp += 1 | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1323 |  | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1324 |         ans = _dec_from_triple(sign, str(coeff), exp) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1325 |         return ans._fix(context) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1326 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1327 |     def _divide(self, other, context): | 
 | 1328 |         """Return (self // other, self % other), to context.prec precision. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1329 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1330 |         Assumes that neither self nor other is a NaN, that self is not | 
 | 1331 |         infinite and that other is nonzero. | 
 | 1332 |         """ | 
 | 1333 |         sign = self._sign ^ other._sign | 
 | 1334 |         if other._isinfinity(): | 
 | 1335 |             ideal_exp = self._exp | 
 | 1336 |         else: | 
 | 1337 |             ideal_exp = min(self._exp, other._exp) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1338 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1339 |         expdiff = self.adjusted() - other.adjusted() | 
 | 1340 |         if not self or other._isinfinity() or expdiff <= -2: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1341 |             return (_dec_from_triple(sign, '0', 0), | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1342 |                     self._rescale(ideal_exp, context.rounding)) | 
 | 1343 |         if expdiff <= context.prec: | 
 | 1344 |             op1 = _WorkRep(self) | 
 | 1345 |             op2 = _WorkRep(other) | 
 | 1346 |             if op1.exp >= op2.exp: | 
 | 1347 |                 op1.int *= 10**(op1.exp - op2.exp) | 
 | 1348 |             else: | 
 | 1349 |                 op2.int *= 10**(op2.exp - op1.exp) | 
 | 1350 |             q, r = divmod(op1.int, op2.int) | 
 | 1351 |             if q < 10**context.prec: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1352 |                 return (_dec_from_triple(sign, str(q), 0), | 
 | 1353 |                         _dec_from_triple(self._sign, str(r), ideal_exp)) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1354 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1355 |         # Here the quotient is too large to be representable | 
 | 1356 |         ans = context._raise_error(DivisionImpossible, | 
 | 1357 |                                    'quotient too large in //, % or divmod') | 
 | 1358 |         return ans, ans | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1359 |  | 
| Neal Norwitz | bcc0db8 | 2006-03-24 08:14:36 +0000 | [diff] [blame] | 1360 |     def __rtruediv__(self, other, context=None): | 
 | 1361 |         """Swaps self/other and returns __truediv__.""" | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1362 |         other = _convert_other(other) | 
| Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1363 |         if other is NotImplemented: | 
 | 1364 |             return other | 
| Neal Norwitz | bcc0db8 | 2006-03-24 08:14:36 +0000 | [diff] [blame] | 1365 |         return other.__truediv__(self, context=context) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1366 |  | 
 | 1367 |     def __divmod__(self, other, context=None): | 
 | 1368 |         """ | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1369 |         Return (self // other, self % other) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1370 |         """ | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1371 |         other = _convert_other(other) | 
 | 1372 |         if other is NotImplemented: | 
 | 1373 |             return other | 
 | 1374 |  | 
 | 1375 |         if context is None: | 
 | 1376 |             context = getcontext() | 
 | 1377 |  | 
 | 1378 |         ans = self._check_nans(other, context) | 
 | 1379 |         if ans: | 
 | 1380 |             return (ans, ans) | 
 | 1381 |  | 
 | 1382 |         sign = self._sign ^ other._sign | 
 | 1383 |         if self._isinfinity(): | 
 | 1384 |             if other._isinfinity(): | 
 | 1385 |                 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)') | 
 | 1386 |                 return ans, ans | 
 | 1387 |             else: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 1388 |                 return (_SignedInfinity[sign], | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1389 |                         context._raise_error(InvalidOperation, 'INF % x')) | 
 | 1390 |  | 
 | 1391 |         if not other: | 
 | 1392 |             if not self: | 
 | 1393 |                 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)') | 
 | 1394 |                 return ans, ans | 
 | 1395 |             else: | 
 | 1396 |                 return (context._raise_error(DivisionByZero, 'x // 0', sign), | 
 | 1397 |                         context._raise_error(InvalidOperation, 'x % 0')) | 
 | 1398 |  | 
 | 1399 |         quotient, remainder = self._divide(other, context) | 
| Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1400 |         remainder = remainder._fix(context) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1401 |         return quotient, remainder | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1402 |  | 
 | 1403 |     def __rdivmod__(self, other, context=None): | 
 | 1404 |         """Swaps self/other and returns __divmod__.""" | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1405 |         other = _convert_other(other) | 
| Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1406 |         if other is NotImplemented: | 
 | 1407 |             return other | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1408 |         return other.__divmod__(self, context=context) | 
 | 1409 |  | 
 | 1410 |     def __mod__(self, other, context=None): | 
 | 1411 |         """ | 
 | 1412 |         self % other | 
 | 1413 |         """ | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1414 |         other = _convert_other(other) | 
| Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1415 |         if other is NotImplemented: | 
 | 1416 |             return other | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1417 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1418 |         if context is None: | 
 | 1419 |             context = getcontext() | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1420 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1421 |         ans = self._check_nans(other, context) | 
 | 1422 |         if ans: | 
 | 1423 |             return ans | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1424 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1425 |         if self._isinfinity(): | 
 | 1426 |             return context._raise_error(InvalidOperation, 'INF % x') | 
 | 1427 |         elif not other: | 
 | 1428 |             if self: | 
 | 1429 |                 return context._raise_error(InvalidOperation, 'x % 0') | 
 | 1430 |             else: | 
 | 1431 |                 return context._raise_error(DivisionUndefined, '0 % 0') | 
 | 1432 |  | 
 | 1433 |         remainder = self._divide(other, context)[1] | 
| Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1434 |         remainder = remainder._fix(context) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1435 |         return remainder | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1436 |  | 
 | 1437 |     def __rmod__(self, other, context=None): | 
 | 1438 |         """Swaps self/other and returns __mod__.""" | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1439 |         other = _convert_other(other) | 
| Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1440 |         if other is NotImplemented: | 
 | 1441 |             return other | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1442 |         return other.__mod__(self, context=context) | 
 | 1443 |  | 
 | 1444 |     def remainder_near(self, other, context=None): | 
 | 1445 |         """ | 
 | 1446 |         Remainder nearest to 0-  abs(remainder-near) <= other/2 | 
 | 1447 |         """ | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1448 |         if context is None: | 
 | 1449 |             context = getcontext() | 
 | 1450 |  | 
 | 1451 |         other = _convert_other(other, raiseit=True) | 
 | 1452 |  | 
 | 1453 |         ans = self._check_nans(other, context) | 
 | 1454 |         if ans: | 
 | 1455 |             return ans | 
 | 1456 |  | 
 | 1457 |         # self == +/-infinity -> InvalidOperation | 
 | 1458 |         if self._isinfinity(): | 
 | 1459 |             return context._raise_error(InvalidOperation, | 
 | 1460 |                                         'remainder_near(infinity, x)') | 
 | 1461 |  | 
 | 1462 |         # other == 0 -> either InvalidOperation or DivisionUndefined | 
 | 1463 |         if not other: | 
 | 1464 |             if self: | 
 | 1465 |                 return context._raise_error(InvalidOperation, | 
 | 1466 |                                             'remainder_near(x, 0)') | 
 | 1467 |             else: | 
 | 1468 |                 return context._raise_error(DivisionUndefined, | 
 | 1469 |                                             'remainder_near(0, 0)') | 
 | 1470 |  | 
 | 1471 |         # other = +/-infinity -> remainder = self | 
 | 1472 |         if other._isinfinity(): | 
 | 1473 |             ans = Decimal(self) | 
 | 1474 |             return ans._fix(context) | 
 | 1475 |  | 
 | 1476 |         # self = 0 -> remainder = self, with ideal exponent | 
 | 1477 |         ideal_exponent = min(self._exp, other._exp) | 
 | 1478 |         if not self: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1479 |             ans = _dec_from_triple(self._sign, '0', ideal_exponent) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1480 |             return ans._fix(context) | 
 | 1481 |  | 
 | 1482 |         # catch most cases of large or small quotient | 
 | 1483 |         expdiff = self.adjusted() - other.adjusted() | 
 | 1484 |         if expdiff >= context.prec + 1: | 
 | 1485 |             # expdiff >= prec+1 => abs(self/other) > 10**prec | 
 | 1486 |             return context._raise_error(DivisionImpossible) | 
 | 1487 |         if expdiff <= -2: | 
 | 1488 |             # expdiff <= -2 => abs(self/other) < 0.1 | 
 | 1489 |             ans = self._rescale(ideal_exponent, context.rounding) | 
 | 1490 |             return ans._fix(context) | 
 | 1491 |  | 
 | 1492 |         # adjust both arguments to have the same exponent, then divide | 
 | 1493 |         op1 = _WorkRep(self) | 
 | 1494 |         op2 = _WorkRep(other) | 
 | 1495 |         if op1.exp >= op2.exp: | 
 | 1496 |             op1.int *= 10**(op1.exp - op2.exp) | 
 | 1497 |         else: | 
 | 1498 |             op2.int *= 10**(op2.exp - op1.exp) | 
 | 1499 |         q, r = divmod(op1.int, op2.int) | 
 | 1500 |         # remainder is r*10**ideal_exponent; other is +/-op2.int * | 
 | 1501 |         # 10**ideal_exponent.   Apply correction to ensure that | 
 | 1502 |         # abs(remainder) <= abs(other)/2 | 
 | 1503 |         if 2*r + (q&1) > op2.int: | 
 | 1504 |             r -= op2.int | 
 | 1505 |             q += 1 | 
 | 1506 |  | 
 | 1507 |         if q >= 10**context.prec: | 
 | 1508 |             return context._raise_error(DivisionImpossible) | 
 | 1509 |  | 
 | 1510 |         # result has same sign as self unless r is negative | 
 | 1511 |         sign = self._sign | 
 | 1512 |         if r < 0: | 
 | 1513 |             sign = 1-sign | 
 | 1514 |             r = -r | 
 | 1515 |  | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1516 |         ans = _dec_from_triple(sign, str(r), ideal_exponent) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1517 |         return ans._fix(context) | 
 | 1518 |  | 
 | 1519 |     def __floordiv__(self, other, context=None): | 
 | 1520 |         """self // other""" | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1521 |         other = _convert_other(other) | 
| Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1522 |         if other is NotImplemented: | 
 | 1523 |             return other | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1524 |  | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1525 |         if context is None: | 
 | 1526 |             context = getcontext() | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1527 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1528 |         ans = self._check_nans(other, context) | 
 | 1529 |         if ans: | 
 | 1530 |             return ans | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1531 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1532 |         if self._isinfinity(): | 
 | 1533 |             if other._isinfinity(): | 
 | 1534 |                 return context._raise_error(InvalidOperation, 'INF // INF') | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1535 |             else: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 1536 |                 return _SignedInfinity[self._sign ^ other._sign] | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1537 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1538 |         if not other: | 
 | 1539 |             if self: | 
 | 1540 |                 return context._raise_error(DivisionByZero, 'x // 0', | 
 | 1541 |                                             self._sign ^ other._sign) | 
 | 1542 |             else: | 
 | 1543 |                 return context._raise_error(DivisionUndefined, '0 // 0') | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1544 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1545 |         return self._divide(other, context)[0] | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1546 |  | 
 | 1547 |     def __rfloordiv__(self, other, context=None): | 
 | 1548 |         """Swaps self/other and returns __floordiv__.""" | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1549 |         other = _convert_other(other) | 
| Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1550 |         if other is NotImplemented: | 
 | 1551 |             return other | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1552 |         return other.__floordiv__(self, context=context) | 
 | 1553 |  | 
 | 1554 |     def __float__(self): | 
 | 1555 |         """Float representation.""" | 
 | 1556 |         return float(str(self)) | 
 | 1557 |  | 
 | 1558 |     def __int__(self): | 
| Brett Cannon | 46b0802 | 2005-03-01 03:12:26 +0000 | [diff] [blame] | 1559 |         """Converts self to an int, truncating if necessary.""" | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1560 |         if self._is_special: | 
 | 1561 |             if self._isnan(): | 
 | 1562 |                 context = getcontext() | 
 | 1563 |                 return context._raise_error(InvalidContext) | 
 | 1564 |             elif self._isinfinity(): | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1565 |                 raise OverflowError("Cannot convert infinity to int") | 
 | 1566 |         s = (-1)**self._sign | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1567 |         if self._exp >= 0: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1568 |             return s*int(self._int)*10**self._exp | 
| Raymond Hettinger | 605ed02 | 2004-11-24 07:28:48 +0000 | [diff] [blame] | 1569 |         else: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1570 |             return s*int(self._int[:self._exp] or '0') | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1571 |  | 
| Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 1572 |     __trunc__ = __int__ | 
 | 1573 |  | 
| Christian Heimes | 0bd4e11 | 2008-02-12 22:59:25 +0000 | [diff] [blame] | 1574 |     def real(self): | 
 | 1575 |         return self | 
| Mark Dickinson | 315a20a | 2009-01-04 21:34:18 +0000 | [diff] [blame] | 1576 |     real = property(real) | 
| Christian Heimes | 0bd4e11 | 2008-02-12 22:59:25 +0000 | [diff] [blame] | 1577 |  | 
| Christian Heimes | 0bd4e11 | 2008-02-12 22:59:25 +0000 | [diff] [blame] | 1578 |     def imag(self): | 
 | 1579 |         return Decimal(0) | 
| Mark Dickinson | 315a20a | 2009-01-04 21:34:18 +0000 | [diff] [blame] | 1580 |     imag = property(imag) | 
| Christian Heimes | 0bd4e11 | 2008-02-12 22:59:25 +0000 | [diff] [blame] | 1581 |  | 
 | 1582 |     def conjugate(self): | 
 | 1583 |         return self | 
 | 1584 |  | 
 | 1585 |     def __complex__(self): | 
 | 1586 |         return complex(float(self)) | 
 | 1587 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1588 |     def _fix_nan(self, context): | 
 | 1589 |         """Decapitate the payload of a NaN to fit the context""" | 
 | 1590 |         payload = self._int | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1591 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1592 |         # maximum length of payload is precision if _clamp=0, | 
 | 1593 |         # precision-1 if _clamp=1. | 
 | 1594 |         max_payload_len = context.prec - context._clamp | 
 | 1595 |         if len(payload) > max_payload_len: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1596 |             payload = payload[len(payload)-max_payload_len:].lstrip('0') | 
 | 1597 |             return _dec_from_triple(self._sign, payload, self._exp, True) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1598 |         return Decimal(self) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1599 |  | 
| Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1600 |     def _fix(self, context): | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1601 |         """Round if it is necessary to keep self within prec precision. | 
 | 1602 |  | 
 | 1603 |         Rounds and fixes the exponent.  Does not raise on a sNaN. | 
 | 1604 |  | 
 | 1605 |         Arguments: | 
 | 1606 |         self - Decimal instance | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1607 |         context - context used. | 
 | 1608 |         """ | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1609 |  | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1610 |         if self._is_special: | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1611 |             if self._isnan(): | 
 | 1612 |                 # decapitate payload if necessary | 
 | 1613 |                 return self._fix_nan(context) | 
 | 1614 |             else: | 
 | 1615 |                 # self is +/-Infinity; return unaltered | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1616 |                 return Decimal(self) | 
 | 1617 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1618 |         # if self is zero then exponent should be between Etiny and | 
 | 1619 |         # Emax if _clamp==0, and between Etiny and Etop if _clamp==1. | 
 | 1620 |         Etiny = context.Etiny() | 
 | 1621 |         Etop = context.Etop() | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1622 |         if not self: | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1623 |             exp_max = [context.Emax, Etop][context._clamp] | 
 | 1624 |             new_exp = min(max(self._exp, Etiny), exp_max) | 
 | 1625 |             if new_exp != self._exp: | 
 | 1626 |                 context._raise_error(Clamped) | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1627 |                 return _dec_from_triple(self._sign, '0', new_exp) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1628 |             else: | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1629 |                 return Decimal(self) | 
 | 1630 |  | 
 | 1631 |         # exp_min is the smallest allowable exponent of the result, | 
 | 1632 |         # equal to max(self.adjusted()-context.prec+1, Etiny) | 
 | 1633 |         exp_min = len(self._int) + self._exp - context.prec | 
 | 1634 |         if exp_min > Etop: | 
 | 1635 |             # overflow: exp_min > Etop iff self.adjusted() > Emax | 
 | 1636 |             context._raise_error(Inexact) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1637 |             context._raise_error(Rounded) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1638 |             return context._raise_error(Overflow, 'above Emax', self._sign) | 
 | 1639 |         self_is_subnormal = exp_min < Etiny | 
 | 1640 |         if self_is_subnormal: | 
 | 1641 |             context._raise_error(Subnormal) | 
 | 1642 |             exp_min = Etiny | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1643 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1644 |         # round if self has too many digits | 
 | 1645 |         if self._exp < exp_min: | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1646 |             context._raise_error(Rounded) | 
| Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1647 |             digits = len(self._int) + self._exp - exp_min | 
 | 1648 |             if digits < 0: | 
 | 1649 |                 self = _dec_from_triple(self._sign, '1', exp_min-1) | 
 | 1650 |                 digits = 0 | 
 | 1651 |             this_function = getattr(self, self._pick_rounding_function[context.rounding]) | 
 | 1652 |             changed = this_function(digits) | 
 | 1653 |             coeff = self._int[:digits] or '0' | 
 | 1654 |             if changed == 1: | 
 | 1655 |                 coeff = str(int(coeff)+1) | 
 | 1656 |             ans = _dec_from_triple(self._sign, coeff, exp_min) | 
 | 1657 |  | 
 | 1658 |             if changed: | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1659 |                 context._raise_error(Inexact) | 
 | 1660 |                 if self_is_subnormal: | 
 | 1661 |                     context._raise_error(Underflow) | 
 | 1662 |                     if not ans: | 
 | 1663 |                         # raise Clamped on underflow to 0 | 
 | 1664 |                         context._raise_error(Clamped) | 
 | 1665 |                 elif len(ans._int) == context.prec+1: | 
 | 1666 |                     # we get here only if rescaling rounds the | 
 | 1667 |                     # cofficient up to exactly 10**context.prec | 
 | 1668 |                     if ans._exp < Etop: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1669 |                         ans = _dec_from_triple(ans._sign, | 
 | 1670 |                                                    ans._int[:-1], ans._exp+1) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1671 |                     else: | 
 | 1672 |                         # Inexact and Rounded have already been raised | 
 | 1673 |                         ans = context._raise_error(Overflow, 'above Emax', | 
 | 1674 |                                                    self._sign) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1675 |             return ans | 
 | 1676 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1677 |         # fold down if _clamp == 1 and self has too few digits | 
 | 1678 |         if context._clamp == 1 and self._exp > Etop: | 
 | 1679 |             context._raise_error(Clamped) | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1680 |             self_padded = self._int + '0'*(self._exp - Etop) | 
 | 1681 |             return _dec_from_triple(self._sign, self_padded, Etop) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1682 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1683 |         # here self was representable to begin with; return unchanged | 
 | 1684 |         return Decimal(self) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1685 |  | 
 | 1686 |     _pick_rounding_function = {} | 
 | 1687 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1688 |     # for each of the rounding functions below: | 
 | 1689 |     #   self is a finite, nonzero Decimal | 
 | 1690 |     #   prec is an integer satisfying 0 <= prec < len(self._int) | 
| Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1691 |     # | 
 | 1692 |     # each function returns either -1, 0, or 1, as follows: | 
 | 1693 |     #   1 indicates that self should be rounded up (away from zero) | 
 | 1694 |     #   0 indicates that self should be truncated, and that all the | 
 | 1695 |     #     digits to be truncated are zeros (so the value is unchanged) | 
 | 1696 |     #  -1 indicates that there are nonzero digits to be truncated | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1697 |  | 
 | 1698 |     def _round_down(self, prec): | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1699 |         """Also known as round-towards-0, truncate.""" | 
| Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1700 |         if _all_zeros(self._int, prec): | 
 | 1701 |             return 0 | 
 | 1702 |         else: | 
 | 1703 |             return -1 | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1704 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1705 |     def _round_up(self, prec): | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1706 |         """Rounds away from 0.""" | 
| Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1707 |         return -self._round_down(prec) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1708 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1709 |     def _round_half_up(self, prec): | 
 | 1710 |         """Rounds 5 up (away from 0)""" | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1711 |         if self._int[prec] in '56789': | 
| Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1712 |             return 1 | 
 | 1713 |         elif _all_zeros(self._int, prec): | 
 | 1714 |             return 0 | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1715 |         else: | 
| Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1716 |             return -1 | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1717 |  | 
 | 1718 |     def _round_half_down(self, prec): | 
 | 1719 |         """Round 5 down""" | 
| Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1720 |         if _exact_half(self._int, prec): | 
 | 1721 |             return -1 | 
 | 1722 |         else: | 
 | 1723 |             return self._round_half_up(prec) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1724 |  | 
 | 1725 |     def _round_half_even(self, prec): | 
 | 1726 |         """Round 5 to even, rest to nearest.""" | 
| Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1727 |         if _exact_half(self._int, prec) and \ | 
 | 1728 |                 (prec == 0 or self._int[prec-1] in '02468'): | 
 | 1729 |             return -1 | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1730 |         else: | 
| Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1731 |             return self._round_half_up(prec) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1732 |  | 
 | 1733 |     def _round_ceiling(self, prec): | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1734 |         """Rounds up (not away from 0 if negative.)""" | 
 | 1735 |         if self._sign: | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1736 |             return self._round_down(prec) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1737 |         else: | 
| Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1738 |             return -self._round_down(prec) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1739 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1740 |     def _round_floor(self, prec): | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1741 |         """Rounds down (not towards 0 if negative)""" | 
 | 1742 |         if not self._sign: | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1743 |             return self._round_down(prec) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1744 |         else: | 
| Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1745 |             return -self._round_down(prec) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1746 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1747 |     def _round_05up(self, prec): | 
 | 1748 |         """Round down unless digit prec-1 is 0 or 5.""" | 
| Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1749 |         if prec and self._int[prec-1] not in '05': | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1750 |             return self._round_down(prec) | 
| Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1751 |         else: | 
 | 1752 |             return -self._round_down(prec) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1753 |  | 
| Mark Dickinson | b27406c | 2008-05-09 13:42:33 +0000 | [diff] [blame] | 1754 |     def __round__(self, n=None): | 
 | 1755 |         """Round self to the nearest integer, or to a given precision. | 
 | 1756 |  | 
 | 1757 |         If only one argument is supplied, round a finite Decimal | 
 | 1758 |         instance self to the nearest integer.  If self is infinite or | 
 | 1759 |         a NaN then a Python exception is raised.  If self is finite | 
 | 1760 |         and lies exactly halfway between two integers then it is | 
 | 1761 |         rounded to the integer with even last digit. | 
 | 1762 |  | 
 | 1763 |         >>> round(Decimal('123.456')) | 
 | 1764 |         123 | 
 | 1765 |         >>> round(Decimal('-456.789')) | 
 | 1766 |         -457 | 
 | 1767 |         >>> round(Decimal('-3.0')) | 
 | 1768 |         -3 | 
 | 1769 |         >>> round(Decimal('2.5')) | 
 | 1770 |         2 | 
 | 1771 |         >>> round(Decimal('3.5')) | 
 | 1772 |         4 | 
 | 1773 |         >>> round(Decimal('Inf')) | 
 | 1774 |         Traceback (most recent call last): | 
 | 1775 |           ... | 
| Mark Dickinson | b27406c | 2008-05-09 13:42:33 +0000 | [diff] [blame] | 1776 |         OverflowError: cannot round an infinity | 
 | 1777 |         >>> round(Decimal('NaN')) | 
 | 1778 |         Traceback (most recent call last): | 
 | 1779 |           ... | 
| Mark Dickinson | b27406c | 2008-05-09 13:42:33 +0000 | [diff] [blame] | 1780 |         ValueError: cannot round a NaN | 
 | 1781 |  | 
 | 1782 |         If a second argument n is supplied, self is rounded to n | 
 | 1783 |         decimal places using the rounding mode for the current | 
 | 1784 |         context. | 
 | 1785 |  | 
 | 1786 |         For an integer n, round(self, -n) is exactly equivalent to | 
 | 1787 |         self.quantize(Decimal('1En')). | 
 | 1788 |  | 
 | 1789 |         >>> round(Decimal('123.456'), 0) | 
 | 1790 |         Decimal('123') | 
 | 1791 |         >>> round(Decimal('123.456'), 2) | 
 | 1792 |         Decimal('123.46') | 
 | 1793 |         >>> round(Decimal('123.456'), -2) | 
 | 1794 |         Decimal('1E+2') | 
 | 1795 |         >>> round(Decimal('-Infinity'), 37) | 
 | 1796 |         Decimal('NaN') | 
 | 1797 |         >>> round(Decimal('sNaN123'), 0) | 
 | 1798 |         Decimal('NaN123') | 
 | 1799 |  | 
 | 1800 |         """ | 
 | 1801 |         if n is not None: | 
 | 1802 |             # two-argument form: use the equivalent quantize call | 
 | 1803 |             if not isinstance(n, int): | 
 | 1804 |                 raise TypeError('Second argument to round should be integral') | 
 | 1805 |             exp = _dec_from_triple(0, '1', -n) | 
 | 1806 |             return self.quantize(exp) | 
 | 1807 |  | 
 | 1808 |         # one-argument form | 
 | 1809 |         if self._is_special: | 
 | 1810 |             if self.is_nan(): | 
 | 1811 |                 raise ValueError("cannot round a NaN") | 
 | 1812 |             else: | 
 | 1813 |                 raise OverflowError("cannot round an infinity") | 
 | 1814 |         return int(self._rescale(0, ROUND_HALF_EVEN)) | 
 | 1815 |  | 
 | 1816 |     def __floor__(self): | 
 | 1817 |         """Return the floor of self, as an integer. | 
 | 1818 |  | 
 | 1819 |         For a finite Decimal instance self, return the greatest | 
 | 1820 |         integer n such that n <= self.  If self is infinite or a NaN | 
 | 1821 |         then a Python exception is raised. | 
 | 1822 |  | 
 | 1823 |         """ | 
 | 1824 |         if self._is_special: | 
 | 1825 |             if self.is_nan(): | 
 | 1826 |                 raise ValueError("cannot round a NaN") | 
 | 1827 |             else: | 
 | 1828 |                 raise OverflowError("cannot round an infinity") | 
 | 1829 |         return int(self._rescale(0, ROUND_FLOOR)) | 
 | 1830 |  | 
 | 1831 |     def __ceil__(self): | 
 | 1832 |         """Return the ceiling of self, as an integer. | 
 | 1833 |  | 
 | 1834 |         For a finite Decimal instance self, return the least integer n | 
 | 1835 |         such that n >= self.  If self is infinite or a NaN then a | 
 | 1836 |         Python exception is raised. | 
 | 1837 |  | 
 | 1838 |         """ | 
 | 1839 |         if self._is_special: | 
 | 1840 |             if self.is_nan(): | 
 | 1841 |                 raise ValueError("cannot round a NaN") | 
 | 1842 |             else: | 
 | 1843 |                 raise OverflowError("cannot round an infinity") | 
 | 1844 |         return int(self._rescale(0, ROUND_CEILING)) | 
 | 1845 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1846 |     def fma(self, other, third, context=None): | 
 | 1847 |         """Fused multiply-add. | 
 | 1848 |  | 
 | 1849 |         Returns self*other+third with no rounding of the intermediate | 
 | 1850 |         product self*other. | 
 | 1851 |  | 
 | 1852 |         self and other are multiplied together, with no rounding of | 
 | 1853 |         the result.  The third operand is then added to the result, | 
 | 1854 |         and a single final rounding is performed. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1855 |         """ | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1856 |  | 
 | 1857 |         other = _convert_other(other, raiseit=True) | 
| Christian Heimes | 8b0facf | 2007-12-04 19:30:01 +0000 | [diff] [blame] | 1858 |  | 
 | 1859 |         # compute product; raise InvalidOperation if either operand is | 
 | 1860 |         # a signaling NaN or if the product is zero times infinity. | 
 | 1861 |         if self._is_special or other._is_special: | 
 | 1862 |             if context is None: | 
 | 1863 |                 context = getcontext() | 
 | 1864 |             if self._exp == 'N': | 
| Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 1865 |                 return context._raise_error(InvalidOperation, 'sNaN', self) | 
| Christian Heimes | 8b0facf | 2007-12-04 19:30:01 +0000 | [diff] [blame] | 1866 |             if other._exp == 'N': | 
| Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 1867 |                 return context._raise_error(InvalidOperation, 'sNaN', other) | 
| Christian Heimes | 8b0facf | 2007-12-04 19:30:01 +0000 | [diff] [blame] | 1868 |             if self._exp == 'n': | 
 | 1869 |                 product = self | 
 | 1870 |             elif other._exp == 'n': | 
 | 1871 |                 product = other | 
 | 1872 |             elif self._exp == 'F': | 
 | 1873 |                 if not other: | 
 | 1874 |                     return context._raise_error(InvalidOperation, | 
 | 1875 |                                                 'INF * 0 in fma') | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 1876 |                 product = _SignedInfinity[self._sign ^ other._sign] | 
| Christian Heimes | 8b0facf | 2007-12-04 19:30:01 +0000 | [diff] [blame] | 1877 |             elif other._exp == 'F': | 
 | 1878 |                 if not self: | 
 | 1879 |                     return context._raise_error(InvalidOperation, | 
 | 1880 |                                                 '0 * INF in fma') | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 1881 |                 product = _SignedInfinity[self._sign ^ other._sign] | 
| Christian Heimes | 8b0facf | 2007-12-04 19:30:01 +0000 | [diff] [blame] | 1882 |         else: | 
 | 1883 |             product = _dec_from_triple(self._sign ^ other._sign, | 
 | 1884 |                                        str(int(self._int) * int(other._int)), | 
 | 1885 |                                        self._exp + other._exp) | 
 | 1886 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1887 |         third = _convert_other(third, raiseit=True) | 
| Christian Heimes | 8b0facf | 2007-12-04 19:30:01 +0000 | [diff] [blame] | 1888 |         return product.__add__(third, context) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1889 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1890 |     def _power_modulo(self, other, modulo, context=None): | 
 | 1891 |         """Three argument version of __pow__""" | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1892 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1893 |         # if can't convert other and modulo to Decimal, raise | 
 | 1894 |         # TypeError; there's no point returning NotImplemented (no | 
 | 1895 |         # equivalent of __rpow__ for three argument pow) | 
 | 1896 |         other = _convert_other(other, raiseit=True) | 
 | 1897 |         modulo = _convert_other(modulo, raiseit=True) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1898 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1899 |         if context is None: | 
 | 1900 |             context = getcontext() | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1901 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1902 |         # deal with NaNs: if there are any sNaNs then first one wins, | 
 | 1903 |         # (i.e. behaviour for NaNs is identical to that of fma) | 
 | 1904 |         self_is_nan = self._isnan() | 
 | 1905 |         other_is_nan = other._isnan() | 
 | 1906 |         modulo_is_nan = modulo._isnan() | 
 | 1907 |         if self_is_nan or other_is_nan or modulo_is_nan: | 
 | 1908 |             if self_is_nan == 2: | 
 | 1909 |                 return context._raise_error(InvalidOperation, 'sNaN', | 
| Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 1910 |                                         self) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1911 |             if other_is_nan == 2: | 
 | 1912 |                 return context._raise_error(InvalidOperation, 'sNaN', | 
| Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 1913 |                                         other) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1914 |             if modulo_is_nan == 2: | 
 | 1915 |                 return context._raise_error(InvalidOperation, 'sNaN', | 
| Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 1916 |                                         modulo) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1917 |             if self_is_nan: | 
 | 1918 |                 return self._fix_nan(context) | 
 | 1919 |             if other_is_nan: | 
 | 1920 |                 return other._fix_nan(context) | 
 | 1921 |             return modulo._fix_nan(context) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1922 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1923 |         # check inputs: we apply same restrictions as Python's pow() | 
 | 1924 |         if not (self._isinteger() and | 
 | 1925 |                 other._isinteger() and | 
 | 1926 |                 modulo._isinteger()): | 
 | 1927 |             return context._raise_error(InvalidOperation, | 
 | 1928 |                                         'pow() 3rd argument not allowed ' | 
 | 1929 |                                         'unless all arguments are integers') | 
 | 1930 |         if other < 0: | 
 | 1931 |             return context._raise_error(InvalidOperation, | 
 | 1932 |                                         'pow() 2nd argument cannot be ' | 
 | 1933 |                                         'negative when 3rd argument specified') | 
 | 1934 |         if not modulo: | 
 | 1935 |             return context._raise_error(InvalidOperation, | 
 | 1936 |                                         'pow() 3rd argument cannot be 0') | 
 | 1937 |  | 
 | 1938 |         # additional restriction for decimal: the modulus must be less | 
 | 1939 |         # than 10**prec in absolute value | 
 | 1940 |         if modulo.adjusted() >= context.prec: | 
 | 1941 |             return context._raise_error(InvalidOperation, | 
 | 1942 |                                         'insufficient precision: pow() 3rd ' | 
 | 1943 |                                         'argument must not have more than ' | 
 | 1944 |                                         'precision digits') | 
 | 1945 |  | 
 | 1946 |         # define 0**0 == NaN, for consistency with two-argument pow | 
 | 1947 |         # (even though it hurts!) | 
 | 1948 |         if not other and not self: | 
 | 1949 |             return context._raise_error(InvalidOperation, | 
 | 1950 |                                         'at least one of pow() 1st argument ' | 
 | 1951 |                                         'and 2nd argument must be nonzero ;' | 
 | 1952 |                                         '0**0 is not defined') | 
 | 1953 |  | 
 | 1954 |         # compute sign of result | 
 | 1955 |         if other._iseven(): | 
 | 1956 |             sign = 0 | 
 | 1957 |         else: | 
 | 1958 |             sign = self._sign | 
 | 1959 |  | 
 | 1960 |         # convert modulo to a Python integer, and self and other to | 
 | 1961 |         # Decimal integers (i.e. force their exponents to be >= 0) | 
 | 1962 |         modulo = abs(int(modulo)) | 
 | 1963 |         base = _WorkRep(self.to_integral_value()) | 
 | 1964 |         exponent = _WorkRep(other.to_integral_value()) | 
 | 1965 |  | 
 | 1966 |         # compute result using integer pow() | 
 | 1967 |         base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo | 
 | 1968 |         for i in range(exponent.exp): | 
 | 1969 |             base = pow(base, 10, modulo) | 
 | 1970 |         base = pow(base, exponent.int, modulo) | 
 | 1971 |  | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1972 |         return _dec_from_triple(sign, str(base), 0) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1973 |  | 
 | 1974 |     def _power_exact(self, other, p): | 
 | 1975 |         """Attempt to compute self**other exactly. | 
 | 1976 |  | 
 | 1977 |         Given Decimals self and other and an integer p, attempt to | 
 | 1978 |         compute an exact result for the power self**other, with p | 
 | 1979 |         digits of precision.  Return None if self**other is not | 
 | 1980 |         exactly representable in p digits. | 
 | 1981 |  | 
 | 1982 |         Assumes that elimination of special cases has already been | 
 | 1983 |         performed: self and other must both be nonspecial; self must | 
 | 1984 |         be positive and not numerically equal to 1; other must be | 
 | 1985 |         nonzero.  For efficiency, other._exp should not be too large, | 
 | 1986 |         so that 10**abs(other._exp) is a feasible calculation.""" | 
 | 1987 |  | 
 | 1988 |         # In the comments below, we write x for the value of self and | 
 | 1989 |         # y for the value of other.  Write x = xc*10**xe and y = | 
 | 1990 |         # yc*10**ye. | 
 | 1991 |  | 
 | 1992 |         # The main purpose of this method is to identify the *failure* | 
 | 1993 |         # of x**y to be exactly representable with as little effort as | 
 | 1994 |         # possible.  So we look for cheap and easy tests that | 
 | 1995 |         # eliminate the possibility of x**y being exact.  Only if all | 
 | 1996 |         # these tests are passed do we go on to actually compute x**y. | 
 | 1997 |  | 
 | 1998 |         # Here's the main idea.  First normalize both x and y.  We | 
 | 1999 |         # express y as a rational m/n, with m and n relatively prime | 
 | 2000 |         # and n>0.  Then for x**y to be exactly representable (at | 
 | 2001 |         # *any* precision), xc must be the nth power of a positive | 
 | 2002 |         # integer and xe must be divisible by n.  If m is negative | 
 | 2003 |         # then additionally xc must be a power of either 2 or 5, hence | 
 | 2004 |         # a power of 2**n or 5**n. | 
 | 2005 |         # | 
 | 2006 |         # There's a limit to how small |y| can be: if y=m/n as above | 
 | 2007 |         # then: | 
 | 2008 |         # | 
 | 2009 |         #  (1) if xc != 1 then for the result to be representable we | 
 | 2010 |         #      need xc**(1/n) >= 2, and hence also xc**|y| >= 2.  So | 
 | 2011 |         #      if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <= | 
 | 2012 |         #      2**(1/|y|), hence xc**|y| < 2 and the result is not | 
 | 2013 |         #      representable. | 
 | 2014 |         # | 
 | 2015 |         #  (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1.  Hence if | 
 | 2016 |         #      |y| < 1/|xe| then the result is not representable. | 
 | 2017 |         # | 
 | 2018 |         # Note that since x is not equal to 1, at least one of (1) and | 
 | 2019 |         # (2) must apply.  Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) < | 
 | 2020 |         # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye. | 
 | 2021 |         # | 
 | 2022 |         # There's also a limit to how large y can be, at least if it's | 
 | 2023 |         # positive: the normalized result will have coefficient xc**y, | 
 | 2024 |         # so if it's representable then xc**y < 10**p, and y < | 
 | 2025 |         # p/log10(xc).  Hence if y*log10(xc) >= p then the result is | 
 | 2026 |         # not exactly representable. | 
 | 2027 |  | 
 | 2028 |         # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye, | 
 | 2029 |         # so |y| < 1/xe and the result is not representable. | 
 | 2030 |         # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y| | 
 | 2031 |         # < 1/nbits(xc). | 
 | 2032 |  | 
 | 2033 |         x = _WorkRep(self) | 
 | 2034 |         xc, xe = x.int, x.exp | 
 | 2035 |         while xc % 10 == 0: | 
 | 2036 |             xc //= 10 | 
 | 2037 |             xe += 1 | 
 | 2038 |  | 
 | 2039 |         y = _WorkRep(other) | 
 | 2040 |         yc, ye = y.int, y.exp | 
 | 2041 |         while yc % 10 == 0: | 
 | 2042 |             yc //= 10 | 
 | 2043 |             ye += 1 | 
 | 2044 |  | 
 | 2045 |         # case where xc == 1: result is 10**(xe*y), with xe*y | 
 | 2046 |         # required to be an integer | 
 | 2047 |         if xc == 1: | 
 | 2048 |             if ye >= 0: | 
 | 2049 |                 exponent = xe*yc*10**ye | 
 | 2050 |             else: | 
 | 2051 |                 exponent, remainder = divmod(xe*yc, 10**-ye) | 
 | 2052 |                 if remainder: | 
 | 2053 |                     return None | 
 | 2054 |             if y.sign == 1: | 
 | 2055 |                 exponent = -exponent | 
 | 2056 |             # if other is a nonnegative integer, use ideal exponent | 
 | 2057 |             if other._isinteger() and other._sign == 0: | 
 | 2058 |                 ideal_exponent = self._exp*int(other) | 
 | 2059 |                 zeros = min(exponent-ideal_exponent, p-1) | 
 | 2060 |             else: | 
 | 2061 |                 zeros = 0 | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2062 |             return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2063 |  | 
 | 2064 |         # case where y is negative: xc must be either a power | 
 | 2065 |         # of 2 or a power of 5. | 
 | 2066 |         if y.sign == 1: | 
 | 2067 |             last_digit = xc % 10 | 
 | 2068 |             if last_digit in (2,4,6,8): | 
 | 2069 |                 # quick test for power of 2 | 
 | 2070 |                 if xc & -xc != xc: | 
 | 2071 |                     return None | 
 | 2072 |                 # now xc is a power of 2; e is its exponent | 
 | 2073 |                 e = _nbits(xc)-1 | 
 | 2074 |                 # find e*y and xe*y; both must be integers | 
 | 2075 |                 if ye >= 0: | 
 | 2076 |                     y_as_int = yc*10**ye | 
 | 2077 |                     e = e*y_as_int | 
 | 2078 |                     xe = xe*y_as_int | 
 | 2079 |                 else: | 
 | 2080 |                     ten_pow = 10**-ye | 
 | 2081 |                     e, remainder = divmod(e*yc, ten_pow) | 
 | 2082 |                     if remainder: | 
 | 2083 |                         return None | 
 | 2084 |                     xe, remainder = divmod(xe*yc, ten_pow) | 
 | 2085 |                     if remainder: | 
 | 2086 |                         return None | 
 | 2087 |  | 
 | 2088 |                 if e*65 >= p*93: # 93/65 > log(10)/log(5) | 
 | 2089 |                     return None | 
 | 2090 |                 xc = 5**e | 
 | 2091 |  | 
 | 2092 |             elif last_digit == 5: | 
 | 2093 |                 # e >= log_5(xc) if xc is a power of 5; we have | 
 | 2094 |                 # equality all the way up to xc=5**2658 | 
 | 2095 |                 e = _nbits(xc)*28//65 | 
 | 2096 |                 xc, remainder = divmod(5**e, xc) | 
 | 2097 |                 if remainder: | 
 | 2098 |                     return None | 
 | 2099 |                 while xc % 5 == 0: | 
 | 2100 |                     xc //= 5 | 
 | 2101 |                     e -= 1 | 
 | 2102 |                 if ye >= 0: | 
 | 2103 |                     y_as_integer = yc*10**ye | 
 | 2104 |                     e = e*y_as_integer | 
 | 2105 |                     xe = xe*y_as_integer | 
 | 2106 |                 else: | 
 | 2107 |                     ten_pow = 10**-ye | 
 | 2108 |                     e, remainder = divmod(e*yc, ten_pow) | 
 | 2109 |                     if remainder: | 
 | 2110 |                         return None | 
 | 2111 |                     xe, remainder = divmod(xe*yc, ten_pow) | 
 | 2112 |                     if remainder: | 
 | 2113 |                         return None | 
 | 2114 |                 if e*3 >= p*10: # 10/3 > log(10)/log(2) | 
 | 2115 |                     return None | 
 | 2116 |                 xc = 2**e | 
 | 2117 |             else: | 
 | 2118 |                 return None | 
 | 2119 |  | 
 | 2120 |             if xc >= 10**p: | 
 | 2121 |                 return None | 
 | 2122 |             xe = -e-xe | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2123 |             return _dec_from_triple(0, str(xc), xe) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2124 |  | 
 | 2125 |         # now y is positive; find m and n such that y = m/n | 
 | 2126 |         if ye >= 0: | 
 | 2127 |             m, n = yc*10**ye, 1 | 
 | 2128 |         else: | 
 | 2129 |             if xe != 0 and len(str(abs(yc*xe))) <= -ye: | 
 | 2130 |                 return None | 
 | 2131 |             xc_bits = _nbits(xc) | 
 | 2132 |             if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye: | 
 | 2133 |                 return None | 
 | 2134 |             m, n = yc, 10**(-ye) | 
 | 2135 |             while m % 2 == n % 2 == 0: | 
 | 2136 |                 m //= 2 | 
 | 2137 |                 n //= 2 | 
 | 2138 |             while m % 5 == n % 5 == 0: | 
 | 2139 |                 m //= 5 | 
 | 2140 |                 n //= 5 | 
 | 2141 |  | 
 | 2142 |         # compute nth root of xc*10**xe | 
 | 2143 |         if n > 1: | 
 | 2144 |             # if 1 < xc < 2**n then xc isn't an nth power | 
 | 2145 |             if xc != 1 and xc_bits <= n: | 
 | 2146 |                 return None | 
 | 2147 |  | 
 | 2148 |             xe, rem = divmod(xe, n) | 
 | 2149 |             if rem != 0: | 
 | 2150 |                 return None | 
 | 2151 |  | 
 | 2152 |             # compute nth root of xc using Newton's method | 
 | 2153 |             a = 1 << -(-_nbits(xc)//n) # initial estimate | 
 | 2154 |             while True: | 
 | 2155 |                 q, r = divmod(xc, a**(n-1)) | 
 | 2156 |                 if a <= q: | 
 | 2157 |                     break | 
 | 2158 |                 else: | 
 | 2159 |                     a = (a*(n-1) + q)//n | 
 | 2160 |             if not (a == q and r == 0): | 
 | 2161 |                 return None | 
 | 2162 |             xc = a | 
 | 2163 |  | 
 | 2164 |         # now xc*10**xe is the nth root of the original xc*10**xe | 
 | 2165 |         # compute mth power of xc*10**xe | 
 | 2166 |  | 
 | 2167 |         # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m > | 
 | 2168 |         # 10**p and the result is not representable. | 
 | 2169 |         if xc > 1 and m > p*100//_log10_lb(xc): | 
 | 2170 |             return None | 
 | 2171 |         xc = xc**m | 
 | 2172 |         xe *= m | 
 | 2173 |         if xc > 10**p: | 
 | 2174 |             return None | 
 | 2175 |  | 
 | 2176 |         # by this point the result *is* exactly representable | 
 | 2177 |         # adjust the exponent to get as close as possible to the ideal | 
 | 2178 |         # exponent, if necessary | 
 | 2179 |         str_xc = str(xc) | 
 | 2180 |         if other._isinteger() and other._sign == 0: | 
 | 2181 |             ideal_exponent = self._exp*int(other) | 
 | 2182 |             zeros = min(xe-ideal_exponent, p-len(str_xc)) | 
 | 2183 |         else: | 
 | 2184 |             zeros = 0 | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2185 |         return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2186 |  | 
 | 2187 |     def __pow__(self, other, modulo=None, context=None): | 
 | 2188 |         """Return self ** other [ % modulo]. | 
 | 2189 |  | 
 | 2190 |         With two arguments, compute self**other. | 
 | 2191 |  | 
 | 2192 |         With three arguments, compute (self**other) % modulo.  For the | 
 | 2193 |         three argument form, the following restrictions on the | 
 | 2194 |         arguments hold: | 
 | 2195 |  | 
 | 2196 |          - all three arguments must be integral | 
 | 2197 |          - other must be nonnegative | 
 | 2198 |          - either self or other (or both) must be nonzero | 
 | 2199 |          - modulo must be nonzero and must have at most p digits, | 
 | 2200 |            where p is the context precision. | 
 | 2201 |  | 
 | 2202 |         If any of these restrictions is violated the InvalidOperation | 
 | 2203 |         flag is raised. | 
 | 2204 |  | 
 | 2205 |         The result of pow(self, other, modulo) is identical to the | 
 | 2206 |         result that would be obtained by computing (self**other) % | 
 | 2207 |         modulo with unbounded precision, but is computed more | 
 | 2208 |         efficiently.  It is always exact. | 
 | 2209 |         """ | 
 | 2210 |  | 
 | 2211 |         if modulo is not None: | 
 | 2212 |             return self._power_modulo(other, modulo, context) | 
 | 2213 |  | 
 | 2214 |         other = _convert_other(other) | 
 | 2215 |         if other is NotImplemented: | 
 | 2216 |             return other | 
 | 2217 |  | 
 | 2218 |         if context is None: | 
 | 2219 |             context = getcontext() | 
 | 2220 |  | 
 | 2221 |         # either argument is a NaN => result is NaN | 
 | 2222 |         ans = self._check_nans(other, context) | 
 | 2223 |         if ans: | 
 | 2224 |             return ans | 
 | 2225 |  | 
 | 2226 |         # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity) | 
 | 2227 |         if not other: | 
 | 2228 |             if not self: | 
 | 2229 |                 return context._raise_error(InvalidOperation, '0 ** 0') | 
 | 2230 |             else: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2231 |                 return _One | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2232 |  | 
 | 2233 |         # result has sign 1 iff self._sign is 1 and other is an odd integer | 
 | 2234 |         result_sign = 0 | 
 | 2235 |         if self._sign == 1: | 
 | 2236 |             if other._isinteger(): | 
 | 2237 |                 if not other._iseven(): | 
 | 2238 |                     result_sign = 1 | 
 | 2239 |             else: | 
 | 2240 |                 # -ve**noninteger = NaN | 
 | 2241 |                 # (-0)**noninteger = 0**noninteger | 
 | 2242 |                 if self: | 
 | 2243 |                     return context._raise_error(InvalidOperation, | 
 | 2244 |                         'x ** y with x negative and y not an integer') | 
 | 2245 |             # negate self, without doing any unwanted rounding | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2246 |             self = self.copy_negate() | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2247 |  | 
 | 2248 |         # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity | 
 | 2249 |         if not self: | 
 | 2250 |             if other._sign == 0: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2251 |                 return _dec_from_triple(result_sign, '0', 0) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2252 |             else: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2253 |                 return _SignedInfinity[result_sign] | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2254 |  | 
 | 2255 |         # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0 | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2256 |         if self._isinfinity(): | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2257 |             if other._sign == 0: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2258 |                 return _SignedInfinity[result_sign] | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2259 |             else: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2260 |                 return _dec_from_triple(result_sign, '0', 0) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2261 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2262 |         # 1**other = 1, but the choice of exponent and the flags | 
 | 2263 |         # depend on the exponent of self, and on whether other is a | 
 | 2264 |         # positive integer, a negative integer, or neither | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2265 |         if self == _One: | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2266 |             if other._isinteger(): | 
 | 2267 |                 # exp = max(self._exp*max(int(other), 0), | 
 | 2268 |                 # 1-context.prec) but evaluating int(other) directly | 
 | 2269 |                 # is dangerous until we know other is small (other | 
 | 2270 |                 # could be 1e999999999) | 
 | 2271 |                 if other._sign == 1: | 
 | 2272 |                     multiplier = 0 | 
 | 2273 |                 elif other > context.prec: | 
 | 2274 |                     multiplier = context.prec | 
 | 2275 |                 else: | 
 | 2276 |                     multiplier = int(other) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2277 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2278 |                 exp = self._exp * multiplier | 
 | 2279 |                 if exp < 1-context.prec: | 
 | 2280 |                     exp = 1-context.prec | 
 | 2281 |                     context._raise_error(Rounded) | 
 | 2282 |             else: | 
 | 2283 |                 context._raise_error(Inexact) | 
 | 2284 |                 context._raise_error(Rounded) | 
 | 2285 |                 exp = 1-context.prec | 
 | 2286 |  | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2287 |             return _dec_from_triple(result_sign, '1'+'0'*-exp, exp) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2288 |  | 
 | 2289 |         # compute adjusted exponent of self | 
 | 2290 |         self_adj = self.adjusted() | 
 | 2291 |  | 
 | 2292 |         # self ** infinity is infinity if self > 1, 0 if self < 1 | 
 | 2293 |         # self ** -infinity is infinity if self < 1, 0 if self > 1 | 
 | 2294 |         if other._isinfinity(): | 
 | 2295 |             if (other._sign == 0) == (self_adj < 0): | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2296 |                 return _dec_from_triple(result_sign, '0', 0) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2297 |             else: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2298 |                 return _SignedInfinity[result_sign] | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2299 |  | 
 | 2300 |         # from here on, the result always goes through the call | 
 | 2301 |         # to _fix at the end of this function. | 
 | 2302 |         ans = None | 
 | 2303 |  | 
 | 2304 |         # crude test to catch cases of extreme overflow/underflow.  If | 
 | 2305 |         # log10(self)*other >= 10**bound and bound >= len(str(Emax)) | 
 | 2306 |         # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence | 
 | 2307 |         # self**other >= 10**(Emax+1), so overflow occurs.  The test | 
 | 2308 |         # for underflow is similar. | 
 | 2309 |         bound = self._log10_exp_bound() + other.adjusted() | 
 | 2310 |         if (self_adj >= 0) == (other._sign == 0): | 
 | 2311 |             # self > 1 and other +ve, or self < 1 and other -ve | 
 | 2312 |             # possibility of overflow | 
 | 2313 |             if bound >= len(str(context.Emax)): | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2314 |                 ans = _dec_from_triple(result_sign, '1', context.Emax+1) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2315 |         else: | 
 | 2316 |             # self > 1 and other -ve, or self < 1 and other +ve | 
 | 2317 |             # possibility of underflow to 0 | 
 | 2318 |             Etiny = context.Etiny() | 
 | 2319 |             if bound >= len(str(-Etiny)): | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2320 |                 ans = _dec_from_triple(result_sign, '1', Etiny-1) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2321 |  | 
 | 2322 |         # try for an exact result with precision +1 | 
 | 2323 |         if ans is None: | 
 | 2324 |             ans = self._power_exact(other, context.prec + 1) | 
 | 2325 |             if ans is not None and result_sign == 1: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2326 |                 ans = _dec_from_triple(1, ans._int, ans._exp) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2327 |  | 
 | 2328 |         # usual case: inexact result, x**y computed directly as exp(y*log(x)) | 
 | 2329 |         if ans is None: | 
 | 2330 |             p = context.prec | 
 | 2331 |             x = _WorkRep(self) | 
 | 2332 |             xc, xe = x.int, x.exp | 
 | 2333 |             y = _WorkRep(other) | 
 | 2334 |             yc, ye = y.int, y.exp | 
 | 2335 |             if y.sign == 1: | 
 | 2336 |                 yc = -yc | 
 | 2337 |  | 
 | 2338 |             # compute correctly rounded result:  start with precision +3, | 
 | 2339 |             # then increase precision until result is unambiguously roundable | 
 | 2340 |             extra = 3 | 
 | 2341 |             while True: | 
 | 2342 |                 coeff, exp = _dpower(xc, xe, yc, ye, p+extra) | 
 | 2343 |                 if coeff % (5*10**(len(str(coeff))-p-1)): | 
 | 2344 |                     break | 
 | 2345 |                 extra += 3 | 
 | 2346 |  | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2347 |             ans = _dec_from_triple(result_sign, str(coeff), exp) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2348 |  | 
 | 2349 |         # the specification says that for non-integer other we need to | 
 | 2350 |         # raise Inexact, even when the result is actually exact.  In | 
 | 2351 |         # the same way, we need to raise Underflow here if the result | 
 | 2352 |         # is subnormal.  (The call to _fix will take care of raising | 
 | 2353 |         # Rounded and Subnormal, as usual.) | 
 | 2354 |         if not other._isinteger(): | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2355 |             context._raise_error(Inexact) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2356 |             # pad with zeros up to length context.prec+1 if necessary | 
 | 2357 |             if len(ans._int) <= context.prec: | 
 | 2358 |                 expdiff = context.prec+1 - len(ans._int) | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2359 |                 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff, | 
 | 2360 |                                        ans._exp-expdiff) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2361 |             if ans.adjusted() < context.Emin: | 
 | 2362 |                 context._raise_error(Underflow) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2363 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2364 |         # unlike exp, ln and log10, the power function respects the | 
 | 2365 |         # rounding mode; no need to use ROUND_HALF_EVEN here | 
 | 2366 |         ans = ans._fix(context) | 
 | 2367 |         return ans | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2368 |  | 
 | 2369 |     def __rpow__(self, other, context=None): | 
 | 2370 |         """Swaps self/other and returns __pow__.""" | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2371 |         other = _convert_other(other) | 
| Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 2372 |         if other is NotImplemented: | 
 | 2373 |             return other | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2374 |         return other.__pow__(self, context=context) | 
 | 2375 |  | 
 | 2376 |     def normalize(self, context=None): | 
 | 2377 |         """Normalize- strip trailing 0s, change anything equal to 0 to 0e0""" | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2378 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2379 |         if context is None: | 
 | 2380 |             context = getcontext() | 
 | 2381 |  | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2382 |         if self._is_special: | 
 | 2383 |             ans = self._check_nans(context=context) | 
 | 2384 |             if ans: | 
 | 2385 |                 return ans | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2386 |  | 
| Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 2387 |         dup = self._fix(context) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2388 |         if dup._isinfinity(): | 
 | 2389 |             return dup | 
 | 2390 |  | 
 | 2391 |         if not dup: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2392 |             return _dec_from_triple(dup._sign, '0', 0) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2393 |         exp_max = [context.Emax, context.Etop()][context._clamp] | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2394 |         end = len(dup._int) | 
 | 2395 |         exp = dup._exp | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2396 |         while dup._int[end-1] == '0' and exp < exp_max: | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2397 |             exp += 1 | 
 | 2398 |             end -= 1 | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2399 |         return _dec_from_triple(dup._sign, dup._int[:end], exp) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2400 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2401 |     def quantize(self, exp, rounding=None, context=None, watchexp=True): | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2402 |         """Quantize self so its exponent is the same as that of exp. | 
 | 2403 |  | 
 | 2404 |         Similar to self._rescale(exp._exp) but with error checking. | 
 | 2405 |         """ | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2406 |         exp = _convert_other(exp, raiseit=True) | 
 | 2407 |  | 
 | 2408 |         if context is None: | 
 | 2409 |             context = getcontext() | 
 | 2410 |         if rounding is None: | 
 | 2411 |             rounding = context.rounding | 
 | 2412 |  | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2413 |         if self._is_special or exp._is_special: | 
 | 2414 |             ans = self._check_nans(exp, context) | 
 | 2415 |             if ans: | 
 | 2416 |                 return ans | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2417 |  | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2418 |             if exp._isinfinity() or self._isinfinity(): | 
 | 2419 |                 if exp._isinfinity() and self._isinfinity(): | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2420 |                     return Decimal(self)  # if both are inf, it is OK | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2421 |                 return context._raise_error(InvalidOperation, | 
 | 2422 |                                         'quantize with one INF') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2423 |  | 
 | 2424 |         # if we're not watching exponents, do a simple rescale | 
 | 2425 |         if not watchexp: | 
 | 2426 |             ans = self._rescale(exp._exp, rounding) | 
 | 2427 |             # raise Inexact and Rounded where appropriate | 
 | 2428 |             if ans._exp > self._exp: | 
 | 2429 |                 context._raise_error(Rounded) | 
 | 2430 |                 if ans != self: | 
 | 2431 |                     context._raise_error(Inexact) | 
 | 2432 |             return ans | 
 | 2433 |  | 
 | 2434 |         # exp._exp should be between Etiny and Emax | 
 | 2435 |         if not (context.Etiny() <= exp._exp <= context.Emax): | 
 | 2436 |             return context._raise_error(InvalidOperation, | 
 | 2437 |                    'target exponent out of bounds in quantize') | 
 | 2438 |  | 
 | 2439 |         if not self: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2440 |             ans = _dec_from_triple(self._sign, '0', exp._exp) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2441 |             return ans._fix(context) | 
 | 2442 |  | 
 | 2443 |         self_adjusted = self.adjusted() | 
 | 2444 |         if self_adjusted > context.Emax: | 
 | 2445 |             return context._raise_error(InvalidOperation, | 
 | 2446 |                                         'exponent of quantize result too large for current context') | 
 | 2447 |         if self_adjusted - exp._exp + 1 > context.prec: | 
 | 2448 |             return context._raise_error(InvalidOperation, | 
 | 2449 |                                         'quantize result has too many digits for current context') | 
 | 2450 |  | 
 | 2451 |         ans = self._rescale(exp._exp, rounding) | 
 | 2452 |         if ans.adjusted() > context.Emax: | 
 | 2453 |             return context._raise_error(InvalidOperation, | 
 | 2454 |                                         'exponent of quantize result too large for current context') | 
 | 2455 |         if len(ans._int) > context.prec: | 
 | 2456 |             return context._raise_error(InvalidOperation, | 
 | 2457 |                                         'quantize result has too many digits for current context') | 
 | 2458 |  | 
 | 2459 |         # raise appropriate flags | 
 | 2460 |         if ans._exp > self._exp: | 
 | 2461 |             context._raise_error(Rounded) | 
 | 2462 |             if ans != self: | 
 | 2463 |                 context._raise_error(Inexact) | 
 | 2464 |         if ans and ans.adjusted() < context.Emin: | 
 | 2465 |             context._raise_error(Subnormal) | 
 | 2466 |  | 
 | 2467 |         # call to fix takes care of any necessary folddown | 
 | 2468 |         ans = ans._fix(context) | 
 | 2469 |         return ans | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2470 |  | 
 | 2471 |     def same_quantum(self, other): | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2472 |         """Return True if self and other have the same exponent; otherwise | 
 | 2473 |         return False. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2474 |  | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2475 |         If either operand is a special value, the following rules are used: | 
 | 2476 |            * return True if both operands are infinities | 
 | 2477 |            * return True if both operands are NaNs | 
 | 2478 |            * otherwise, return False. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2479 |         """ | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2480 |         other = _convert_other(other, raiseit=True) | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2481 |         if self._is_special or other._is_special: | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2482 |             return (self.is_nan() and other.is_nan() or | 
 | 2483 |                     self.is_infinite() and other.is_infinite()) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2484 |         return self._exp == other._exp | 
 | 2485 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2486 |     def _rescale(self, exp, rounding): | 
 | 2487 |         """Rescale self so that the exponent is exp, either by padding with zeros | 
 | 2488 |         or by truncating digits, using the given rounding mode. | 
 | 2489 |  | 
 | 2490 |         Specials are returned without change.  This operation is | 
 | 2491 |         quiet: it raises no flags, and uses no information from the | 
 | 2492 |         context. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2493 |  | 
 | 2494 |         exp = exp to scale to (an integer) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2495 |         rounding = rounding mode | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2496 |         """ | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2497 |         if self._is_special: | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2498 |             return Decimal(self) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2499 |         if not self: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2500 |             return _dec_from_triple(self._sign, '0', exp) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2501 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2502 |         if self._exp >= exp: | 
 | 2503 |             # pad answer with zeros if necessary | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2504 |             return _dec_from_triple(self._sign, | 
 | 2505 |                                         self._int + '0'*(self._exp - exp), exp) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2506 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2507 |         # too many digits; round and lose data.  If self.adjusted() < | 
 | 2508 |         # exp-1, replace self by 10**(exp-1) before rounding | 
 | 2509 |         digits = len(self._int) + self._exp - exp | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2510 |         if digits < 0: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2511 |             self = _dec_from_triple(self._sign, '1', exp-1) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2512 |             digits = 0 | 
 | 2513 |         this_function = getattr(self, self._pick_rounding_function[rounding]) | 
| Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 2514 |         changed = this_function(digits) | 
 | 2515 |         coeff = self._int[:digits] or '0' | 
 | 2516 |         if changed == 1: | 
 | 2517 |             coeff = str(int(coeff)+1) | 
 | 2518 |         return _dec_from_triple(self._sign, coeff, exp) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2519 |  | 
| Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 2520 |     def _round(self, places, rounding): | 
 | 2521 |         """Round a nonzero, nonspecial Decimal to a fixed number of | 
 | 2522 |         significant figures, using the given rounding mode. | 
 | 2523 |  | 
 | 2524 |         Infinities, NaNs and zeros are returned unaltered. | 
 | 2525 |  | 
 | 2526 |         This operation is quiet: it raises no flags, and uses no | 
 | 2527 |         information from the context. | 
 | 2528 |  | 
 | 2529 |         """ | 
 | 2530 |         if places <= 0: | 
 | 2531 |             raise ValueError("argument should be at least 1 in _round") | 
 | 2532 |         if self._is_special or not self: | 
 | 2533 |             return Decimal(self) | 
 | 2534 |         ans = self._rescale(self.adjusted()+1-places, rounding) | 
 | 2535 |         # it can happen that the rescale alters the adjusted exponent; | 
 | 2536 |         # for example when rounding 99.97 to 3 significant figures. | 
 | 2537 |         # When this happens we end up with an extra 0 at the end of | 
 | 2538 |         # the number; a second rescale fixes this. | 
 | 2539 |         if ans.adjusted() != self.adjusted(): | 
 | 2540 |             ans = ans._rescale(ans.adjusted()+1-places, rounding) | 
 | 2541 |         return ans | 
 | 2542 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2543 |     def to_integral_exact(self, rounding=None, context=None): | 
 | 2544 |         """Rounds to a nearby integer. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2545 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2546 |         If no rounding mode is specified, take the rounding mode from | 
 | 2547 |         the context.  This method raises the Rounded and Inexact flags | 
 | 2548 |         when appropriate. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2549 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2550 |         See also: to_integral_value, which does exactly the same as | 
 | 2551 |         this method except that it doesn't raise Inexact or Rounded. | 
 | 2552 |         """ | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2553 |         if self._is_special: | 
 | 2554 |             ans = self._check_nans(context=context) | 
 | 2555 |             if ans: | 
 | 2556 |                 return ans | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2557 |             return Decimal(self) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2558 |         if self._exp >= 0: | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2559 |             return Decimal(self) | 
 | 2560 |         if not self: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2561 |             return _dec_from_triple(self._sign, '0', 0) | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2562 |         if context is None: | 
 | 2563 |             context = getcontext() | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2564 |         if rounding is None: | 
 | 2565 |             rounding = context.rounding | 
 | 2566 |         context._raise_error(Rounded) | 
 | 2567 |         ans = self._rescale(0, rounding) | 
 | 2568 |         if ans != self: | 
 | 2569 |             context._raise_error(Inexact) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2570 |         return ans | 
 | 2571 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2572 |     def to_integral_value(self, rounding=None, context=None): | 
 | 2573 |         """Rounds to the nearest integer, without raising inexact, rounded.""" | 
 | 2574 |         if context is None: | 
 | 2575 |             context = getcontext() | 
 | 2576 |         if rounding is None: | 
 | 2577 |             rounding = context.rounding | 
 | 2578 |         if self._is_special: | 
 | 2579 |             ans = self._check_nans(context=context) | 
 | 2580 |             if ans: | 
 | 2581 |                 return ans | 
 | 2582 |             return Decimal(self) | 
 | 2583 |         if self._exp >= 0: | 
 | 2584 |             return Decimal(self) | 
 | 2585 |         else: | 
 | 2586 |             return self._rescale(0, rounding) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2587 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2588 |     # the method name changed, but we provide also the old one, for compatibility | 
 | 2589 |     to_integral = to_integral_value | 
 | 2590 |  | 
 | 2591 |     def sqrt(self, context=None): | 
 | 2592 |         """Return the square root of self.""" | 
| Christian Heimes | 0348fb6 | 2008-03-26 12:55:56 +0000 | [diff] [blame] | 2593 |         if context is None: | 
 | 2594 |             context = getcontext() | 
 | 2595 |  | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2596 |         if self._is_special: | 
 | 2597 |             ans = self._check_nans(context=context) | 
 | 2598 |             if ans: | 
 | 2599 |                 return ans | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2600 |  | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2601 |             if self._isinfinity() and self._sign == 0: | 
 | 2602 |                 return Decimal(self) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2603 |  | 
 | 2604 |         if not self: | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2605 |             # exponent = self._exp // 2.  sqrt(-0) = -0 | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2606 |             ans = _dec_from_triple(self._sign, '0', self._exp // 2) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2607 |             return ans._fix(context) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2608 |  | 
 | 2609 |         if self._sign == 1: | 
 | 2610 |             return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0') | 
 | 2611 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2612 |         # At this point self represents a positive number.  Let p be | 
 | 2613 |         # the desired precision and express self in the form c*100**e | 
 | 2614 |         # with c a positive real number and e an integer, c and e | 
 | 2615 |         # being chosen so that 100**(p-1) <= c < 100**p.  Then the | 
 | 2616 |         # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1) | 
 | 2617 |         # <= sqrt(c) < 10**p, so the closest representable Decimal at | 
 | 2618 |         # precision p is n*10**e where n = round_half_even(sqrt(c)), | 
 | 2619 |         # the closest integer to sqrt(c) with the even integer chosen | 
 | 2620 |         # in the case of a tie. | 
 | 2621 |         # | 
 | 2622 |         # To ensure correct rounding in all cases, we use the | 
 | 2623 |         # following trick: we compute the square root to an extra | 
 | 2624 |         # place (precision p+1 instead of precision p), rounding down. | 
 | 2625 |         # Then, if the result is inexact and its last digit is 0 or 5, | 
 | 2626 |         # we increase the last digit to 1 or 6 respectively; if it's | 
 | 2627 |         # exact we leave the last digit alone.  Now the final round to | 
 | 2628 |         # p places (or fewer in the case of underflow) will round | 
 | 2629 |         # correctly and raise the appropriate flags. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2630 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2631 |         # use an extra digit of precision | 
 | 2632 |         prec = context.prec+1 | 
 | 2633 |  | 
 | 2634 |         # write argument in the form c*100**e where e = self._exp//2 | 
 | 2635 |         # is the 'ideal' exponent, to be used if the square root is | 
 | 2636 |         # exactly representable.  l is the number of 'digits' of c in | 
 | 2637 |         # base 100, so that 100**(l-1) <= c < 100**l. | 
 | 2638 |         op = _WorkRep(self) | 
 | 2639 |         e = op.exp >> 1 | 
 | 2640 |         if op.exp & 1: | 
 | 2641 |             c = op.int * 10 | 
 | 2642 |             l = (len(self._int) >> 1) + 1 | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2643 |         else: | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2644 |             c = op.int | 
 | 2645 |             l = len(self._int)+1 >> 1 | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2646 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2647 |         # rescale so that c has exactly prec base 100 'digits' | 
 | 2648 |         shift = prec-l | 
 | 2649 |         if shift >= 0: | 
 | 2650 |             c *= 100**shift | 
 | 2651 |             exact = True | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2652 |         else: | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2653 |             c, remainder = divmod(c, 100**-shift) | 
 | 2654 |             exact = not remainder | 
 | 2655 |         e -= shift | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2656 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2657 |         # find n = floor(sqrt(c)) using Newton's method | 
 | 2658 |         n = 10**prec | 
 | 2659 |         while True: | 
 | 2660 |             q = c//n | 
 | 2661 |             if n <= q: | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2662 |                 break | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2663 |             else: | 
 | 2664 |                 n = n + q >> 1 | 
 | 2665 |         exact = exact and n*n == c | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2666 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2667 |         if exact: | 
 | 2668 |             # result is exact; rescale to use ideal exponent e | 
 | 2669 |             if shift >= 0: | 
 | 2670 |                 # assert n % 10**shift == 0 | 
 | 2671 |                 n //= 10**shift | 
 | 2672 |             else: | 
 | 2673 |                 n *= 10**-shift | 
 | 2674 |             e += shift | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2675 |         else: | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2676 |             # result is not exact; fix last digit as described above | 
 | 2677 |             if n % 5 == 0: | 
 | 2678 |                 n += 1 | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2679 |  | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2680 |         ans = _dec_from_triple(0, str(n), e) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2681 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2682 |         # round, and fit to current context | 
 | 2683 |         context = context._shallow_copy() | 
 | 2684 |         rounding = context._set_rounding(ROUND_HALF_EVEN) | 
| Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 2685 |         ans = ans._fix(context) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2686 |         context.rounding = rounding | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2687 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2688 |         return ans | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2689 |  | 
 | 2690 |     def max(self, other, context=None): | 
 | 2691 |         """Returns the larger value. | 
 | 2692 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2693 |         Like max(self, other) except if one is not a number, returns | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2694 |         NaN (and signals if one is sNaN).  Also rounds. | 
 | 2695 |         """ | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2696 |         other = _convert_other(other, raiseit=True) | 
 | 2697 |  | 
 | 2698 |         if context is None: | 
 | 2699 |             context = getcontext() | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2700 |  | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2701 |         if self._is_special or other._is_special: | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2702 |             # If one operand is a quiet NaN and the other is number, then the | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2703 |             # number is always returned | 
 | 2704 |             sn = self._isnan() | 
 | 2705 |             on = other._isnan() | 
 | 2706 |             if sn or on: | 
| Facundo Batista | 708d581 | 2008-12-11 04:20:07 +0000 | [diff] [blame] | 2707 |                 if on == 1 and sn == 0: | 
 | 2708 |                     return self._fix(context) | 
 | 2709 |                 if sn == 1 and on == 0: | 
 | 2710 |                     return other._fix(context) | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2711 |                 return self._check_nans(other, context) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2712 |  | 
| Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 2713 |         c = self._cmp(other) | 
| Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2714 |         if c == 0: | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2715 |             # If both operands are finite and equal in numerical value | 
| Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2716 |             # then an ordering is applied: | 
 | 2717 |             # | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2718 |             # If the signs differ then max returns the operand with the | 
| Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2719 |             # positive sign and min returns the operand with the negative sign | 
 | 2720 |             # | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2721 |             # If the signs are the same then the exponent is used to select | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2722 |             # the result.  This is exactly the ordering used in compare_total. | 
 | 2723 |             c = self.compare_total(other) | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2724 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2725 |         if c == -1: | 
 | 2726 |             ans = other | 
 | 2727 |         else: | 
 | 2728 |             ans = self | 
 | 2729 |  | 
| Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 2730 |         return ans._fix(context) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2731 |  | 
 | 2732 |     def min(self, other, context=None): | 
 | 2733 |         """Returns the smaller value. | 
 | 2734 |  | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2735 |         Like min(self, other) except if one is not a number, returns | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2736 |         NaN (and signals if one is sNaN).  Also rounds. | 
 | 2737 |         """ | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2738 |         other = _convert_other(other, raiseit=True) | 
 | 2739 |  | 
 | 2740 |         if context is None: | 
 | 2741 |             context = getcontext() | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2742 |  | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2743 |         if self._is_special or other._is_special: | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2744 |             # If one operand is a quiet NaN and the other is number, then the | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2745 |             # number is always returned | 
 | 2746 |             sn = self._isnan() | 
 | 2747 |             on = other._isnan() | 
 | 2748 |             if sn or on: | 
| Facundo Batista | 708d581 | 2008-12-11 04:20:07 +0000 | [diff] [blame] | 2749 |                 if on == 1 and sn == 0: | 
 | 2750 |                     return self._fix(context) | 
 | 2751 |                 if sn == 1 and on == 0: | 
 | 2752 |                     return other._fix(context) | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2753 |                 return self._check_nans(other, context) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2754 |  | 
| Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 2755 |         c = self._cmp(other) | 
| Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2756 |         if c == 0: | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2757 |             c = self.compare_total(other) | 
 | 2758 |  | 
 | 2759 |         if c == -1: | 
 | 2760 |             ans = self | 
 | 2761 |         else: | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2762 |             ans = other | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2763 |  | 
| Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 2764 |         return ans._fix(context) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2765 |  | 
 | 2766 |     def _isinteger(self): | 
 | 2767 |         """Returns whether self is an integer""" | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2768 |         if self._is_special: | 
 | 2769 |             return False | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2770 |         if self._exp >= 0: | 
 | 2771 |             return True | 
 | 2772 |         rest = self._int[self._exp:] | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2773 |         return rest == '0'*len(rest) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2774 |  | 
 | 2775 |     def _iseven(self): | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2776 |         """Returns True if self is even.  Assumes self is an integer.""" | 
 | 2777 |         if not self or self._exp > 0: | 
 | 2778 |             return True | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2779 |         return self._int[-1+self._exp] in '02468' | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2780 |  | 
 | 2781 |     def adjusted(self): | 
 | 2782 |         """Return the adjusted exponent of self""" | 
 | 2783 |         try: | 
 | 2784 |             return self._exp + len(self._int) - 1 | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2785 |         # If NaN or Infinity, self._exp is string | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2786 |         except TypeError: | 
 | 2787 |             return 0 | 
 | 2788 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2789 |     def canonical(self, context=None): | 
 | 2790 |         """Returns the same Decimal object. | 
 | 2791 |  | 
 | 2792 |         As we do not have different encodings for the same number, the | 
 | 2793 |         received object already is in its canonical form. | 
 | 2794 |         """ | 
 | 2795 |         return self | 
 | 2796 |  | 
 | 2797 |     def compare_signal(self, other, context=None): | 
 | 2798 |         """Compares self to the other operand numerically. | 
 | 2799 |  | 
 | 2800 |         It's pretty much like compare(), but all NaNs signal, with signaling | 
 | 2801 |         NaNs taking precedence over quiet NaNs. | 
 | 2802 |         """ | 
| Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 2803 |         other = _convert_other(other, raiseit = True) | 
 | 2804 |         ans = self._compare_check_nans(other, context) | 
 | 2805 |         if ans: | 
 | 2806 |             return ans | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2807 |         return self.compare(other, context=context) | 
 | 2808 |  | 
 | 2809 |     def compare_total(self, other): | 
 | 2810 |         """Compares self to other using the abstract representations. | 
 | 2811 |  | 
 | 2812 |         This is not like the standard compare, which use their numerical | 
 | 2813 |         value. Note that a total ordering is defined for all possible abstract | 
 | 2814 |         representations. | 
 | 2815 |         """ | 
 | 2816 |         # if one is negative and the other is positive, it's easy | 
 | 2817 |         if self._sign and not other._sign: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2818 |             return _NegativeOne | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2819 |         if not self._sign and other._sign: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2820 |             return _One | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2821 |         sign = self._sign | 
 | 2822 |  | 
 | 2823 |         # let's handle both NaN types | 
 | 2824 |         self_nan = self._isnan() | 
 | 2825 |         other_nan = other._isnan() | 
 | 2826 |         if self_nan or other_nan: | 
 | 2827 |             if self_nan == other_nan: | 
 | 2828 |                 if self._int < other._int: | 
 | 2829 |                     if sign: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2830 |                         return _One | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2831 |                     else: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2832 |                         return _NegativeOne | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2833 |                 if self._int > other._int: | 
 | 2834 |                     if sign: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2835 |                         return _NegativeOne | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2836 |                     else: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2837 |                         return _One | 
 | 2838 |                 return _Zero | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2839 |  | 
 | 2840 |             if sign: | 
 | 2841 |                 if self_nan == 1: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2842 |                     return _NegativeOne | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2843 |                 if other_nan == 1: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2844 |                     return _One | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2845 |                 if self_nan == 2: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2846 |                     return _NegativeOne | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2847 |                 if other_nan == 2: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2848 |                     return _One | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2849 |             else: | 
 | 2850 |                 if self_nan == 1: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2851 |                     return _One | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2852 |                 if other_nan == 1: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2853 |                     return _NegativeOne | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2854 |                 if self_nan == 2: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2855 |                     return _One | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2856 |                 if other_nan == 2: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2857 |                     return _NegativeOne | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2858 |  | 
 | 2859 |         if self < other: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2860 |             return _NegativeOne | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2861 |         if self > other: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2862 |             return _One | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2863 |  | 
 | 2864 |         if self._exp < other._exp: | 
 | 2865 |             if sign: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2866 |                 return _One | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2867 |             else: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2868 |                 return _NegativeOne | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2869 |         if self._exp > other._exp: | 
 | 2870 |             if sign: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2871 |                 return _NegativeOne | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2872 |             else: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2873 |                 return _One | 
 | 2874 |         return _Zero | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2875 |  | 
 | 2876 |  | 
 | 2877 |     def compare_total_mag(self, other): | 
 | 2878 |         """Compares self to other using abstract repr., ignoring sign. | 
 | 2879 |  | 
 | 2880 |         Like compare_total, but with operand's sign ignored and assumed to be 0. | 
 | 2881 |         """ | 
 | 2882 |         s = self.copy_abs() | 
 | 2883 |         o = other.copy_abs() | 
 | 2884 |         return s.compare_total(o) | 
 | 2885 |  | 
 | 2886 |     def copy_abs(self): | 
 | 2887 |         """Returns a copy with the sign set to 0. """ | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2888 |         return _dec_from_triple(0, self._int, self._exp, self._is_special) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2889 |  | 
 | 2890 |     def copy_negate(self): | 
 | 2891 |         """Returns a copy with the sign inverted.""" | 
 | 2892 |         if self._sign: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2893 |             return _dec_from_triple(0, self._int, self._exp, self._is_special) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2894 |         else: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2895 |             return _dec_from_triple(1, self._int, self._exp, self._is_special) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2896 |  | 
 | 2897 |     def copy_sign(self, other): | 
 | 2898 |         """Returns self with the sign of other.""" | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2899 |         return _dec_from_triple(other._sign, self._int, | 
 | 2900 |                                 self._exp, self._is_special) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2901 |  | 
 | 2902 |     def exp(self, context=None): | 
 | 2903 |         """Returns e ** self.""" | 
 | 2904 |  | 
 | 2905 |         if context is None: | 
 | 2906 |             context = getcontext() | 
 | 2907 |  | 
 | 2908 |         # exp(NaN) = NaN | 
 | 2909 |         ans = self._check_nans(context=context) | 
 | 2910 |         if ans: | 
 | 2911 |             return ans | 
 | 2912 |  | 
 | 2913 |         # exp(-Infinity) = 0 | 
 | 2914 |         if self._isinfinity() == -1: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2915 |             return _Zero | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2916 |  | 
 | 2917 |         # exp(0) = 1 | 
 | 2918 |         if not self: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2919 |             return _One | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2920 |  | 
 | 2921 |         # exp(Infinity) = Infinity | 
 | 2922 |         if self._isinfinity() == 1: | 
 | 2923 |             return Decimal(self) | 
 | 2924 |  | 
 | 2925 |         # the result is now guaranteed to be inexact (the true | 
 | 2926 |         # mathematical result is transcendental). There's no need to | 
 | 2927 |         # raise Rounded and Inexact here---they'll always be raised as | 
 | 2928 |         # a result of the call to _fix. | 
 | 2929 |         p = context.prec | 
 | 2930 |         adj = self.adjusted() | 
 | 2931 |  | 
 | 2932 |         # we only need to do any computation for quite a small range | 
 | 2933 |         # of adjusted exponents---for example, -29 <= adj <= 10 for | 
 | 2934 |         # the default context.  For smaller exponent the result is | 
 | 2935 |         # indistinguishable from 1 at the given precision, while for | 
 | 2936 |         # larger exponent the result either overflows or underflows. | 
 | 2937 |         if self._sign == 0 and adj > len(str((context.Emax+1)*3)): | 
 | 2938 |             # overflow | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2939 |             ans = _dec_from_triple(0, '1', context.Emax+1) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2940 |         elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)): | 
 | 2941 |             # underflow to 0 | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2942 |             ans = _dec_from_triple(0, '1', context.Etiny()-1) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2943 |         elif self._sign == 0 and adj < -p: | 
 | 2944 |             # p+1 digits; final round will raise correct flags | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2945 |             ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2946 |         elif self._sign == 1 and adj < -p-1: | 
 | 2947 |             # p+1 digits; final round will raise correct flags | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2948 |             ans = _dec_from_triple(0, '9'*(p+1), -p-1) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2949 |         # general case | 
 | 2950 |         else: | 
 | 2951 |             op = _WorkRep(self) | 
 | 2952 |             c, e = op.int, op.exp | 
 | 2953 |             if op.sign == 1: | 
 | 2954 |                 c = -c | 
 | 2955 |  | 
 | 2956 |             # compute correctly rounded result: increase precision by | 
 | 2957 |             # 3 digits at a time until we get an unambiguously | 
 | 2958 |             # roundable result | 
 | 2959 |             extra = 3 | 
 | 2960 |             while True: | 
 | 2961 |                 coeff, exp = _dexp(c, e, p+extra) | 
 | 2962 |                 if coeff % (5*10**(len(str(coeff))-p-1)): | 
 | 2963 |                     break | 
 | 2964 |                 extra += 3 | 
 | 2965 |  | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2966 |             ans = _dec_from_triple(0, str(coeff), exp) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2967 |  | 
 | 2968 |         # at this stage, ans should round correctly with *any* | 
 | 2969 |         # rounding mode, not just with ROUND_HALF_EVEN | 
 | 2970 |         context = context._shallow_copy() | 
 | 2971 |         rounding = context._set_rounding(ROUND_HALF_EVEN) | 
 | 2972 |         ans = ans._fix(context) | 
 | 2973 |         context.rounding = rounding | 
 | 2974 |  | 
 | 2975 |         return ans | 
 | 2976 |  | 
 | 2977 |     def is_canonical(self): | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2978 |         """Return True if self is canonical; otherwise return False. | 
 | 2979 |  | 
 | 2980 |         Currently, the encoding of a Decimal instance is always | 
 | 2981 |         canonical, so this method returns True for any Decimal. | 
 | 2982 |         """ | 
 | 2983 |         return True | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2984 |  | 
 | 2985 |     def is_finite(self): | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2986 |         """Return True if self is finite; otherwise return False. | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2987 |  | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2988 |         A Decimal instance is considered finite if it is neither | 
 | 2989 |         infinite nor a NaN. | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2990 |         """ | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2991 |         return not self._is_special | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2992 |  | 
 | 2993 |     def is_infinite(self): | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2994 |         """Return True if self is infinite; otherwise return False.""" | 
 | 2995 |         return self._exp == 'F' | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2996 |  | 
 | 2997 |     def is_nan(self): | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2998 |         """Return True if self is a qNaN or sNaN; otherwise return False.""" | 
 | 2999 |         return self._exp in ('n', 'N') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3000 |  | 
 | 3001 |     def is_normal(self, context=None): | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3002 |         """Return True if self is a normal number; otherwise return False.""" | 
 | 3003 |         if self._is_special or not self: | 
 | 3004 |             return False | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3005 |         if context is None: | 
 | 3006 |             context = getcontext() | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3007 |         return context.Emin <= self.adjusted() <= context.Emax | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3008 |  | 
 | 3009 |     def is_qnan(self): | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3010 |         """Return True if self is a quiet NaN; otherwise return False.""" | 
 | 3011 |         return self._exp == 'n' | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3012 |  | 
 | 3013 |     def is_signed(self): | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3014 |         """Return True if self is negative; otherwise return False.""" | 
 | 3015 |         return self._sign == 1 | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3016 |  | 
 | 3017 |     def is_snan(self): | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3018 |         """Return True if self is a signaling NaN; otherwise return False.""" | 
 | 3019 |         return self._exp == 'N' | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3020 |  | 
 | 3021 |     def is_subnormal(self, context=None): | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3022 |         """Return True if self is subnormal; otherwise return False.""" | 
 | 3023 |         if self._is_special or not self: | 
 | 3024 |             return False | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3025 |         if context is None: | 
 | 3026 |             context = getcontext() | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3027 |         return self.adjusted() < context.Emin | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3028 |  | 
 | 3029 |     def is_zero(self): | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3030 |         """Return True if self is a zero; otherwise return False.""" | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3031 |         return not self._is_special and self._int == '0' | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3032 |  | 
 | 3033 |     def _ln_exp_bound(self): | 
 | 3034 |         """Compute a lower bound for the adjusted exponent of self.ln(). | 
 | 3035 |         In other words, compute r such that self.ln() >= 10**r.  Assumes | 
 | 3036 |         that self is finite and positive and that self != 1. | 
 | 3037 |         """ | 
 | 3038 |  | 
 | 3039 |         # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1 | 
 | 3040 |         adj = self._exp + len(self._int) - 1 | 
 | 3041 |         if adj >= 1: | 
 | 3042 |             # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10) | 
 | 3043 |             return len(str(adj*23//10)) - 1 | 
 | 3044 |         if adj <= -2: | 
 | 3045 |             # argument <= 0.1 | 
 | 3046 |             return len(str((-1-adj)*23//10)) - 1 | 
 | 3047 |         op = _WorkRep(self) | 
 | 3048 |         c, e = op.int, op.exp | 
 | 3049 |         if adj == 0: | 
 | 3050 |             # 1 < self < 10 | 
 | 3051 |             num = str(c-10**-e) | 
 | 3052 |             den = str(c) | 
 | 3053 |             return len(num) - len(den) - (num < den) | 
 | 3054 |         # adj == -1, 0.1 <= self < 1 | 
 | 3055 |         return e + len(str(10**-e - c)) - 1 | 
 | 3056 |  | 
 | 3057 |  | 
 | 3058 |     def ln(self, context=None): | 
 | 3059 |         """Returns the natural (base e) logarithm of self.""" | 
 | 3060 |  | 
 | 3061 |         if context is None: | 
 | 3062 |             context = getcontext() | 
 | 3063 |  | 
 | 3064 |         # ln(NaN) = NaN | 
 | 3065 |         ans = self._check_nans(context=context) | 
 | 3066 |         if ans: | 
 | 3067 |             return ans | 
 | 3068 |  | 
 | 3069 |         # ln(0.0) == -Infinity | 
 | 3070 |         if not self: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3071 |             return _NegativeInfinity | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3072 |  | 
 | 3073 |         # ln(Infinity) = Infinity | 
 | 3074 |         if self._isinfinity() == 1: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3075 |             return _Infinity | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3076 |  | 
 | 3077 |         # ln(1.0) == 0.0 | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3078 |         if self == _One: | 
 | 3079 |             return _Zero | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3080 |  | 
 | 3081 |         # ln(negative) raises InvalidOperation | 
 | 3082 |         if self._sign == 1: | 
 | 3083 |             return context._raise_error(InvalidOperation, | 
 | 3084 |                                         'ln of a negative value') | 
 | 3085 |  | 
 | 3086 |         # result is irrational, so necessarily inexact | 
 | 3087 |         op = _WorkRep(self) | 
 | 3088 |         c, e = op.int, op.exp | 
 | 3089 |         p = context.prec | 
 | 3090 |  | 
 | 3091 |         # correctly rounded result: repeatedly increase precision by 3 | 
 | 3092 |         # until we get an unambiguously roundable result | 
 | 3093 |         places = p - self._ln_exp_bound() + 2 # at least p+3 places | 
 | 3094 |         while True: | 
 | 3095 |             coeff = _dlog(c, e, places) | 
 | 3096 |             # assert len(str(abs(coeff)))-p >= 1 | 
 | 3097 |             if coeff % (5*10**(len(str(abs(coeff)))-p-1)): | 
 | 3098 |                 break | 
 | 3099 |             places += 3 | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3100 |         ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3101 |  | 
 | 3102 |         context = context._shallow_copy() | 
 | 3103 |         rounding = context._set_rounding(ROUND_HALF_EVEN) | 
 | 3104 |         ans = ans._fix(context) | 
 | 3105 |         context.rounding = rounding | 
 | 3106 |         return ans | 
 | 3107 |  | 
 | 3108 |     def _log10_exp_bound(self): | 
 | 3109 |         """Compute a lower bound for the adjusted exponent of self.log10(). | 
 | 3110 |         In other words, find r such that self.log10() >= 10**r. | 
 | 3111 |         Assumes that self is finite and positive and that self != 1. | 
 | 3112 |         """ | 
 | 3113 |  | 
 | 3114 |         # For x >= 10 or x < 0.1 we only need a bound on the integer | 
 | 3115 |         # part of log10(self), and this comes directly from the | 
 | 3116 |         # exponent of x.  For 0.1 <= x <= 10 we use the inequalities | 
 | 3117 |         # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| > | 
 | 3118 |         # (1-1/x)/2.31 > 0.  If x < 1 then |log10(x)| > (1-x)/2.31 > 0 | 
 | 3119 |  | 
 | 3120 |         adj = self._exp + len(self._int) - 1 | 
 | 3121 |         if adj >= 1: | 
 | 3122 |             # self >= 10 | 
 | 3123 |             return len(str(adj))-1 | 
 | 3124 |         if adj <= -2: | 
 | 3125 |             # self < 0.1 | 
 | 3126 |             return len(str(-1-adj))-1 | 
 | 3127 |         op = _WorkRep(self) | 
 | 3128 |         c, e = op.int, op.exp | 
 | 3129 |         if adj == 0: | 
 | 3130 |             # 1 < self < 10 | 
 | 3131 |             num = str(c-10**-e) | 
 | 3132 |             den = str(231*c) | 
 | 3133 |             return len(num) - len(den) - (num < den) + 2 | 
 | 3134 |         # adj == -1, 0.1 <= self < 1 | 
 | 3135 |         num = str(10**-e-c) | 
 | 3136 |         return len(num) + e - (num < "231") - 1 | 
 | 3137 |  | 
 | 3138 |     def log10(self, context=None): | 
 | 3139 |         """Returns the base 10 logarithm of self.""" | 
 | 3140 |  | 
 | 3141 |         if context is None: | 
 | 3142 |             context = getcontext() | 
 | 3143 |  | 
 | 3144 |         # log10(NaN) = NaN | 
 | 3145 |         ans = self._check_nans(context=context) | 
 | 3146 |         if ans: | 
 | 3147 |             return ans | 
 | 3148 |  | 
 | 3149 |         # log10(0.0) == -Infinity | 
 | 3150 |         if not self: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3151 |             return _NegativeInfinity | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3152 |  | 
 | 3153 |         # log10(Infinity) = Infinity | 
 | 3154 |         if self._isinfinity() == 1: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3155 |             return _Infinity | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3156 |  | 
 | 3157 |         # log10(negative or -Infinity) raises InvalidOperation | 
 | 3158 |         if self._sign == 1: | 
 | 3159 |             return context._raise_error(InvalidOperation, | 
 | 3160 |                                         'log10 of a negative value') | 
 | 3161 |  | 
 | 3162 |         # log10(10**n) = n | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3163 |         if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1): | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3164 |             # answer may need rounding | 
 | 3165 |             ans = Decimal(self._exp + len(self._int) - 1) | 
 | 3166 |         else: | 
 | 3167 |             # result is irrational, so necessarily inexact | 
 | 3168 |             op = _WorkRep(self) | 
 | 3169 |             c, e = op.int, op.exp | 
 | 3170 |             p = context.prec | 
 | 3171 |  | 
 | 3172 |             # correctly rounded result: repeatedly increase precision | 
 | 3173 |             # until result is unambiguously roundable | 
 | 3174 |             places = p-self._log10_exp_bound()+2 | 
 | 3175 |             while True: | 
 | 3176 |                 coeff = _dlog10(c, e, places) | 
 | 3177 |                 # assert len(str(abs(coeff)))-p >= 1 | 
 | 3178 |                 if coeff % (5*10**(len(str(abs(coeff)))-p-1)): | 
 | 3179 |                     break | 
 | 3180 |                 places += 3 | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3181 |             ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3182 |  | 
 | 3183 |         context = context._shallow_copy() | 
 | 3184 |         rounding = context._set_rounding(ROUND_HALF_EVEN) | 
 | 3185 |         ans = ans._fix(context) | 
 | 3186 |         context.rounding = rounding | 
 | 3187 |         return ans | 
 | 3188 |  | 
 | 3189 |     def logb(self, context=None): | 
 | 3190 |         """ Returns the exponent of the magnitude of self's MSD. | 
 | 3191 |  | 
 | 3192 |         The result is the integer which is the exponent of the magnitude | 
 | 3193 |         of the most significant digit of self (as though it were truncated | 
 | 3194 |         to a single digit while maintaining the value of that digit and | 
 | 3195 |         without limiting the resulting exponent). | 
 | 3196 |         """ | 
 | 3197 |         # logb(NaN) = NaN | 
 | 3198 |         ans = self._check_nans(context=context) | 
 | 3199 |         if ans: | 
 | 3200 |             return ans | 
 | 3201 |  | 
 | 3202 |         if context is None: | 
 | 3203 |             context = getcontext() | 
 | 3204 |  | 
 | 3205 |         # logb(+/-Inf) = +Inf | 
 | 3206 |         if self._isinfinity(): | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3207 |             return _Infinity | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3208 |  | 
 | 3209 |         # logb(0) = -Inf, DivisionByZero | 
 | 3210 |         if not self: | 
 | 3211 |             return context._raise_error(DivisionByZero, 'logb(0)', 1) | 
 | 3212 |  | 
 | 3213 |         # otherwise, simply return the adjusted exponent of self, as a | 
 | 3214 |         # Decimal.  Note that no attempt is made to fit the result | 
 | 3215 |         # into the current context. | 
 | 3216 |         return Decimal(self.adjusted()) | 
 | 3217 |  | 
 | 3218 |     def _islogical(self): | 
 | 3219 |         """Return True if self is a logical operand. | 
 | 3220 |  | 
| Christian Heimes | 679db4a | 2008-01-18 09:56:22 +0000 | [diff] [blame] | 3221 |         For being logical, it must be a finite number with a sign of 0, | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3222 |         an exponent of 0, and a coefficient whose digits must all be | 
 | 3223 |         either 0 or 1. | 
 | 3224 |         """ | 
 | 3225 |         if self._sign != 0 or self._exp != 0: | 
 | 3226 |             return False | 
 | 3227 |         for dig in self._int: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3228 |             if dig not in '01': | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3229 |                 return False | 
 | 3230 |         return True | 
 | 3231 |  | 
 | 3232 |     def _fill_logical(self, context, opa, opb): | 
 | 3233 |         dif = context.prec - len(opa) | 
 | 3234 |         if dif > 0: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3235 |             opa = '0'*dif + opa | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3236 |         elif dif < 0: | 
 | 3237 |             opa = opa[-context.prec:] | 
 | 3238 |         dif = context.prec - len(opb) | 
 | 3239 |         if dif > 0: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3240 |             opb = '0'*dif + opb | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3241 |         elif dif < 0: | 
 | 3242 |             opb = opb[-context.prec:] | 
 | 3243 |         return opa, opb | 
 | 3244 |  | 
 | 3245 |     def logical_and(self, other, context=None): | 
 | 3246 |         """Applies an 'and' operation between self and other's digits.""" | 
 | 3247 |         if context is None: | 
 | 3248 |             context = getcontext() | 
 | 3249 |         if not self._islogical() or not other._islogical(): | 
 | 3250 |             return context._raise_error(InvalidOperation) | 
 | 3251 |  | 
 | 3252 |         # fill to context.prec | 
 | 3253 |         (opa, opb) = self._fill_logical(context, self._int, other._int) | 
 | 3254 |  | 
 | 3255 |         # make the operation, and clean starting zeroes | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3256 |         result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)]) | 
 | 3257 |         return _dec_from_triple(0, result.lstrip('0') or '0', 0) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3258 |  | 
 | 3259 |     def logical_invert(self, context=None): | 
 | 3260 |         """Invert all its digits.""" | 
 | 3261 |         if context is None: | 
 | 3262 |             context = getcontext() | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3263 |         return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0), | 
 | 3264 |                                 context) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3265 |  | 
 | 3266 |     def logical_or(self, other, context=None): | 
 | 3267 |         """Applies an 'or' operation between self and other's digits.""" | 
 | 3268 |         if context is None: | 
 | 3269 |             context = getcontext() | 
 | 3270 |         if not self._islogical() or not other._islogical(): | 
 | 3271 |             return context._raise_error(InvalidOperation) | 
 | 3272 |  | 
 | 3273 |         # fill to context.prec | 
 | 3274 |         (opa, opb) = self._fill_logical(context, self._int, other._int) | 
 | 3275 |  | 
 | 3276 |         # make the operation, and clean starting zeroes | 
| Mark Dickinson | 315a20a | 2009-01-04 21:34:18 +0000 | [diff] [blame] | 3277 |         result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)]) | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3278 |         return _dec_from_triple(0, result.lstrip('0') or '0', 0) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3279 |  | 
 | 3280 |     def logical_xor(self, other, context=None): | 
 | 3281 |         """Applies an 'xor' operation between self and other's digits.""" | 
 | 3282 |         if context is None: | 
 | 3283 |             context = getcontext() | 
 | 3284 |         if not self._islogical() or not other._islogical(): | 
 | 3285 |             return context._raise_error(InvalidOperation) | 
 | 3286 |  | 
 | 3287 |         # fill to context.prec | 
 | 3288 |         (opa, opb) = self._fill_logical(context, self._int, other._int) | 
 | 3289 |  | 
 | 3290 |         # make the operation, and clean starting zeroes | 
| Mark Dickinson | 315a20a | 2009-01-04 21:34:18 +0000 | [diff] [blame] | 3291 |         result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)]) | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3292 |         return _dec_from_triple(0, result.lstrip('0') or '0', 0) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3293 |  | 
 | 3294 |     def max_mag(self, other, context=None): | 
 | 3295 |         """Compares the values numerically with their sign ignored.""" | 
 | 3296 |         other = _convert_other(other, raiseit=True) | 
 | 3297 |  | 
 | 3298 |         if context is None: | 
 | 3299 |             context = getcontext() | 
 | 3300 |  | 
 | 3301 |         if self._is_special or other._is_special: | 
 | 3302 |             # If one operand is a quiet NaN and the other is number, then the | 
 | 3303 |             # number is always returned | 
 | 3304 |             sn = self._isnan() | 
 | 3305 |             on = other._isnan() | 
 | 3306 |             if sn or on: | 
| Facundo Batista | 708d581 | 2008-12-11 04:20:07 +0000 | [diff] [blame] | 3307 |                 if on == 1 and sn == 0: | 
 | 3308 |                     return self._fix(context) | 
 | 3309 |                 if sn == 1 and on == 0: | 
 | 3310 |                     return other._fix(context) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3311 |                 return self._check_nans(other, context) | 
 | 3312 |  | 
| Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 3313 |         c = self.copy_abs()._cmp(other.copy_abs()) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3314 |         if c == 0: | 
 | 3315 |             c = self.compare_total(other) | 
 | 3316 |  | 
 | 3317 |         if c == -1: | 
 | 3318 |             ans = other | 
 | 3319 |         else: | 
 | 3320 |             ans = self | 
 | 3321 |  | 
| Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 3322 |         return ans._fix(context) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3323 |  | 
 | 3324 |     def min_mag(self, other, context=None): | 
 | 3325 |         """Compares the values numerically with their sign ignored.""" | 
 | 3326 |         other = _convert_other(other, raiseit=True) | 
 | 3327 |  | 
 | 3328 |         if context is None: | 
 | 3329 |             context = getcontext() | 
 | 3330 |  | 
 | 3331 |         if self._is_special or other._is_special: | 
 | 3332 |             # If one operand is a quiet NaN and the other is number, then the | 
 | 3333 |             # number is always returned | 
 | 3334 |             sn = self._isnan() | 
 | 3335 |             on = other._isnan() | 
 | 3336 |             if sn or on: | 
| Facundo Batista | 708d581 | 2008-12-11 04:20:07 +0000 | [diff] [blame] | 3337 |                 if on == 1 and sn == 0: | 
 | 3338 |                     return self._fix(context) | 
 | 3339 |                 if sn == 1 and on == 0: | 
 | 3340 |                     return other._fix(context) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3341 |                 return self._check_nans(other, context) | 
 | 3342 |  | 
| Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 3343 |         c = self.copy_abs()._cmp(other.copy_abs()) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3344 |         if c == 0: | 
 | 3345 |             c = self.compare_total(other) | 
 | 3346 |  | 
 | 3347 |         if c == -1: | 
 | 3348 |             ans = self | 
 | 3349 |         else: | 
 | 3350 |             ans = other | 
 | 3351 |  | 
| Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 3352 |         return ans._fix(context) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3353 |  | 
 | 3354 |     def next_minus(self, context=None): | 
 | 3355 |         """Returns the largest representable number smaller than itself.""" | 
 | 3356 |         if context is None: | 
 | 3357 |             context = getcontext() | 
 | 3358 |  | 
 | 3359 |         ans = self._check_nans(context=context) | 
 | 3360 |         if ans: | 
 | 3361 |             return ans | 
 | 3362 |  | 
 | 3363 |         if self._isinfinity() == -1: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3364 |             return _NegativeInfinity | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3365 |         if self._isinfinity() == 1: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3366 |             return _dec_from_triple(0, '9'*context.prec, context.Etop()) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3367 |  | 
 | 3368 |         context = context.copy() | 
 | 3369 |         context._set_rounding(ROUND_FLOOR) | 
 | 3370 |         context._ignore_all_flags() | 
 | 3371 |         new_self = self._fix(context) | 
 | 3372 |         if new_self != self: | 
 | 3373 |             return new_self | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3374 |         return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1), | 
 | 3375 |                             context) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3376 |  | 
 | 3377 |     def next_plus(self, context=None): | 
 | 3378 |         """Returns the smallest representable number larger than itself.""" | 
 | 3379 |         if context is None: | 
 | 3380 |             context = getcontext() | 
 | 3381 |  | 
 | 3382 |         ans = self._check_nans(context=context) | 
 | 3383 |         if ans: | 
 | 3384 |             return ans | 
 | 3385 |  | 
 | 3386 |         if self._isinfinity() == 1: | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3387 |             return _Infinity | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3388 |         if self._isinfinity() == -1: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3389 |             return _dec_from_triple(1, '9'*context.prec, context.Etop()) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3390 |  | 
 | 3391 |         context = context.copy() | 
 | 3392 |         context._set_rounding(ROUND_CEILING) | 
 | 3393 |         context._ignore_all_flags() | 
 | 3394 |         new_self = self._fix(context) | 
 | 3395 |         if new_self != self: | 
 | 3396 |             return new_self | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3397 |         return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1), | 
 | 3398 |                             context) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3399 |  | 
 | 3400 |     def next_toward(self, other, context=None): | 
 | 3401 |         """Returns the number closest to self, in the direction towards other. | 
 | 3402 |  | 
 | 3403 |         The result is the closest representable number to self | 
 | 3404 |         (excluding self) that is in the direction towards other, | 
 | 3405 |         unless both have the same value.  If the two operands are | 
 | 3406 |         numerically equal, then the result is a copy of self with the | 
 | 3407 |         sign set to be the same as the sign of other. | 
 | 3408 |         """ | 
 | 3409 |         other = _convert_other(other, raiseit=True) | 
 | 3410 |  | 
 | 3411 |         if context is None: | 
 | 3412 |             context = getcontext() | 
 | 3413 |  | 
 | 3414 |         ans = self._check_nans(other, context) | 
 | 3415 |         if ans: | 
 | 3416 |             return ans | 
 | 3417 |  | 
| Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 3418 |         comparison = self._cmp(other) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3419 |         if comparison == 0: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3420 |             return self.copy_sign(other) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3421 |  | 
 | 3422 |         if comparison == -1: | 
 | 3423 |             ans = self.next_plus(context) | 
 | 3424 |         else: # comparison == 1 | 
 | 3425 |             ans = self.next_minus(context) | 
 | 3426 |  | 
 | 3427 |         # decide which flags to raise using value of ans | 
 | 3428 |         if ans._isinfinity(): | 
 | 3429 |             context._raise_error(Overflow, | 
 | 3430 |                                  'Infinite result from next_toward', | 
 | 3431 |                                  ans._sign) | 
 | 3432 |             context._raise_error(Rounded) | 
 | 3433 |             context._raise_error(Inexact) | 
 | 3434 |         elif ans.adjusted() < context.Emin: | 
 | 3435 |             context._raise_error(Underflow) | 
 | 3436 |             context._raise_error(Subnormal) | 
 | 3437 |             context._raise_error(Rounded) | 
 | 3438 |             context._raise_error(Inexact) | 
 | 3439 |             # if precision == 1 then we don't raise Clamped for a | 
 | 3440 |             # result 0E-Etiny. | 
 | 3441 |             if not ans: | 
 | 3442 |                 context._raise_error(Clamped) | 
 | 3443 |  | 
 | 3444 |         return ans | 
 | 3445 |  | 
 | 3446 |     def number_class(self, context=None): | 
 | 3447 |         """Returns an indication of the class of self. | 
 | 3448 |  | 
 | 3449 |         The class is one of the following strings: | 
| Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 3450 |           sNaN | 
 | 3451 |           NaN | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3452 |           -Infinity | 
 | 3453 |           -Normal | 
 | 3454 |           -Subnormal | 
 | 3455 |           -Zero | 
 | 3456 |           +Zero | 
 | 3457 |           +Subnormal | 
 | 3458 |           +Normal | 
 | 3459 |           +Infinity | 
 | 3460 |         """ | 
 | 3461 |         if self.is_snan(): | 
 | 3462 |             return "sNaN" | 
 | 3463 |         if self.is_qnan(): | 
 | 3464 |             return "NaN" | 
 | 3465 |         inf = self._isinfinity() | 
 | 3466 |         if inf == 1: | 
 | 3467 |             return "+Infinity" | 
 | 3468 |         if inf == -1: | 
 | 3469 |             return "-Infinity" | 
 | 3470 |         if self.is_zero(): | 
 | 3471 |             if self._sign: | 
 | 3472 |                 return "-Zero" | 
 | 3473 |             else: | 
 | 3474 |                 return "+Zero" | 
 | 3475 |         if context is None: | 
 | 3476 |             context = getcontext() | 
 | 3477 |         if self.is_subnormal(context=context): | 
 | 3478 |             if self._sign: | 
 | 3479 |                 return "-Subnormal" | 
 | 3480 |             else: | 
 | 3481 |                 return "+Subnormal" | 
 | 3482 |         # just a normal, regular, boring number, :) | 
 | 3483 |         if self._sign: | 
 | 3484 |             return "-Normal" | 
 | 3485 |         else: | 
 | 3486 |             return "+Normal" | 
 | 3487 |  | 
 | 3488 |     def radix(self): | 
 | 3489 |         """Just returns 10, as this is Decimal, :)""" | 
 | 3490 |         return Decimal(10) | 
 | 3491 |  | 
 | 3492 |     def rotate(self, other, context=None): | 
 | 3493 |         """Returns a rotated copy of self, value-of-other times.""" | 
 | 3494 |         if context is None: | 
 | 3495 |             context = getcontext() | 
 | 3496 |  | 
 | 3497 |         ans = self._check_nans(other, context) | 
 | 3498 |         if ans: | 
 | 3499 |             return ans | 
 | 3500 |  | 
 | 3501 |         if other._exp != 0: | 
 | 3502 |             return context._raise_error(InvalidOperation) | 
 | 3503 |         if not (-context.prec <= int(other) <= context.prec): | 
 | 3504 |             return context._raise_error(InvalidOperation) | 
 | 3505 |  | 
 | 3506 |         if self._isinfinity(): | 
 | 3507 |             return Decimal(self) | 
 | 3508 |  | 
 | 3509 |         # get values, pad if necessary | 
 | 3510 |         torot = int(other) | 
 | 3511 |         rotdig = self._int | 
 | 3512 |         topad = context.prec - len(rotdig) | 
 | 3513 |         if topad: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3514 |             rotdig = '0'*topad + rotdig | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3515 |  | 
 | 3516 |         # let's rotate! | 
 | 3517 |         rotated = rotdig[torot:] + rotdig[:torot] | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3518 |         return _dec_from_triple(self._sign, | 
 | 3519 |                                 rotated.lstrip('0') or '0', self._exp) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3520 |  | 
 | 3521 |     def scaleb (self, other, context=None): | 
 | 3522 |         """Returns self operand after adding the second value to its exp.""" | 
 | 3523 |         if context is None: | 
 | 3524 |             context = getcontext() | 
 | 3525 |  | 
 | 3526 |         ans = self._check_nans(other, context) | 
 | 3527 |         if ans: | 
 | 3528 |             return ans | 
 | 3529 |  | 
 | 3530 |         if other._exp != 0: | 
 | 3531 |             return context._raise_error(InvalidOperation) | 
 | 3532 |         liminf = -2 * (context.Emax + context.prec) | 
 | 3533 |         limsup =  2 * (context.Emax + context.prec) | 
 | 3534 |         if not (liminf <= int(other) <= limsup): | 
 | 3535 |             return context._raise_error(InvalidOperation) | 
 | 3536 |  | 
 | 3537 |         if self._isinfinity(): | 
 | 3538 |             return Decimal(self) | 
 | 3539 |  | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3540 |         d = _dec_from_triple(self._sign, self._int, self._exp + int(other)) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3541 |         d = d._fix(context) | 
 | 3542 |         return d | 
 | 3543 |  | 
 | 3544 |     def shift(self, other, context=None): | 
 | 3545 |         """Returns a shifted copy of self, value-of-other times.""" | 
 | 3546 |         if context is None: | 
 | 3547 |             context = getcontext() | 
 | 3548 |  | 
 | 3549 |         ans = self._check_nans(other, context) | 
 | 3550 |         if ans: | 
 | 3551 |             return ans | 
 | 3552 |  | 
 | 3553 |         if other._exp != 0: | 
 | 3554 |             return context._raise_error(InvalidOperation) | 
 | 3555 |         if not (-context.prec <= int(other) <= context.prec): | 
 | 3556 |             return context._raise_error(InvalidOperation) | 
 | 3557 |  | 
 | 3558 |         if self._isinfinity(): | 
 | 3559 |             return Decimal(self) | 
 | 3560 |  | 
 | 3561 |         # get values, pad if necessary | 
 | 3562 |         torot = int(other) | 
 | 3563 |         if not torot: | 
 | 3564 |             return Decimal(self) | 
 | 3565 |         rotdig = self._int | 
 | 3566 |         topad = context.prec - len(rotdig) | 
 | 3567 |         if topad: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3568 |             rotdig = '0'*topad + rotdig | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3569 |  | 
 | 3570 |         # let's shift! | 
 | 3571 |         if torot < 0: | 
 | 3572 |             rotated = rotdig[:torot] | 
 | 3573 |         else: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3574 |             rotated = rotdig + '0'*torot | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3575 |             rotated = rotated[-context.prec:] | 
 | 3576 |  | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3577 |         return _dec_from_triple(self._sign, | 
 | 3578 |                                     rotated.lstrip('0') or '0', self._exp) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3579 |  | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3580 |     # Support for pickling, copy, and deepcopy | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3581 |     def __reduce__(self): | 
 | 3582 |         return (self.__class__, (str(self),)) | 
 | 3583 |  | 
 | 3584 |     def __copy__(self): | 
 | 3585 |         if type(self) == Decimal: | 
 | 3586 |             return self     # I'm immutable; therefore I am my own clone | 
 | 3587 |         return self.__class__(str(self)) | 
 | 3588 |  | 
 | 3589 |     def __deepcopy__(self, memo): | 
 | 3590 |         if type(self) == Decimal: | 
 | 3591 |             return self     # My components are also immutable | 
 | 3592 |         return self.__class__(str(self)) | 
 | 3593 |  | 
| Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3594 |     # PEP 3101 support.  See also _parse_format_specifier and _format_align | 
 | 3595 |     def __format__(self, specifier, context=None): | 
 | 3596 |         """Format a Decimal instance according to the given specifier. | 
 | 3597 |  | 
 | 3598 |         The specifier should be a standard format specifier, with the | 
 | 3599 |         form described in PEP 3101.  Formatting types 'e', 'E', 'f', | 
 | 3600 |         'F', 'g', 'G', and '%' are supported.  If the formatting type | 
 | 3601 |         is omitted it defaults to 'g' or 'G', depending on the value | 
 | 3602 |         of context.capitals. | 
 | 3603 |  | 
 | 3604 |         At this time the 'n' format specifier type (which is supposed | 
 | 3605 |         to use the current locale) is not supported. | 
 | 3606 |         """ | 
 | 3607 |  | 
 | 3608 |         # Note: PEP 3101 says that if the type is not present then | 
 | 3609 |         # there should be at least one digit after the decimal point. | 
 | 3610 |         # We take the liberty of ignoring this requirement for | 
 | 3611 |         # Decimal---it's presumably there to make sure that | 
 | 3612 |         # format(float, '') behaves similarly to str(float). | 
 | 3613 |         if context is None: | 
 | 3614 |             context = getcontext() | 
 | 3615 |  | 
 | 3616 |         spec = _parse_format_specifier(specifier) | 
 | 3617 |  | 
 | 3618 |         # special values don't care about the type or precision... | 
 | 3619 |         if self._is_special: | 
 | 3620 |             return _format_align(str(self), spec) | 
 | 3621 |  | 
 | 3622 |         # a type of None defaults to 'g' or 'G', depending on context | 
 | 3623 |         # if type is '%', adjust exponent of self accordingly | 
 | 3624 |         if spec['type'] is None: | 
 | 3625 |             spec['type'] = ['g', 'G'][context.capitals] | 
 | 3626 |         elif spec['type'] == '%': | 
 | 3627 |             self = _dec_from_triple(self._sign, self._int, self._exp+2) | 
 | 3628 |  | 
 | 3629 |         # round if necessary, taking rounding mode from the context | 
 | 3630 |         rounding = context.rounding | 
 | 3631 |         precision = spec['precision'] | 
 | 3632 |         if precision is not None: | 
 | 3633 |             if spec['type'] in 'eE': | 
 | 3634 |                 self = self._round(precision+1, rounding) | 
 | 3635 |             elif spec['type'] in 'gG': | 
 | 3636 |                 if len(self._int) > precision: | 
 | 3637 |                     self = self._round(precision, rounding) | 
 | 3638 |             elif spec['type'] in 'fF%': | 
 | 3639 |                 self = self._rescale(-precision, rounding) | 
 | 3640 |         # special case: zeros with a positive exponent can't be | 
 | 3641 |         # represented in fixed point; rescale them to 0e0. | 
 | 3642 |         elif not self and self._exp > 0 and spec['type'] in 'fF%': | 
 | 3643 |             self = self._rescale(0, rounding) | 
 | 3644 |  | 
 | 3645 |         # figure out placement of the decimal point | 
 | 3646 |         leftdigits = self._exp + len(self._int) | 
 | 3647 |         if spec['type'] in 'fF%': | 
 | 3648 |             dotplace = leftdigits | 
 | 3649 |         elif spec['type'] in 'eE': | 
 | 3650 |             if not self and precision is not None: | 
 | 3651 |                 dotplace = 1 - precision | 
 | 3652 |             else: | 
 | 3653 |                 dotplace = 1 | 
 | 3654 |         elif spec['type'] in 'gG': | 
 | 3655 |             if self._exp <= 0 and leftdigits > -6: | 
 | 3656 |                 dotplace = leftdigits | 
 | 3657 |             else: | 
 | 3658 |                 dotplace = 1 | 
 | 3659 |  | 
 | 3660 |         # figure out main part of numeric string... | 
 | 3661 |         if dotplace <= 0: | 
 | 3662 |             num = '0.' + '0'*(-dotplace) + self._int | 
 | 3663 |         elif dotplace >= len(self._int): | 
 | 3664 |             # make sure we're not padding a '0' with extra zeros on the right | 
 | 3665 |             assert dotplace==len(self._int) or self._int != '0' | 
 | 3666 |             num = self._int + '0'*(dotplace-len(self._int)) | 
 | 3667 |         else: | 
 | 3668 |             num = self._int[:dotplace] + '.' + self._int[dotplace:] | 
 | 3669 |  | 
 | 3670 |         # ...then the trailing exponent, or trailing '%' | 
 | 3671 |         if leftdigits != dotplace or spec['type'] in 'eE': | 
 | 3672 |             echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']] | 
 | 3673 |             num = num + "{0}{1:+}".format(echar, leftdigits-dotplace) | 
 | 3674 |         elif spec['type'] == '%': | 
 | 3675 |             num = num + '%' | 
 | 3676 |  | 
 | 3677 |         # add sign | 
 | 3678 |         if self._sign == 1: | 
 | 3679 |             num = '-' + num | 
 | 3680 |         return _format_align(num, spec) | 
 | 3681 |  | 
 | 3682 |  | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3683 | def _dec_from_triple(sign, coefficient, exponent, special=False): | 
 | 3684 |     """Create a decimal instance directly, without any validation, | 
 | 3685 |     normalization (e.g. removal of leading zeros) or argument | 
 | 3686 |     conversion. | 
 | 3687 |  | 
 | 3688 |     This function is for *internal use only*. | 
 | 3689 |     """ | 
 | 3690 |  | 
 | 3691 |     self = object.__new__(Decimal) | 
 | 3692 |     self._sign = sign | 
 | 3693 |     self._int = coefficient | 
 | 3694 |     self._exp = exponent | 
 | 3695 |     self._is_special = special | 
 | 3696 |  | 
 | 3697 |     return self | 
 | 3698 |  | 
| Raymond Hettinger | 82417ca | 2009-02-03 03:54:28 +0000 | [diff] [blame^] | 3699 | # Register Decimal as a kind of Number (an abstract base class). | 
 | 3700 | # However, do not register it as Real (because Decimals are not | 
 | 3701 | # interoperable with floats). | 
 | 3702 | _numbers.Number.register(Decimal) | 
 | 3703 |  | 
 | 3704 |  | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3705 | ##### Context class ####################################################### | 
| Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 3706 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3707 |  | 
 | 3708 | # get rounding method function: | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3709 | rounding_functions = [name for name in Decimal.__dict__.keys() | 
 | 3710 |                                     if name.startswith('_round_')] | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3711 | for name in rounding_functions: | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3712 |     # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3713 |     globalname = name[1:].upper() | 
 | 3714 |     val = globals()[globalname] | 
 | 3715 |     Decimal._pick_rounding_function[val] = name | 
 | 3716 |  | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3717 | del name, val, globalname, rounding_functions | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3718 |  | 
| Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 3719 | class _ContextManager(object): | 
 | 3720 |     """Context manager class to support localcontext(). | 
| Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 3721 |  | 
| Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 3722 |       Sets a copy of the supplied context in __enter__() and restores | 
 | 3723 |       the previous decimal context in __exit__() | 
| Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 3724 |     """ | 
 | 3725 |     def __init__(self, new_context): | 
| Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 3726 |         self.new_context = new_context.copy() | 
| Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 3727 |     def __enter__(self): | 
 | 3728 |         self.saved_context = getcontext() | 
 | 3729 |         setcontext(self.new_context) | 
 | 3730 |         return self.new_context | 
 | 3731 |     def __exit__(self, t, v, tb): | 
 | 3732 |         setcontext(self.saved_context) | 
| Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 3733 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3734 | class Context(object): | 
 | 3735 |     """Contains the context for a Decimal instance. | 
 | 3736 |  | 
 | 3737 |     Contains: | 
 | 3738 |     prec - precision (for use in rounding, division, square roots..) | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3739 |     rounding - rounding type (how you round) | 
| Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3740 |     traps - If traps[exception] = 1, then the exception is | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3741 |                     raised when it is caused.  Otherwise, a value is | 
 | 3742 |                     substituted in. | 
| Raymond Hettinger | 86173da | 2008-02-01 20:38:12 +0000 | [diff] [blame] | 3743 |     flags  - When an exception is caused, flags[exception] is set. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3744 |              (Whether or not the trap_enabler is set) | 
 | 3745 |              Should be reset by user of Decimal instance. | 
| Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 3746 |     Emin -   Minimum exponent | 
 | 3747 |     Emax -   Maximum exponent | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3748 |     capitals -      If 1, 1*10^1 is printed as 1E+1. | 
 | 3749 |                     If 0, printed as 1e1 | 
| Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 3750 |     _clamp - If 1, change exponents if too high (Default 0) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3751 |     """ | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3752 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3753 |     def __init__(self, prec=None, rounding=None, | 
| Raymond Hettinger | abf8a56 | 2004-10-12 09:12:16 +0000 | [diff] [blame] | 3754 |                  traps=None, flags=None, | 
| Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 3755 |                  Emin=None, Emax=None, | 
| Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 3756 |                  capitals=None, _clamp=0, | 
| Raymond Hettinger | abf8a56 | 2004-10-12 09:12:16 +0000 | [diff] [blame] | 3757 |                  _ignored_flags=None): | 
 | 3758 |         if flags is None: | 
 | 3759 |             flags = [] | 
 | 3760 |         if _ignored_flags is None: | 
 | 3761 |             _ignored_flags = [] | 
| Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3762 |         if not isinstance(flags, dict): | 
| Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 3763 |             flags = dict([(s, int(s in flags)) for s in _signals]) | 
| Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3764 |         if traps is not None and not isinstance(traps, dict): | 
| Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 3765 |             traps = dict([(s, int(s in traps)) for s in _signals]) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3766 |         for name, val in locals().items(): | 
 | 3767 |             if val is None: | 
| Raymond Hettinger | eb26084 | 2005-06-07 18:52:34 +0000 | [diff] [blame] | 3768 |                 setattr(self, name, _copy.copy(getattr(DefaultContext, name))) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3769 |             else: | 
 | 3770 |                 setattr(self, name, val) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3771 |         del self.self | 
 | 3772 |  | 
| Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 3773 |     def __repr__(self): | 
| Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3774 |         """Show the current context.""" | 
| Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 3775 |         s = [] | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3776 |         s.append('Context(prec=%(prec)d, rounding=%(rounding)s, ' | 
 | 3777 |                  'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d' | 
 | 3778 |                  % vars(self)) | 
 | 3779 |         names = [f.__name__ for f, v in self.flags.items() if v] | 
 | 3780 |         s.append('flags=[' + ', '.join(names) + ']') | 
 | 3781 |         names = [t.__name__ for t, v in self.traps.items() if v] | 
 | 3782 |         s.append('traps=[' + ', '.join(names) + ']') | 
| Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 3783 |         return ', '.join(s) + ')' | 
 | 3784 |  | 
| Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 3785 |     def clear_flags(self): | 
 | 3786 |         """Reset all flags to zero""" | 
 | 3787 |         for flag in self.flags: | 
| Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 3788 |             self.flags[flag] = 0 | 
| Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 3789 |  | 
| Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 3790 |     def _shallow_copy(self): | 
 | 3791 |         """Returns a shallow copy from self.""" | 
| Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 3792 |         nc = Context(self.prec, self.rounding, self.traps, | 
 | 3793 |                      self.flags, self.Emin, self.Emax, | 
 | 3794 |                      self.capitals, self._clamp, self._ignored_flags) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3795 |         return nc | 
| Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 3796 |  | 
 | 3797 |     def copy(self): | 
 | 3798 |         """Returns a deep copy from self.""" | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3799 |         nc = Context(self.prec, self.rounding, self.traps.copy(), | 
| Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 3800 |                      self.flags.copy(), self.Emin, self.Emax, | 
 | 3801 |                      self.capitals, self._clamp, self._ignored_flags) | 
| Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 3802 |         return nc | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3803 |     __copy__ = copy | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3804 |  | 
| Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 3805 |     def _raise_error(self, condition, explanation = None, *args): | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3806 |         """Handles an error | 
 | 3807 |  | 
 | 3808 |         If the flag is in _ignored_flags, returns the default response. | 
| Raymond Hettinger | 86173da | 2008-02-01 20:38:12 +0000 | [diff] [blame] | 3809 |         Otherwise, it sets the flag, then, if the corresponding | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3810 |         trap_enabler is set, it reaises the exception.  Otherwise, it returns | 
| Raymond Hettinger | 86173da | 2008-02-01 20:38:12 +0000 | [diff] [blame] | 3811 |         the default value after setting the flag. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3812 |         """ | 
| Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 3813 |         error = _condition_map.get(condition, condition) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3814 |         if error in self._ignored_flags: | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3815 |             # Don't touch the flag | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3816 |             return error().handle(self, *args) | 
 | 3817 |  | 
| Raymond Hettinger | 86173da | 2008-02-01 20:38:12 +0000 | [diff] [blame] | 3818 |         self.flags[error] = 1 | 
| Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3819 |         if not self.traps[error]: | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3820 |             # The errors define how to handle themselves. | 
| Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 3821 |             return condition().handle(self, *args) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3822 |  | 
 | 3823 |         # Errors should only be risked on copies of the context | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3824 |         # self._ignored_flags = [] | 
| Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 3825 |         raise error(explanation) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3826 |  | 
 | 3827 |     def _ignore_all_flags(self): | 
 | 3828 |         """Ignore all flags, if they are raised""" | 
| Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 3829 |         return self._ignore_flags(*_signals) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3830 |  | 
 | 3831 |     def _ignore_flags(self, *flags): | 
 | 3832 |         """Ignore the flags, if they are raised""" | 
 | 3833 |         # Do not mutate-- This way, copies of a context leave the original | 
 | 3834 |         # alone. | 
 | 3835 |         self._ignored_flags = (self._ignored_flags + list(flags)) | 
 | 3836 |         return list(flags) | 
 | 3837 |  | 
 | 3838 |     def _regard_flags(self, *flags): | 
 | 3839 |         """Stop ignoring the flags, if they are raised""" | 
 | 3840 |         if flags and isinstance(flags[0], (tuple,list)): | 
 | 3841 |             flags = flags[0] | 
 | 3842 |         for flag in flags: | 
 | 3843 |             self._ignored_flags.remove(flag) | 
 | 3844 |  | 
| Nick Coghlan | d1abd25 | 2008-07-15 15:46:38 +0000 | [diff] [blame] | 3845 |     # We inherit object.__hash__, so we must deny this explicitly | 
 | 3846 |     __hash__ = None | 
| Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 3847 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3848 |     def Etiny(self): | 
 | 3849 |         """Returns Etiny (= Emin - prec + 1)""" | 
 | 3850 |         return int(self.Emin - self.prec + 1) | 
 | 3851 |  | 
 | 3852 |     def Etop(self): | 
| Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 3853 |         """Returns maximum exponent (= Emax - prec + 1)""" | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3854 |         return int(self.Emax - self.prec + 1) | 
 | 3855 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3856 |     def _set_rounding(self, type): | 
 | 3857 |         """Sets the rounding type. | 
 | 3858 |  | 
 | 3859 |         Sets the rounding type, and returns the current (previous) | 
 | 3860 |         rounding type.  Often used like: | 
 | 3861 |  | 
 | 3862 |         context = context.copy() | 
 | 3863 |         # so you don't change the calling context | 
 | 3864 |         # if an error occurs in the middle. | 
 | 3865 |         rounding = context._set_rounding(ROUND_UP) | 
 | 3866 |         val = self.__sub__(other, context=context) | 
 | 3867 |         context._set_rounding(rounding) | 
 | 3868 |  | 
 | 3869 |         This will make it round up for that operation. | 
 | 3870 |         """ | 
 | 3871 |         rounding = self.rounding | 
 | 3872 |         self.rounding= type | 
 | 3873 |         return rounding | 
 | 3874 |  | 
| Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 3875 |     def create_decimal(self, num='0'): | 
| Christian Heimes | a62da1d | 2008-01-12 19:39:10 +0000 | [diff] [blame] | 3876 |         """Creates a new Decimal instance but using self as context. | 
 | 3877 |  | 
 | 3878 |         This method implements the to-number operation of the | 
 | 3879 |         IBM Decimal specification.""" | 
 | 3880 |  | 
 | 3881 |         if isinstance(num, str) and num != num.strip(): | 
 | 3882 |             return self._raise_error(ConversionSyntax, | 
 | 3883 |                                      "no trailing or leading whitespace is " | 
 | 3884 |                                      "permitted.") | 
 | 3885 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3886 |         d = Decimal(num, context=self) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3887 |         if d._isnan() and len(d._int) > self.prec - self._clamp: | 
 | 3888 |             return self._raise_error(ConversionSyntax, | 
 | 3889 |                                      "diagnostic info too long in NaN") | 
| Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 3890 |         return d._fix(self) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3891 |  | 
| Raymond Hettinger | 771ed76 | 2009-01-03 19:20:32 +0000 | [diff] [blame] | 3892 |     def create_decimal_from_float(self, f): | 
 | 3893 |         """Creates a new Decimal instance from a float but rounding using self | 
 | 3894 |         as the context. | 
 | 3895 |  | 
 | 3896 |         >>> context = Context(prec=5, rounding=ROUND_DOWN) | 
 | 3897 |         >>> context.create_decimal_from_float(3.1415926535897932) | 
 | 3898 |         Decimal('3.1415') | 
 | 3899 |         >>> context = Context(prec=5, traps=[Inexact]) | 
 | 3900 |         >>> context.create_decimal_from_float(3.1415926535897932) | 
 | 3901 |         Traceback (most recent call last): | 
 | 3902 |             ... | 
 | 3903 |         decimal.Inexact: None | 
 | 3904 |  | 
 | 3905 |         """ | 
 | 3906 |         d = Decimal.from_float(f)       # An exact conversion | 
 | 3907 |         return d._fix(self)             # Apply the context rounding | 
 | 3908 |  | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3909 |     # Methods | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3910 |     def abs(self, a): | 
 | 3911 |         """Returns the absolute value of the operand. | 
 | 3912 |  | 
 | 3913 |         If the operand is negative, the result is the same as using the minus | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3914 |         operation on the operand.  Otherwise, the result is the same as using | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3915 |         the plus operation on the operand. | 
 | 3916 |  | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3917 |         >>> ExtendedContext.abs(Decimal('2.1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3918 |         Decimal('2.1') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3919 |         >>> ExtendedContext.abs(Decimal('-100')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3920 |         Decimal('100') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3921 |         >>> ExtendedContext.abs(Decimal('101.5')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3922 |         Decimal('101.5') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3923 |         >>> ExtendedContext.abs(Decimal('-101.5')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3924 |         Decimal('101.5') | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3925 |         """ | 
 | 3926 |         return a.__abs__(context=self) | 
 | 3927 |  | 
 | 3928 |     def add(self, a, b): | 
 | 3929 |         """Return the sum of the two operands. | 
 | 3930 |  | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3931 |         >>> ExtendedContext.add(Decimal('12'), Decimal('7.00')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3932 |         Decimal('19.00') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3933 |         >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3934 |         Decimal('1.02E+4') | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3935 |         """ | 
 | 3936 |         return a.__add__(b, context=self) | 
 | 3937 |  | 
 | 3938 |     def _apply(self, a): | 
| Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 3939 |         return str(a._fix(self)) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3940 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3941 |     def canonical(self, a): | 
 | 3942 |         """Returns the same Decimal object. | 
 | 3943 |  | 
 | 3944 |         As we do not have different encodings for the same number, the | 
 | 3945 |         received object already is in its canonical form. | 
 | 3946 |  | 
 | 3947 |         >>> ExtendedContext.canonical(Decimal('2.50')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3948 |         Decimal('2.50') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3949 |         """ | 
 | 3950 |         return a.canonical(context=self) | 
 | 3951 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3952 |     def compare(self, a, b): | 
 | 3953 |         """Compares values numerically. | 
 | 3954 |  | 
 | 3955 |         If the signs of the operands differ, a value representing each operand | 
 | 3956 |         ('-1' if the operand is less than zero, '0' if the operand is zero or | 
 | 3957 |         negative zero, or '1' if the operand is greater than zero) is used in | 
 | 3958 |         place of that operand for the comparison instead of the actual | 
 | 3959 |         operand. | 
 | 3960 |  | 
 | 3961 |         The comparison is then effected by subtracting the second operand from | 
 | 3962 |         the first and then returning a value according to the result of the | 
 | 3963 |         subtraction: '-1' if the result is less than zero, '0' if the result is | 
 | 3964 |         zero or negative zero, or '1' if the result is greater than zero. | 
 | 3965 |  | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3966 |         >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3967 |         Decimal('-1') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3968 |         >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3969 |         Decimal('0') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3970 |         >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3971 |         Decimal('0') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3972 |         >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3973 |         Decimal('1') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3974 |         >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3975 |         Decimal('1') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3976 |         >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3977 |         Decimal('-1') | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3978 |         """ | 
 | 3979 |         return a.compare(b, context=self) | 
 | 3980 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3981 |     def compare_signal(self, a, b): | 
 | 3982 |         """Compares the values of the two operands numerically. | 
 | 3983 |  | 
 | 3984 |         It's pretty much like compare(), but all NaNs signal, with signaling | 
 | 3985 |         NaNs taking precedence over quiet NaNs. | 
 | 3986 |  | 
 | 3987 |         >>> c = ExtendedContext | 
 | 3988 |         >>> c.compare_signal(Decimal('2.1'), Decimal('3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3989 |         Decimal('-1') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3990 |         >>> c.compare_signal(Decimal('2.1'), Decimal('2.1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3991 |         Decimal('0') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3992 |         >>> c.flags[InvalidOperation] = 0 | 
 | 3993 |         >>> print(c.flags[InvalidOperation]) | 
 | 3994 |         0 | 
 | 3995 |         >>> c.compare_signal(Decimal('NaN'), Decimal('2.1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3996 |         Decimal('NaN') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3997 |         >>> print(c.flags[InvalidOperation]) | 
 | 3998 |         1 | 
 | 3999 |         >>> c.flags[InvalidOperation] = 0 | 
 | 4000 |         >>> print(c.flags[InvalidOperation]) | 
 | 4001 |         0 | 
 | 4002 |         >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4003 |         Decimal('NaN') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4004 |         >>> print(c.flags[InvalidOperation]) | 
 | 4005 |         1 | 
 | 4006 |         """ | 
 | 4007 |         return a.compare_signal(b, context=self) | 
 | 4008 |  | 
 | 4009 |     def compare_total(self, a, b): | 
 | 4010 |         """Compares two operands using their abstract representation. | 
 | 4011 |  | 
 | 4012 |         This is not like the standard compare, which use their numerical | 
 | 4013 |         value. Note that a total ordering is defined for all possible abstract | 
 | 4014 |         representations. | 
 | 4015 |  | 
 | 4016 |         >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4017 |         Decimal('-1') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4018 |         >>> ExtendedContext.compare_total(Decimal('-127'),  Decimal('12')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4019 |         Decimal('-1') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4020 |         >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4021 |         Decimal('-1') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4022 |         >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4023 |         Decimal('0') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4024 |         >>> ExtendedContext.compare_total(Decimal('12.3'),  Decimal('12.300')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4025 |         Decimal('1') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4026 |         >>> ExtendedContext.compare_total(Decimal('12.3'),  Decimal('NaN')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4027 |         Decimal('-1') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4028 |         """ | 
 | 4029 |         return a.compare_total(b) | 
 | 4030 |  | 
 | 4031 |     def compare_total_mag(self, a, b): | 
 | 4032 |         """Compares two operands using their abstract representation ignoring sign. | 
 | 4033 |  | 
 | 4034 |         Like compare_total, but with operand's sign ignored and assumed to be 0. | 
 | 4035 |         """ | 
 | 4036 |         return a.compare_total_mag(b) | 
 | 4037 |  | 
 | 4038 |     def copy_abs(self, a): | 
 | 4039 |         """Returns a copy of the operand with the sign set to 0. | 
 | 4040 |  | 
 | 4041 |         >>> ExtendedContext.copy_abs(Decimal('2.1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4042 |         Decimal('2.1') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4043 |         >>> ExtendedContext.copy_abs(Decimal('-100')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4044 |         Decimal('100') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4045 |         """ | 
 | 4046 |         return a.copy_abs() | 
 | 4047 |  | 
 | 4048 |     def copy_decimal(self, a): | 
 | 4049 |         """Returns a copy of the decimal objet. | 
 | 4050 |  | 
 | 4051 |         >>> ExtendedContext.copy_decimal(Decimal('2.1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4052 |         Decimal('2.1') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4053 |         >>> ExtendedContext.copy_decimal(Decimal('-1.00')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4054 |         Decimal('-1.00') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4055 |         """ | 
 | 4056 |         return Decimal(a) | 
 | 4057 |  | 
 | 4058 |     def copy_negate(self, a): | 
 | 4059 |         """Returns a copy of the operand with the sign inverted. | 
 | 4060 |  | 
 | 4061 |         >>> ExtendedContext.copy_negate(Decimal('101.5')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4062 |         Decimal('-101.5') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4063 |         >>> ExtendedContext.copy_negate(Decimal('-101.5')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4064 |         Decimal('101.5') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4065 |         """ | 
 | 4066 |         return a.copy_negate() | 
 | 4067 |  | 
 | 4068 |     def copy_sign(self, a, b): | 
 | 4069 |         """Copies the second operand's sign to the first one. | 
 | 4070 |  | 
 | 4071 |         In detail, it returns a copy of the first operand with the sign | 
 | 4072 |         equal to the sign of the second operand. | 
 | 4073 |  | 
 | 4074 |         >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4075 |         Decimal('1.50') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4076 |         >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4077 |         Decimal('1.50') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4078 |         >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4079 |         Decimal('-1.50') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4080 |         >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4081 |         Decimal('-1.50') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4082 |         """ | 
 | 4083 |         return a.copy_sign(b) | 
 | 4084 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4085 |     def divide(self, a, b): | 
 | 4086 |         """Decimal division in a specified context. | 
 | 4087 |  | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4088 |         >>> ExtendedContext.divide(Decimal('1'), Decimal('3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4089 |         Decimal('0.333333333') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4090 |         >>> ExtendedContext.divide(Decimal('2'), Decimal('3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4091 |         Decimal('0.666666667') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4092 |         >>> ExtendedContext.divide(Decimal('5'), Decimal('2')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4093 |         Decimal('2.5') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4094 |         >>> ExtendedContext.divide(Decimal('1'), Decimal('10')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4095 |         Decimal('0.1') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4096 |         >>> ExtendedContext.divide(Decimal('12'), Decimal('12')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4097 |         Decimal('1') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4098 |         >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4099 |         Decimal('4.00') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4100 |         >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4101 |         Decimal('1.20') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4102 |         >>> ExtendedContext.divide(Decimal('1000'), Decimal('100')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4103 |         Decimal('10') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4104 |         >>> ExtendedContext.divide(Decimal('1000'), Decimal('1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4105 |         Decimal('1000') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4106 |         >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4107 |         Decimal('1.20E+6') | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4108 |         """ | 
| Neal Norwitz | bcc0db8 | 2006-03-24 08:14:36 +0000 | [diff] [blame] | 4109 |         return a.__truediv__(b, context=self) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4110 |  | 
 | 4111 |     def divide_int(self, a, b): | 
 | 4112 |         """Divides two numbers and returns the integer part of the result. | 
 | 4113 |  | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4114 |         >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4115 |         Decimal('0') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4116 |         >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4117 |         Decimal('3') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4118 |         >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4119 |         Decimal('3') | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4120 |         """ | 
 | 4121 |         return a.__floordiv__(b, context=self) | 
 | 4122 |  | 
 | 4123 |     def divmod(self, a, b): | 
 | 4124 |         return a.__divmod__(b, context=self) | 
 | 4125 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4126 |     def exp(self, a): | 
 | 4127 |         """Returns e ** a. | 
 | 4128 |  | 
 | 4129 |         >>> c = ExtendedContext.copy() | 
 | 4130 |         >>> c.Emin = -999 | 
 | 4131 |         >>> c.Emax = 999 | 
 | 4132 |         >>> c.exp(Decimal('-Infinity')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4133 |         Decimal('0') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4134 |         >>> c.exp(Decimal('-1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4135 |         Decimal('0.367879441') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4136 |         >>> c.exp(Decimal('0')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4137 |         Decimal('1') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4138 |         >>> c.exp(Decimal('1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4139 |         Decimal('2.71828183') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4140 |         >>> c.exp(Decimal('0.693147181')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4141 |         Decimal('2.00000000') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4142 |         >>> c.exp(Decimal('+Infinity')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4143 |         Decimal('Infinity') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4144 |         """ | 
 | 4145 |         return a.exp(context=self) | 
 | 4146 |  | 
 | 4147 |     def fma(self, a, b, c): | 
 | 4148 |         """Returns a multiplied by b, plus c. | 
 | 4149 |  | 
 | 4150 |         The first two operands are multiplied together, using multiply, | 
 | 4151 |         the third operand is then added to the result of that | 
 | 4152 |         multiplication, using add, all with only one final rounding. | 
 | 4153 |  | 
 | 4154 |         >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4155 |         Decimal('22') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4156 |         >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4157 |         Decimal('-8') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4158 |         >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4159 |         Decimal('1.38435736E+12') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4160 |         """ | 
 | 4161 |         return a.fma(b, c, context=self) | 
 | 4162 |  | 
 | 4163 |     def is_canonical(self, a): | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4164 |         """Return True if the operand is canonical; otherwise return False. | 
 | 4165 |  | 
 | 4166 |         Currently, the encoding of a Decimal instance is always | 
 | 4167 |         canonical, so this method returns True for any Decimal. | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4168 |  | 
 | 4169 |         >>> ExtendedContext.is_canonical(Decimal('2.50')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4170 |         True | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4171 |         """ | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4172 |         return a.is_canonical() | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4173 |  | 
 | 4174 |     def is_finite(self, a): | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4175 |         """Return True if the operand is finite; otherwise return False. | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4176 |  | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4177 |         A Decimal instance is considered finite if it is neither | 
 | 4178 |         infinite nor a NaN. | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4179 |  | 
 | 4180 |         >>> ExtendedContext.is_finite(Decimal('2.50')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4181 |         True | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4182 |         >>> ExtendedContext.is_finite(Decimal('-0.3')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4183 |         True | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4184 |         >>> ExtendedContext.is_finite(Decimal('0')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4185 |         True | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4186 |         >>> ExtendedContext.is_finite(Decimal('Inf')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4187 |         False | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4188 |         >>> ExtendedContext.is_finite(Decimal('NaN')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4189 |         False | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4190 |         """ | 
 | 4191 |         return a.is_finite() | 
 | 4192 |  | 
 | 4193 |     def is_infinite(self, a): | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4194 |         """Return True if the operand is infinite; otherwise return False. | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4195 |  | 
 | 4196 |         >>> ExtendedContext.is_infinite(Decimal('2.50')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4197 |         False | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4198 |         >>> ExtendedContext.is_infinite(Decimal('-Inf')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4199 |         True | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4200 |         >>> ExtendedContext.is_infinite(Decimal('NaN')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4201 |         False | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4202 |         """ | 
 | 4203 |         return a.is_infinite() | 
 | 4204 |  | 
 | 4205 |     def is_nan(self, a): | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4206 |         """Return True if the operand is a qNaN or sNaN; | 
 | 4207 |         otherwise return False. | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4208 |  | 
 | 4209 |         >>> ExtendedContext.is_nan(Decimal('2.50')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4210 |         False | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4211 |         >>> ExtendedContext.is_nan(Decimal('NaN')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4212 |         True | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4213 |         >>> ExtendedContext.is_nan(Decimal('-sNaN')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4214 |         True | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4215 |         """ | 
 | 4216 |         return a.is_nan() | 
 | 4217 |  | 
 | 4218 |     def is_normal(self, a): | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4219 |         """Return True if the operand is a normal number; | 
 | 4220 |         otherwise return False. | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4221 |  | 
 | 4222 |         >>> c = ExtendedContext.copy() | 
 | 4223 |         >>> c.Emin = -999 | 
 | 4224 |         >>> c.Emax = 999 | 
 | 4225 |         >>> c.is_normal(Decimal('2.50')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4226 |         True | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4227 |         >>> c.is_normal(Decimal('0.1E-999')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4228 |         False | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4229 |         >>> c.is_normal(Decimal('0.00')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4230 |         False | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4231 |         >>> c.is_normal(Decimal('-Inf')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4232 |         False | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4233 |         >>> c.is_normal(Decimal('NaN')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4234 |         False | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4235 |         """ | 
 | 4236 |         return a.is_normal(context=self) | 
 | 4237 |  | 
 | 4238 |     def is_qnan(self, a): | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4239 |         """Return True if the operand is a quiet NaN; otherwise return False. | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4240 |  | 
 | 4241 |         >>> ExtendedContext.is_qnan(Decimal('2.50')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4242 |         False | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4243 |         >>> ExtendedContext.is_qnan(Decimal('NaN')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4244 |         True | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4245 |         >>> ExtendedContext.is_qnan(Decimal('sNaN')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4246 |         False | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4247 |         """ | 
 | 4248 |         return a.is_qnan() | 
 | 4249 |  | 
 | 4250 |     def is_signed(self, a): | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4251 |         """Return True if the operand is negative; otherwise return False. | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4252 |  | 
 | 4253 |         >>> ExtendedContext.is_signed(Decimal('2.50')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4254 |         False | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4255 |         >>> ExtendedContext.is_signed(Decimal('-12')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4256 |         True | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4257 |         >>> ExtendedContext.is_signed(Decimal('-0')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4258 |         True | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4259 |         """ | 
 | 4260 |         return a.is_signed() | 
 | 4261 |  | 
 | 4262 |     def is_snan(self, a): | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4263 |         """Return True if the operand is a signaling NaN; | 
 | 4264 |         otherwise return False. | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4265 |  | 
 | 4266 |         >>> ExtendedContext.is_snan(Decimal('2.50')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4267 |         False | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4268 |         >>> ExtendedContext.is_snan(Decimal('NaN')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4269 |         False | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4270 |         >>> ExtendedContext.is_snan(Decimal('sNaN')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4271 |         True | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4272 |         """ | 
 | 4273 |         return a.is_snan() | 
 | 4274 |  | 
 | 4275 |     def is_subnormal(self, a): | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4276 |         """Return True if the operand is subnormal; otherwise return False. | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4277 |  | 
 | 4278 |         >>> c = ExtendedContext.copy() | 
 | 4279 |         >>> c.Emin = -999 | 
 | 4280 |         >>> c.Emax = 999 | 
 | 4281 |         >>> c.is_subnormal(Decimal('2.50')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4282 |         False | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4283 |         >>> c.is_subnormal(Decimal('0.1E-999')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4284 |         True | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4285 |         >>> c.is_subnormal(Decimal('0.00')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4286 |         False | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4287 |         >>> c.is_subnormal(Decimal('-Inf')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4288 |         False | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4289 |         >>> c.is_subnormal(Decimal('NaN')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4290 |         False | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4291 |         """ | 
 | 4292 |         return a.is_subnormal(context=self) | 
 | 4293 |  | 
 | 4294 |     def is_zero(self, a): | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4295 |         """Return True if the operand is a zero; otherwise return False. | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4296 |  | 
 | 4297 |         >>> ExtendedContext.is_zero(Decimal('0')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4298 |         True | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4299 |         >>> ExtendedContext.is_zero(Decimal('2.50')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4300 |         False | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4301 |         >>> ExtendedContext.is_zero(Decimal('-0E+2')) | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4302 |         True | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4303 |         """ | 
 | 4304 |         return a.is_zero() | 
 | 4305 |  | 
 | 4306 |     def ln(self, a): | 
 | 4307 |         """Returns the natural (base e) logarithm of the operand. | 
 | 4308 |  | 
 | 4309 |         >>> c = ExtendedContext.copy() | 
 | 4310 |         >>> c.Emin = -999 | 
 | 4311 |         >>> c.Emax = 999 | 
 | 4312 |         >>> c.ln(Decimal('0')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4313 |         Decimal('-Infinity') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4314 |         >>> c.ln(Decimal('1.000')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4315 |         Decimal('0') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4316 |         >>> c.ln(Decimal('2.71828183')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4317 |         Decimal('1.00000000') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4318 |         >>> c.ln(Decimal('10')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4319 |         Decimal('2.30258509') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4320 |         >>> c.ln(Decimal('+Infinity')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4321 |         Decimal('Infinity') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4322 |         """ | 
 | 4323 |         return a.ln(context=self) | 
 | 4324 |  | 
 | 4325 |     def log10(self, a): | 
 | 4326 |         """Returns the base 10 logarithm of the operand. | 
 | 4327 |  | 
 | 4328 |         >>> c = ExtendedContext.copy() | 
 | 4329 |         >>> c.Emin = -999 | 
 | 4330 |         >>> c.Emax = 999 | 
 | 4331 |         >>> c.log10(Decimal('0')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4332 |         Decimal('-Infinity') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4333 |         >>> c.log10(Decimal('0.001')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4334 |         Decimal('-3') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4335 |         >>> c.log10(Decimal('1.000')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4336 |         Decimal('0') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4337 |         >>> c.log10(Decimal('2')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4338 |         Decimal('0.301029996') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4339 |         >>> c.log10(Decimal('10')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4340 |         Decimal('1') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4341 |         >>> c.log10(Decimal('70')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4342 |         Decimal('1.84509804') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4343 |         >>> c.log10(Decimal('+Infinity')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4344 |         Decimal('Infinity') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4345 |         """ | 
 | 4346 |         return a.log10(context=self) | 
 | 4347 |  | 
 | 4348 |     def logb(self, a): | 
 | 4349 |         """ Returns the exponent of the magnitude of the operand's MSD. | 
 | 4350 |  | 
 | 4351 |         The result is the integer which is the exponent of the magnitude | 
 | 4352 |         of the most significant digit of the operand (as though the | 
 | 4353 |         operand were truncated to a single digit while maintaining the | 
 | 4354 |         value of that digit and without limiting the resulting exponent). | 
 | 4355 |  | 
 | 4356 |         >>> ExtendedContext.logb(Decimal('250')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4357 |         Decimal('2') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4358 |         >>> ExtendedContext.logb(Decimal('2.50')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4359 |         Decimal('0') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4360 |         >>> ExtendedContext.logb(Decimal('0.03')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4361 |         Decimal('-2') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4362 |         >>> ExtendedContext.logb(Decimal('0')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4363 |         Decimal('-Infinity') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4364 |         """ | 
 | 4365 |         return a.logb(context=self) | 
 | 4366 |  | 
 | 4367 |     def logical_and(self, a, b): | 
 | 4368 |         """Applies the logical operation 'and' between each operand's digits. | 
 | 4369 |  | 
 | 4370 |         The operands must be both logical numbers. | 
 | 4371 |  | 
 | 4372 |         >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4373 |         Decimal('0') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4374 |         >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4375 |         Decimal('0') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4376 |         >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4377 |         Decimal('0') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4378 |         >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4379 |         Decimal('1') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4380 |         >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4381 |         Decimal('1000') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4382 |         >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4383 |         Decimal('10') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4384 |         """ | 
 | 4385 |         return a.logical_and(b, context=self) | 
 | 4386 |  | 
 | 4387 |     def logical_invert(self, a): | 
 | 4388 |         """Invert all the digits in the operand. | 
 | 4389 |  | 
 | 4390 |         The operand must be a logical number. | 
 | 4391 |  | 
 | 4392 |         >>> ExtendedContext.logical_invert(Decimal('0')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4393 |         Decimal('111111111') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4394 |         >>> ExtendedContext.logical_invert(Decimal('1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4395 |         Decimal('111111110') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4396 |         >>> ExtendedContext.logical_invert(Decimal('111111111')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4397 |         Decimal('0') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4398 |         >>> ExtendedContext.logical_invert(Decimal('101010101')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4399 |         Decimal('10101010') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4400 |         """ | 
 | 4401 |         return a.logical_invert(context=self) | 
 | 4402 |  | 
 | 4403 |     def logical_or(self, a, b): | 
 | 4404 |         """Applies the logical operation 'or' between each operand's digits. | 
 | 4405 |  | 
 | 4406 |         The operands must be both logical numbers. | 
 | 4407 |  | 
 | 4408 |         >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4409 |         Decimal('0') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4410 |         >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4411 |         Decimal('1') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4412 |         >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4413 |         Decimal('1') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4414 |         >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4415 |         Decimal('1') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4416 |         >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4417 |         Decimal('1110') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4418 |         >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4419 |         Decimal('1110') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4420 |         """ | 
 | 4421 |         return a.logical_or(b, context=self) | 
 | 4422 |  | 
 | 4423 |     def logical_xor(self, a, b): | 
 | 4424 |         """Applies the logical operation 'xor' between each operand's digits. | 
 | 4425 |  | 
 | 4426 |         The operands must be both logical numbers. | 
 | 4427 |  | 
 | 4428 |         >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4429 |         Decimal('0') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4430 |         >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4431 |         Decimal('1') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4432 |         >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4433 |         Decimal('1') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4434 |         >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4435 |         Decimal('0') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4436 |         >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4437 |         Decimal('110') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4438 |         >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4439 |         Decimal('1101') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4440 |         """ | 
 | 4441 |         return a.logical_xor(b, context=self) | 
 | 4442 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4443 |     def max(self, a,b): | 
 | 4444 |         """max compares two values numerically and returns the maximum. | 
 | 4445 |  | 
 | 4446 |         If either operand is a NaN then the general rules apply. | 
| Christian Heimes | 679db4a | 2008-01-18 09:56:22 +0000 | [diff] [blame] | 4447 |         Otherwise, the operands are compared as though by the compare | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 4448 |         operation.  If they are numerically equal then the left-hand operand | 
 | 4449 |         is chosen as the result.  Otherwise the maximum (closer to positive | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4450 |         infinity) of the two operands is chosen as the result. | 
 | 4451 |  | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4452 |         >>> ExtendedContext.max(Decimal('3'), Decimal('2')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4453 |         Decimal('3') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4454 |         >>> ExtendedContext.max(Decimal('-10'), Decimal('3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4455 |         Decimal('3') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4456 |         >>> ExtendedContext.max(Decimal('1.0'), Decimal('1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4457 |         Decimal('1') | 
| Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 4458 |         >>> ExtendedContext.max(Decimal('7'), Decimal('NaN')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4459 |         Decimal('7') | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4460 |         """ | 
 | 4461 |         return a.max(b, context=self) | 
 | 4462 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4463 |     def max_mag(self, a, b): | 
 | 4464 |         """Compares the values numerically with their sign ignored.""" | 
 | 4465 |         return a.max_mag(b, context=self) | 
 | 4466 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4467 |     def min(self, a,b): | 
 | 4468 |         """min compares two values numerically and returns the minimum. | 
 | 4469 |  | 
 | 4470 |         If either operand is a NaN then the general rules apply. | 
| Christian Heimes | 679db4a | 2008-01-18 09:56:22 +0000 | [diff] [blame] | 4471 |         Otherwise, the operands are compared as though by the compare | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 4472 |         operation.  If they are numerically equal then the left-hand operand | 
 | 4473 |         is chosen as the result.  Otherwise the minimum (closer to negative | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4474 |         infinity) of the two operands is chosen as the result. | 
 | 4475 |  | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4476 |         >>> ExtendedContext.min(Decimal('3'), Decimal('2')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4477 |         Decimal('2') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4478 |         >>> ExtendedContext.min(Decimal('-10'), Decimal('3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4479 |         Decimal('-10') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4480 |         >>> ExtendedContext.min(Decimal('1.0'), Decimal('1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4481 |         Decimal('1.0') | 
| Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 4482 |         >>> ExtendedContext.min(Decimal('7'), Decimal('NaN')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4483 |         Decimal('7') | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4484 |         """ | 
 | 4485 |         return a.min(b, context=self) | 
 | 4486 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4487 |     def min_mag(self, a, b): | 
 | 4488 |         """Compares the values numerically with their sign ignored.""" | 
 | 4489 |         return a.min_mag(b, context=self) | 
 | 4490 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4491 |     def minus(self, a): | 
 | 4492 |         """Minus corresponds to unary prefix minus in Python. | 
 | 4493 |  | 
 | 4494 |         The operation is evaluated using the same rules as subtract; the | 
 | 4495 |         operation minus(a) is calculated as subtract('0', a) where the '0' | 
 | 4496 |         has the same exponent as the operand. | 
 | 4497 |  | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4498 |         >>> ExtendedContext.minus(Decimal('1.3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4499 |         Decimal('-1.3') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4500 |         >>> ExtendedContext.minus(Decimal('-1.3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4501 |         Decimal('1.3') | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4502 |         """ | 
 | 4503 |         return a.__neg__(context=self) | 
 | 4504 |  | 
 | 4505 |     def multiply(self, a, b): | 
 | 4506 |         """multiply multiplies two operands. | 
 | 4507 |  | 
 | 4508 |         If either operand is a special value then the general rules apply. | 
 | 4509 |         Otherwise, the operands are multiplied together ('long multiplication'), | 
 | 4510 |         resulting in a number which may be as long as the sum of the lengths | 
 | 4511 |         of the two operands. | 
 | 4512 |  | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4513 |         >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4514 |         Decimal('3.60') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4515 |         >>> ExtendedContext.multiply(Decimal('7'), Decimal('3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4516 |         Decimal('21') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4517 |         >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4518 |         Decimal('0.72') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4519 |         >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4520 |         Decimal('-0.0') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4521 |         >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4522 |         Decimal('4.28135971E+11') | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4523 |         """ | 
 | 4524 |         return a.__mul__(b, context=self) | 
 | 4525 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4526 |     def next_minus(self, a): | 
 | 4527 |         """Returns the largest representable number smaller than a. | 
 | 4528 |  | 
 | 4529 |         >>> c = ExtendedContext.copy() | 
 | 4530 |         >>> c.Emin = -999 | 
 | 4531 |         >>> c.Emax = 999 | 
 | 4532 |         >>> ExtendedContext.next_minus(Decimal('1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4533 |         Decimal('0.999999999') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4534 |         >>> c.next_minus(Decimal('1E-1007')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4535 |         Decimal('0E-1007') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4536 |         >>> ExtendedContext.next_minus(Decimal('-1.00000003')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4537 |         Decimal('-1.00000004') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4538 |         >>> c.next_minus(Decimal('Infinity')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4539 |         Decimal('9.99999999E+999') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4540 |         """ | 
 | 4541 |         return a.next_minus(context=self) | 
 | 4542 |  | 
 | 4543 |     def next_plus(self, a): | 
 | 4544 |         """Returns the smallest representable number larger than a. | 
 | 4545 |  | 
 | 4546 |         >>> c = ExtendedContext.copy() | 
 | 4547 |         >>> c.Emin = -999 | 
 | 4548 |         >>> c.Emax = 999 | 
 | 4549 |         >>> ExtendedContext.next_plus(Decimal('1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4550 |         Decimal('1.00000001') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4551 |         >>> c.next_plus(Decimal('-1E-1007')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4552 |         Decimal('-0E-1007') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4553 |         >>> ExtendedContext.next_plus(Decimal('-1.00000003')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4554 |         Decimal('-1.00000002') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4555 |         >>> c.next_plus(Decimal('-Infinity')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4556 |         Decimal('-9.99999999E+999') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4557 |         """ | 
 | 4558 |         return a.next_plus(context=self) | 
 | 4559 |  | 
 | 4560 |     def next_toward(self, a, b): | 
 | 4561 |         """Returns the number closest to a, in direction towards b. | 
 | 4562 |  | 
 | 4563 |         The result is the closest representable number from the first | 
 | 4564 |         operand (but not the first operand) that is in the direction | 
 | 4565 |         towards the second operand, unless the operands have the same | 
 | 4566 |         value. | 
 | 4567 |  | 
 | 4568 |         >>> c = ExtendedContext.copy() | 
 | 4569 |         >>> c.Emin = -999 | 
 | 4570 |         >>> c.Emax = 999 | 
 | 4571 |         >>> c.next_toward(Decimal('1'), Decimal('2')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4572 |         Decimal('1.00000001') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4573 |         >>> c.next_toward(Decimal('-1E-1007'), Decimal('1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4574 |         Decimal('-0E-1007') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4575 |         >>> c.next_toward(Decimal('-1.00000003'), Decimal('0')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4576 |         Decimal('-1.00000002') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4577 |         >>> c.next_toward(Decimal('1'), Decimal('0')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4578 |         Decimal('0.999999999') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4579 |         >>> c.next_toward(Decimal('1E-1007'), Decimal('-100')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4580 |         Decimal('0E-1007') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4581 |         >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4582 |         Decimal('-1.00000004') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4583 |         >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4584 |         Decimal('-0.00') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4585 |         """ | 
 | 4586 |         return a.next_toward(b, context=self) | 
 | 4587 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4588 |     def normalize(self, a): | 
| Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 4589 |         """normalize reduces an operand to its simplest form. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4590 |  | 
 | 4591 |         Essentially a plus operation with all trailing zeros removed from the | 
 | 4592 |         result. | 
 | 4593 |  | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4594 |         >>> ExtendedContext.normalize(Decimal('2.1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4595 |         Decimal('2.1') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4596 |         >>> ExtendedContext.normalize(Decimal('-2.0')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4597 |         Decimal('-2') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4598 |         >>> ExtendedContext.normalize(Decimal('1.200')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4599 |         Decimal('1.2') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4600 |         >>> ExtendedContext.normalize(Decimal('-120')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4601 |         Decimal('-1.2E+2') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4602 |         >>> ExtendedContext.normalize(Decimal('120.00')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4603 |         Decimal('1.2E+2') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4604 |         >>> ExtendedContext.normalize(Decimal('0.00')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4605 |         Decimal('0') | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4606 |         """ | 
 | 4607 |         return a.normalize(context=self) | 
 | 4608 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4609 |     def number_class(self, a): | 
 | 4610 |         """Returns an indication of the class of the operand. | 
 | 4611 |  | 
 | 4612 |         The class is one of the following strings: | 
 | 4613 |           -sNaN | 
 | 4614 |           -NaN | 
 | 4615 |           -Infinity | 
 | 4616 |           -Normal | 
 | 4617 |           -Subnormal | 
 | 4618 |           -Zero | 
 | 4619 |           +Zero | 
 | 4620 |           +Subnormal | 
 | 4621 |           +Normal | 
 | 4622 |           +Infinity | 
 | 4623 |  | 
 | 4624 |         >>> c = Context(ExtendedContext) | 
 | 4625 |         >>> c.Emin = -999 | 
 | 4626 |         >>> c.Emax = 999 | 
 | 4627 |         >>> c.number_class(Decimal('Infinity')) | 
 | 4628 |         '+Infinity' | 
 | 4629 |         >>> c.number_class(Decimal('1E-10')) | 
 | 4630 |         '+Normal' | 
 | 4631 |         >>> c.number_class(Decimal('2.50')) | 
 | 4632 |         '+Normal' | 
 | 4633 |         >>> c.number_class(Decimal('0.1E-999')) | 
 | 4634 |         '+Subnormal' | 
 | 4635 |         >>> c.number_class(Decimal('0')) | 
 | 4636 |         '+Zero' | 
 | 4637 |         >>> c.number_class(Decimal('-0')) | 
 | 4638 |         '-Zero' | 
 | 4639 |         >>> c.number_class(Decimal('-0.1E-999')) | 
 | 4640 |         '-Subnormal' | 
 | 4641 |         >>> c.number_class(Decimal('-1E-10')) | 
 | 4642 |         '-Normal' | 
 | 4643 |         >>> c.number_class(Decimal('-2.50')) | 
 | 4644 |         '-Normal' | 
 | 4645 |         >>> c.number_class(Decimal('-Infinity')) | 
 | 4646 |         '-Infinity' | 
 | 4647 |         >>> c.number_class(Decimal('NaN')) | 
 | 4648 |         'NaN' | 
 | 4649 |         >>> c.number_class(Decimal('-NaN')) | 
 | 4650 |         'NaN' | 
 | 4651 |         >>> c.number_class(Decimal('sNaN')) | 
 | 4652 |         'sNaN' | 
 | 4653 |         """ | 
 | 4654 |         return a.number_class(context=self) | 
 | 4655 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4656 |     def plus(self, a): | 
 | 4657 |         """Plus corresponds to unary prefix plus in Python. | 
 | 4658 |  | 
 | 4659 |         The operation is evaluated using the same rules as add; the | 
 | 4660 |         operation plus(a) is calculated as add('0', a) where the '0' | 
 | 4661 |         has the same exponent as the operand. | 
 | 4662 |  | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4663 |         >>> ExtendedContext.plus(Decimal('1.3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4664 |         Decimal('1.3') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4665 |         >>> ExtendedContext.plus(Decimal('-1.3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4666 |         Decimal('-1.3') | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4667 |         """ | 
 | 4668 |         return a.__pos__(context=self) | 
 | 4669 |  | 
 | 4670 |     def power(self, a, b, modulo=None): | 
 | 4671 |         """Raises a to the power of b, to modulo if given. | 
 | 4672 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4673 |         With two arguments, compute a**b.  If a is negative then b | 
 | 4674 |         must be integral.  The result will be inexact unless b is | 
 | 4675 |         integral and the result is finite and can be expressed exactly | 
 | 4676 |         in 'precision' digits. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4677 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4678 |         With three arguments, compute (a**b) % modulo.  For the | 
 | 4679 |         three argument form, the following restrictions on the | 
 | 4680 |         arguments hold: | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4681 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4682 |          - all three arguments must be integral | 
 | 4683 |          - b must be nonnegative | 
 | 4684 |          - at least one of a or b must be nonzero | 
 | 4685 |          - modulo must be nonzero and have at most 'precision' digits | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4686 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4687 |         The result of pow(a, b, modulo) is identical to the result | 
 | 4688 |         that would be obtained by computing (a**b) % modulo with | 
 | 4689 |         unbounded precision, but is computed more efficiently.  It is | 
 | 4690 |         always exact. | 
 | 4691 |  | 
 | 4692 |         >>> c = ExtendedContext.copy() | 
 | 4693 |         >>> c.Emin = -999 | 
 | 4694 |         >>> c.Emax = 999 | 
 | 4695 |         >>> c.power(Decimal('2'), Decimal('3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4696 |         Decimal('8') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4697 |         >>> c.power(Decimal('-2'), Decimal('3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4698 |         Decimal('-8') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4699 |         >>> c.power(Decimal('2'), Decimal('-3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4700 |         Decimal('0.125') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4701 |         >>> c.power(Decimal('1.7'), Decimal('8')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4702 |         Decimal('69.7575744') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4703 |         >>> c.power(Decimal('10'), Decimal('0.301029996')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4704 |         Decimal('2.00000000') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4705 |         >>> c.power(Decimal('Infinity'), Decimal('-1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4706 |         Decimal('0') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4707 |         >>> c.power(Decimal('Infinity'), Decimal('0')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4708 |         Decimal('1') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4709 |         >>> c.power(Decimal('Infinity'), Decimal('1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4710 |         Decimal('Infinity') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4711 |         >>> c.power(Decimal('-Infinity'), Decimal('-1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4712 |         Decimal('-0') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4713 |         >>> c.power(Decimal('-Infinity'), Decimal('0')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4714 |         Decimal('1') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4715 |         >>> c.power(Decimal('-Infinity'), Decimal('1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4716 |         Decimal('-Infinity') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4717 |         >>> c.power(Decimal('-Infinity'), Decimal('2')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4718 |         Decimal('Infinity') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4719 |         >>> c.power(Decimal('0'), Decimal('0')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4720 |         Decimal('NaN') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4721 |  | 
 | 4722 |         >>> c.power(Decimal('3'), Decimal('7'), Decimal('16')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4723 |         Decimal('11') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4724 |         >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4725 |         Decimal('-11') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4726 |         >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4727 |         Decimal('1') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4728 |         >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4729 |         Decimal('11') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4730 |         >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4731 |         Decimal('11729830') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4732 |         >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4733 |         Decimal('-0') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4734 |         >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4735 |         Decimal('1') | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4736 |         """ | 
 | 4737 |         return a.__pow__(b, modulo, context=self) | 
 | 4738 |  | 
 | 4739 |     def quantize(self, a, b): | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 4740 |         """Returns a value equal to 'a' (rounded), having the exponent of 'b'. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4741 |  | 
 | 4742 |         The coefficient of the result is derived from that of the left-hand | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 4743 |         operand.  It may be rounded using the current rounding setting (if the | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4744 |         exponent is being increased), multiplied by a positive power of ten (if | 
 | 4745 |         the exponent is being decreased), or is unchanged (if the exponent is | 
 | 4746 |         already equal to that of the right-hand operand). | 
 | 4747 |  | 
 | 4748 |         Unlike other operations, if the length of the coefficient after the | 
 | 4749 |         quantize operation would be greater than precision then an Invalid | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 4750 |         operation condition is raised.  This guarantees that, unless there is | 
 | 4751 |         an error condition, the exponent of the result of a quantize is always | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4752 |         equal to that of the right-hand operand. | 
 | 4753 |  | 
 | 4754 |         Also unlike other operations, quantize will never raise Underflow, even | 
 | 4755 |         if the result is subnormal and inexact. | 
 | 4756 |  | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4757 |         >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4758 |         Decimal('2.170') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4759 |         >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4760 |         Decimal('2.17') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4761 |         >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4762 |         Decimal('2.2') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4763 |         >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4764 |         Decimal('2') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4765 |         >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4766 |         Decimal('0E+1') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4767 |         >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4768 |         Decimal('-Infinity') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4769 |         >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4770 |         Decimal('NaN') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4771 |         >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4772 |         Decimal('-0') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4773 |         >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4774 |         Decimal('-0E+5') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4775 |         >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4776 |         Decimal('NaN') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4777 |         >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4778 |         Decimal('NaN') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4779 |         >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4780 |         Decimal('217.0') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4781 |         >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4782 |         Decimal('217') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4783 |         >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4784 |         Decimal('2.2E+2') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4785 |         >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4786 |         Decimal('2E+2') | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4787 |         """ | 
 | 4788 |         return a.quantize(b, context=self) | 
 | 4789 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4790 |     def radix(self): | 
 | 4791 |         """Just returns 10, as this is Decimal, :) | 
 | 4792 |  | 
 | 4793 |         >>> ExtendedContext.radix() | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4794 |         Decimal('10') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4795 |         """ | 
 | 4796 |         return Decimal(10) | 
 | 4797 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4798 |     def remainder(self, a, b): | 
 | 4799 |         """Returns the remainder from integer division. | 
 | 4800 |  | 
 | 4801 |         The result is the residue of the dividend after the operation of | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 4802 |         calculating integer division as described for divide-integer, rounded | 
 | 4803 |         to precision digits if necessary.  The sign of the result, if | 
 | 4804 |         non-zero, is the same as that of the original dividend. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4805 |  | 
 | 4806 |         This operation will fail under the same conditions as integer division | 
 | 4807 |         (that is, if integer division on the same two operands would fail, the | 
 | 4808 |         remainder cannot be calculated). | 
 | 4809 |  | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4810 |         >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4811 |         Decimal('2.1') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4812 |         >>> ExtendedContext.remainder(Decimal('10'), Decimal('3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4813 |         Decimal('1') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4814 |         >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4815 |         Decimal('-1') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4816 |         >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4817 |         Decimal('0.2') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4818 |         >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4819 |         Decimal('0.1') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4820 |         >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4821 |         Decimal('1.0') | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4822 |         """ | 
 | 4823 |         return a.__mod__(b, context=self) | 
 | 4824 |  | 
 | 4825 |     def remainder_near(self, a, b): | 
 | 4826 |         """Returns to be "a - b * n", where n is the integer nearest the exact | 
 | 4827 |         value of "x / b" (if two integers are equally near then the even one | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 4828 |         is chosen).  If the result is equal to 0 then its sign will be the | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4829 |         sign of a. | 
 | 4830 |  | 
 | 4831 |         This operation will fail under the same conditions as integer division | 
 | 4832 |         (that is, if integer division on the same two operands would fail, the | 
 | 4833 |         remainder cannot be calculated). | 
 | 4834 |  | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4835 |         >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4836 |         Decimal('-0.9') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4837 |         >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4838 |         Decimal('-2') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4839 |         >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4840 |         Decimal('1') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4841 |         >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4842 |         Decimal('-1') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4843 |         >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4844 |         Decimal('0.2') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4845 |         >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4846 |         Decimal('0.1') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4847 |         >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4848 |         Decimal('-0.3') | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4849 |         """ | 
 | 4850 |         return a.remainder_near(b, context=self) | 
 | 4851 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4852 |     def rotate(self, a, b): | 
 | 4853 |         """Returns a rotated copy of a, b times. | 
 | 4854 |  | 
 | 4855 |         The coefficient of the result is a rotated copy of the digits in | 
 | 4856 |         the coefficient of the first operand.  The number of places of | 
 | 4857 |         rotation is taken from the absolute value of the second operand, | 
 | 4858 |         with the rotation being to the left if the second operand is | 
 | 4859 |         positive or to the right otherwise. | 
 | 4860 |  | 
 | 4861 |         >>> ExtendedContext.rotate(Decimal('34'), Decimal('8')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4862 |         Decimal('400000003') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4863 |         >>> ExtendedContext.rotate(Decimal('12'), Decimal('9')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4864 |         Decimal('12') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4865 |         >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4866 |         Decimal('891234567') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4867 |         >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4868 |         Decimal('123456789') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4869 |         >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4870 |         Decimal('345678912') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4871 |         """ | 
 | 4872 |         return a.rotate(b, context=self) | 
 | 4873 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4874 |     def same_quantum(self, a, b): | 
 | 4875 |         """Returns True if the two operands have the same exponent. | 
 | 4876 |  | 
 | 4877 |         The result is never affected by either the sign or the coefficient of | 
 | 4878 |         either operand. | 
 | 4879 |  | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4880 |         >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001')) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4881 |         False | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4882 |         >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01')) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4883 |         True | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4884 |         >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1')) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4885 |         False | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4886 |         >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf')) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4887 |         True | 
 | 4888 |         """ | 
 | 4889 |         return a.same_quantum(b) | 
 | 4890 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4891 |     def scaleb (self, a, b): | 
 | 4892 |         """Returns the first operand after adding the second value its exp. | 
 | 4893 |  | 
 | 4894 |         >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4895 |         Decimal('0.0750') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4896 |         >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4897 |         Decimal('7.50') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4898 |         >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4899 |         Decimal('7.50E+3') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4900 |         """ | 
 | 4901 |         return a.scaleb (b, context=self) | 
 | 4902 |  | 
 | 4903 |     def shift(self, a, b): | 
 | 4904 |         """Returns a shifted copy of a, b times. | 
 | 4905 |  | 
 | 4906 |         The coefficient of the result is a shifted copy of the digits | 
 | 4907 |         in the coefficient of the first operand.  The number of places | 
 | 4908 |         to shift is taken from the absolute value of the second operand, | 
 | 4909 |         with the shift being to the left if the second operand is | 
 | 4910 |         positive or to the right otherwise.  Digits shifted into the | 
 | 4911 |         coefficient are zeros. | 
 | 4912 |  | 
 | 4913 |         >>> ExtendedContext.shift(Decimal('34'), Decimal('8')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4914 |         Decimal('400000000') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4915 |         >>> ExtendedContext.shift(Decimal('12'), Decimal('9')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4916 |         Decimal('0') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4917 |         >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4918 |         Decimal('1234567') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4919 |         >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4920 |         Decimal('123456789') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4921 |         >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4922 |         Decimal('345678900') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4923 |         """ | 
 | 4924 |         return a.shift(b, context=self) | 
 | 4925 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4926 |     def sqrt(self, a): | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 4927 |         """Square root of a non-negative number to context precision. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4928 |  | 
 | 4929 |         If the result must be inexact, it is rounded using the round-half-even | 
 | 4930 |         algorithm. | 
 | 4931 |  | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4932 |         >>> ExtendedContext.sqrt(Decimal('0')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4933 |         Decimal('0') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4934 |         >>> ExtendedContext.sqrt(Decimal('-0')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4935 |         Decimal('-0') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4936 |         >>> ExtendedContext.sqrt(Decimal('0.39')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4937 |         Decimal('0.624499800') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4938 |         >>> ExtendedContext.sqrt(Decimal('100')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4939 |         Decimal('10') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4940 |         >>> ExtendedContext.sqrt(Decimal('1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4941 |         Decimal('1') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4942 |         >>> ExtendedContext.sqrt(Decimal('1.0')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4943 |         Decimal('1.0') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4944 |         >>> ExtendedContext.sqrt(Decimal('1.00')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4945 |         Decimal('1.0') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4946 |         >>> ExtendedContext.sqrt(Decimal('7')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4947 |         Decimal('2.64575131') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4948 |         >>> ExtendedContext.sqrt(Decimal('10')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4949 |         Decimal('3.16227766') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4950 |         >>> ExtendedContext.prec | 
| Raymond Hettinger | 6ea4845 | 2004-07-03 12:26:21 +0000 | [diff] [blame] | 4951 |         9 | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4952 |         """ | 
 | 4953 |         return a.sqrt(context=self) | 
 | 4954 |  | 
 | 4955 |     def subtract(self, a, b): | 
| Georg Brandl | f33d01d | 2005-08-22 19:35:18 +0000 | [diff] [blame] | 4956 |         """Return the difference between the two operands. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4957 |  | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4958 |         >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4959 |         Decimal('0.23') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4960 |         >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4961 |         Decimal('0.00') | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4962 |         >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4963 |         Decimal('-0.77') | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4964 |         """ | 
 | 4965 |         return a.__sub__(b, context=self) | 
 | 4966 |  | 
 | 4967 |     def to_eng_string(self, a): | 
 | 4968 |         """Converts a number to a string, using scientific notation. | 
 | 4969 |  | 
 | 4970 |         The operation is not affected by the context. | 
 | 4971 |         """ | 
 | 4972 |         return a.to_eng_string(context=self) | 
 | 4973 |  | 
 | 4974 |     def to_sci_string(self, a): | 
 | 4975 |         """Converts a number to a string, using scientific notation. | 
 | 4976 |  | 
 | 4977 |         The operation is not affected by the context. | 
 | 4978 |         """ | 
 | 4979 |         return a.__str__(context=self) | 
 | 4980 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4981 |     def to_integral_exact(self, a): | 
 | 4982 |         """Rounds to an integer. | 
 | 4983 |  | 
 | 4984 |         When the operand has a negative exponent, the result is the same | 
 | 4985 |         as using the quantize() operation using the given operand as the | 
 | 4986 |         left-hand-operand, 1E+0 as the right-hand-operand, and the precision | 
 | 4987 |         of the operand as the precision setting; Inexact and Rounded flags | 
 | 4988 |         are allowed in this operation.  The rounding mode is taken from the | 
 | 4989 |         context. | 
 | 4990 |  | 
 | 4991 |         >>> ExtendedContext.to_integral_exact(Decimal('2.1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4992 |         Decimal('2') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4993 |         >>> ExtendedContext.to_integral_exact(Decimal('100')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4994 |         Decimal('100') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4995 |         >>> ExtendedContext.to_integral_exact(Decimal('100.0')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4996 |         Decimal('100') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4997 |         >>> ExtendedContext.to_integral_exact(Decimal('101.5')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4998 |         Decimal('102') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4999 |         >>> ExtendedContext.to_integral_exact(Decimal('-101.5')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5000 |         Decimal('-102') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5001 |         >>> ExtendedContext.to_integral_exact(Decimal('10E+5')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5002 |         Decimal('1.0E+6') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5003 |         >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5004 |         Decimal('7.89E+77') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5005 |         >>> ExtendedContext.to_integral_exact(Decimal('-Inf')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5006 |         Decimal('-Infinity') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5007 |         """ | 
 | 5008 |         return a.to_integral_exact(context=self) | 
 | 5009 |  | 
 | 5010 |     def to_integral_value(self, a): | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5011 |         """Rounds to an integer. | 
 | 5012 |  | 
 | 5013 |         When the operand has a negative exponent, the result is the same | 
 | 5014 |         as using the quantize() operation using the given operand as the | 
 | 5015 |         left-hand-operand, 1E+0 as the right-hand-operand, and the precision | 
 | 5016 |         of the operand as the precision setting, except that no flags will | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 5017 |         be set.  The rounding mode is taken from the context. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5018 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5019 |         >>> ExtendedContext.to_integral_value(Decimal('2.1')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5020 |         Decimal('2') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5021 |         >>> ExtendedContext.to_integral_value(Decimal('100')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5022 |         Decimal('100') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5023 |         >>> ExtendedContext.to_integral_value(Decimal('100.0')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5024 |         Decimal('100') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5025 |         >>> ExtendedContext.to_integral_value(Decimal('101.5')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5026 |         Decimal('102') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5027 |         >>> ExtendedContext.to_integral_value(Decimal('-101.5')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5028 |         Decimal('-102') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5029 |         >>> ExtendedContext.to_integral_value(Decimal('10E+5')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5030 |         Decimal('1.0E+6') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5031 |         >>> ExtendedContext.to_integral_value(Decimal('7.89E+77')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5032 |         Decimal('7.89E+77') | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5033 |         >>> ExtendedContext.to_integral_value(Decimal('-Inf')) | 
| Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5034 |         Decimal('-Infinity') | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5035 |         """ | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5036 |         return a.to_integral_value(context=self) | 
 | 5037 |  | 
 | 5038 |     # the method name changed, but we provide also the old one, for compatibility | 
 | 5039 |     to_integral = to_integral_value | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5040 |  | 
 | 5041 | class _WorkRep(object): | 
 | 5042 |     __slots__ = ('sign','int','exp') | 
| Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 5043 |     # sign: 0 or 1 | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5044 |     # int:  int | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5045 |     # exp:  None, int, or string | 
 | 5046 |  | 
 | 5047 |     def __init__(self, value=None): | 
 | 5048 |         if value is None: | 
 | 5049 |             self.sign = None | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5050 |             self.int = 0 | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5051 |             self.exp = None | 
| Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 5052 |         elif isinstance(value, Decimal): | 
 | 5053 |             self.sign = value._sign | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5054 |             self.int = int(value._int) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5055 |             self.exp = value._exp | 
| Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 5056 |         else: | 
 | 5057 |             # assert isinstance(value, tuple) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5058 |             self.sign = value[0] | 
 | 5059 |             self.int = value[1] | 
 | 5060 |             self.exp = value[2] | 
 | 5061 |  | 
 | 5062 |     def __repr__(self): | 
 | 5063 |         return "(%r, %r, %r)" % (self.sign, self.int, self.exp) | 
 | 5064 |  | 
 | 5065 |     __str__ = __repr__ | 
 | 5066 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5067 |  | 
 | 5068 |  | 
| Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 5069 | def _normalize(op1, op2, prec = 0): | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5070 |     """Normalizes op1, op2 to have the same exp and length of coefficient. | 
 | 5071 |  | 
 | 5072 |     Done during addition. | 
 | 5073 |     """ | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5074 |     if op1.exp < op2.exp: | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5075 |         tmp = op2 | 
 | 5076 |         other = op1 | 
 | 5077 |     else: | 
 | 5078 |         tmp = op1 | 
 | 5079 |         other = op2 | 
 | 5080 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5081 |     # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1). | 
 | 5082 |     # Then adding 10**exp to tmp has the same effect (after rounding) | 
 | 5083 |     # as adding any positive quantity smaller than 10**exp; similarly | 
 | 5084 |     # for subtraction.  So if other is smaller than 10**exp we replace | 
 | 5085 |     # it with 10**exp.  This avoids tmp.exp - other.exp getting too large. | 
| Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 5086 |     tmp_len = len(str(tmp.int)) | 
 | 5087 |     other_len = len(str(other.int)) | 
 | 5088 |     exp = tmp.exp + min(-1, tmp_len - prec - 2) | 
 | 5089 |     if other_len + other.exp - 1 < exp: | 
 | 5090 |         other.int = 1 | 
 | 5091 |         other.exp = exp | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5092 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5093 |     tmp.int *= 10 ** (tmp.exp - other.exp) | 
 | 5094 |     tmp.exp = other.exp | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5095 |     return op1, op2 | 
 | 5096 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5097 | ##### Integer arithmetic functions used by ln, log10, exp and __pow__ ##### | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5098 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5099 | # This function from Tim Peters was taken from here: | 
 | 5100 | # http://mail.python.org/pipermail/python-list/1999-July/007758.html | 
 | 5101 | # The correction being in the function definition is for speed, and | 
 | 5102 | # the whole function is not resolved with math.log because of avoiding | 
 | 5103 | # the use of floats. | 
 | 5104 | def _nbits(n, correction = { | 
 | 5105 |         '0': 4, '1': 3, '2': 2, '3': 2, | 
 | 5106 |         '4': 1, '5': 1, '6': 1, '7': 1, | 
 | 5107 |         '8': 0, '9': 0, 'a': 0, 'b': 0, | 
 | 5108 |         'c': 0, 'd': 0, 'e': 0, 'f': 0}): | 
 | 5109 |     """Number of bits in binary representation of the positive integer n, | 
 | 5110 |     or 0 if n == 0. | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5111 |     """ | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5112 |     if n < 0: | 
 | 5113 |         raise ValueError("The argument to _nbits should be nonnegative.") | 
 | 5114 |     hex_n = "%x" % n | 
 | 5115 |     return 4*len(hex_n) - correction[hex_n[0]] | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5116 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5117 | def _sqrt_nearest(n, a): | 
 | 5118 |     """Closest integer to the square root of the positive integer n.  a is | 
 | 5119 |     an initial approximation to the square root.  Any positive integer | 
 | 5120 |     will do for a, but the closer a is to the square root of n the | 
 | 5121 |     faster convergence will be. | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5122 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5123 |     """ | 
 | 5124 |     if n <= 0 or a <= 0: | 
 | 5125 |         raise ValueError("Both arguments to _sqrt_nearest should be positive.") | 
 | 5126 |  | 
 | 5127 |     b=0 | 
 | 5128 |     while a != b: | 
 | 5129 |         b, a = a, a--n//a>>1 | 
 | 5130 |     return a | 
 | 5131 |  | 
 | 5132 | def _rshift_nearest(x, shift): | 
 | 5133 |     """Given an integer x and a nonnegative integer shift, return closest | 
 | 5134 |     integer to x / 2**shift; use round-to-even in case of a tie. | 
 | 5135 |  | 
 | 5136 |     """ | 
 | 5137 |     b, q = 1 << shift, x >> shift | 
 | 5138 |     return q + (2*(x & (b-1)) + (q&1) > b) | 
 | 5139 |  | 
 | 5140 | def _div_nearest(a, b): | 
 | 5141 |     """Closest integer to a/b, a and b positive integers; rounds to even | 
 | 5142 |     in the case of a tie. | 
 | 5143 |  | 
 | 5144 |     """ | 
 | 5145 |     q, r = divmod(a, b) | 
 | 5146 |     return q + (2*r + (q&1) > b) | 
 | 5147 |  | 
 | 5148 | def _ilog(x, M, L = 8): | 
 | 5149 |     """Integer approximation to M*log(x/M), with absolute error boundable | 
 | 5150 |     in terms only of x/M. | 
 | 5151 |  | 
 | 5152 |     Given positive integers x and M, return an integer approximation to | 
 | 5153 |     M * log(x/M).  For L = 8 and 0.1 <= x/M <= 10 the difference | 
 | 5154 |     between the approximation and the exact result is at most 22.  For | 
 | 5155 |     L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15.  In | 
 | 5156 |     both cases these are upper bounds on the error; it will usually be | 
 | 5157 |     much smaller.""" | 
 | 5158 |  | 
 | 5159 |     # The basic algorithm is the following: let log1p be the function | 
 | 5160 |     # log1p(x) = log(1+x).  Then log(x/M) = log1p((x-M)/M).  We use | 
 | 5161 |     # the reduction | 
 | 5162 |     # | 
 | 5163 |     #    log1p(y) = 2*log1p(y/(1+sqrt(1+y))) | 
 | 5164 |     # | 
 | 5165 |     # repeatedly until the argument to log1p is small (< 2**-L in | 
 | 5166 |     # absolute value).  For small y we can use the Taylor series | 
 | 5167 |     # expansion | 
 | 5168 |     # | 
 | 5169 |     #    log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T | 
 | 5170 |     # | 
 | 5171 |     # truncating at T such that y**T is small enough.  The whole | 
 | 5172 |     # computation is carried out in a form of fixed-point arithmetic, | 
 | 5173 |     # with a real number z being represented by an integer | 
 | 5174 |     # approximation to z*M.  To avoid loss of precision, the y below | 
 | 5175 |     # is actually an integer approximation to 2**R*y*M, where R is the | 
 | 5176 |     # number of reductions performed so far. | 
 | 5177 |  | 
 | 5178 |     y = x-M | 
 | 5179 |     # argument reduction; R = number of reductions performed | 
 | 5180 |     R = 0 | 
 | 5181 |     while (R <= L and abs(y) << L-R >= M or | 
 | 5182 |            R > L and abs(y) >> R-L >= M): | 
 | 5183 |         y = _div_nearest((M*y) << 1, | 
 | 5184 |                          M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M)) | 
 | 5185 |         R += 1 | 
 | 5186 |  | 
 | 5187 |     # Taylor series with T terms | 
 | 5188 |     T = -int(-10*len(str(M))//(3*L)) | 
 | 5189 |     yshift = _rshift_nearest(y, R) | 
 | 5190 |     w = _div_nearest(M, T) | 
 | 5191 |     for k in range(T-1, 0, -1): | 
 | 5192 |         w = _div_nearest(M, k) - _div_nearest(yshift*w, M) | 
 | 5193 |  | 
 | 5194 |     return _div_nearest(w*y, M) | 
 | 5195 |  | 
 | 5196 | def _dlog10(c, e, p): | 
 | 5197 |     """Given integers c, e and p with c > 0, p >= 0, compute an integer | 
 | 5198 |     approximation to 10**p * log10(c*10**e), with an absolute error of | 
 | 5199 |     at most 1.  Assumes that c*10**e is not exactly 1.""" | 
 | 5200 |  | 
 | 5201 |     # increase precision by 2; compensate for this by dividing | 
 | 5202 |     # final result by 100 | 
 | 5203 |     p += 2 | 
 | 5204 |  | 
 | 5205 |     # write c*10**e as d*10**f with either: | 
 | 5206 |     #   f >= 0 and 1 <= d <= 10, or | 
 | 5207 |     #   f <= 0 and 0.1 <= d <= 1. | 
 | 5208 |     # Thus for c*10**e close to 1, f = 0 | 
 | 5209 |     l = len(str(c)) | 
 | 5210 |     f = e+l - (e+l >= 1) | 
 | 5211 |  | 
 | 5212 |     if p > 0: | 
 | 5213 |         M = 10**p | 
 | 5214 |         k = e+p-f | 
 | 5215 |         if k >= 0: | 
 | 5216 |             c *= 10**k | 
 | 5217 |         else: | 
 | 5218 |             c = _div_nearest(c, 10**-k) | 
 | 5219 |  | 
 | 5220 |         log_d = _ilog(c, M) # error < 5 + 22 = 27 | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5221 |         log_10 = _log10_digits(p) # error < 1 | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5222 |         log_d = _div_nearest(log_d*M, log_10) | 
 | 5223 |         log_tenpower = f*M # exact | 
 | 5224 |     else: | 
 | 5225 |         log_d = 0  # error < 2.31 | 
| Neal Norwitz | 2f99b24 | 2008-08-24 05:48:10 +0000 | [diff] [blame] | 5226 |         log_tenpower = _div_nearest(f, 10**-p) # error < 0.5 | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5227 |  | 
 | 5228 |     return _div_nearest(log_tenpower+log_d, 100) | 
 | 5229 |  | 
 | 5230 | def _dlog(c, e, p): | 
 | 5231 |     """Given integers c, e and p with c > 0, compute an integer | 
 | 5232 |     approximation to 10**p * log(c*10**e), with an absolute error of | 
 | 5233 |     at most 1.  Assumes that c*10**e is not exactly 1.""" | 
 | 5234 |  | 
 | 5235 |     # Increase precision by 2. The precision increase is compensated | 
 | 5236 |     # for at the end with a division by 100. | 
 | 5237 |     p += 2 | 
 | 5238 |  | 
 | 5239 |     # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10, | 
 | 5240 |     # or f <= 0 and 0.1 <= d <= 1.  Then we can compute 10**p * log(c*10**e) | 
 | 5241 |     # as 10**p * log(d) + 10**p*f * log(10). | 
 | 5242 |     l = len(str(c)) | 
 | 5243 |     f = e+l - (e+l >= 1) | 
 | 5244 |  | 
 | 5245 |     # compute approximation to 10**p*log(d), with error < 27 | 
 | 5246 |     if p > 0: | 
 | 5247 |         k = e+p-f | 
 | 5248 |         if k >= 0: | 
 | 5249 |             c *= 10**k | 
 | 5250 |         else: | 
 | 5251 |             c = _div_nearest(c, 10**-k)  # error of <= 0.5 in c | 
 | 5252 |  | 
 | 5253 |         # _ilog magnifies existing error in c by a factor of at most 10 | 
 | 5254 |         log_d = _ilog(c, 10**p) # error < 5 + 22 = 27 | 
 | 5255 |     else: | 
 | 5256 |         # p <= 0: just approximate the whole thing by 0; error < 2.31 | 
 | 5257 |         log_d = 0 | 
 | 5258 |  | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5259 |     # compute approximation to f*10**p*log(10), with error < 11. | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5260 |     if f: | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5261 |         extra = len(str(abs(f)))-1 | 
 | 5262 |         if p + extra >= 0: | 
 | 5263 |             # error in f * _log10_digits(p+extra) < |f| * 1 = |f| | 
 | 5264 |             # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11 | 
 | 5265 |             f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5266 |         else: | 
 | 5267 |             f_log_ten = 0 | 
 | 5268 |     else: | 
 | 5269 |         f_log_ten = 0 | 
 | 5270 |  | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5271 |     # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1 | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5272 |     return _div_nearest(f_log_ten + log_d, 100) | 
 | 5273 |  | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5274 | class _Log10Memoize(object): | 
 | 5275 |     """Class to compute, store, and allow retrieval of, digits of the | 
 | 5276 |     constant log(10) = 2.302585....  This constant is needed by | 
 | 5277 |     Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__.""" | 
 | 5278 |     def __init__(self): | 
 | 5279 |         self.digits = "23025850929940456840179914546843642076011014886" | 
 | 5280 |  | 
 | 5281 |     def getdigits(self, p): | 
 | 5282 |         """Given an integer p >= 0, return floor(10**p)*log(10). | 
 | 5283 |  | 
 | 5284 |         For example, self.getdigits(3) returns 2302. | 
 | 5285 |         """ | 
 | 5286 |         # digits are stored as a string, for quick conversion to | 
 | 5287 |         # integer in the case that we've already computed enough | 
 | 5288 |         # digits; the stored digits should always be correct | 
 | 5289 |         # (truncated, not rounded to nearest). | 
 | 5290 |         if p < 0: | 
 | 5291 |             raise ValueError("p should be nonnegative") | 
 | 5292 |  | 
 | 5293 |         if p >= len(self.digits): | 
 | 5294 |             # compute p+3, p+6, p+9, ... digits; continue until at | 
 | 5295 |             # least one of the extra digits is nonzero | 
 | 5296 |             extra = 3 | 
 | 5297 |             while True: | 
 | 5298 |                 # compute p+extra digits, correct to within 1ulp | 
 | 5299 |                 M = 10**(p+extra+2) | 
 | 5300 |                 digits = str(_div_nearest(_ilog(10*M, M), 100)) | 
 | 5301 |                 if digits[-extra:] != '0'*extra: | 
 | 5302 |                     break | 
 | 5303 |                 extra += 3 | 
 | 5304 |             # keep all reliable digits so far; remove trailing zeros | 
 | 5305 |             # and next nonzero digit | 
 | 5306 |             self.digits = digits.rstrip('0')[:-1] | 
 | 5307 |         return int(self.digits[:p+1]) | 
 | 5308 |  | 
 | 5309 | _log10_digits = _Log10Memoize().getdigits | 
 | 5310 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5311 | def _iexp(x, M, L=8): | 
 | 5312 |     """Given integers x and M, M > 0, such that x/M is small in absolute | 
 | 5313 |     value, compute an integer approximation to M*exp(x/M).  For 0 <= | 
 | 5314 |     x/M <= 2.4, the absolute error in the result is bounded by 60 (and | 
 | 5315 |     is usually much smaller).""" | 
 | 5316 |  | 
 | 5317 |     # Algorithm: to compute exp(z) for a real number z, first divide z | 
 | 5318 |     # by a suitable power R of 2 so that |z/2**R| < 2**-L.  Then | 
 | 5319 |     # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor | 
 | 5320 |     # series | 
 | 5321 |     # | 
 | 5322 |     #     expm1(x) = x + x**2/2! + x**3/3! + ... | 
 | 5323 |     # | 
 | 5324 |     # Now use the identity | 
 | 5325 |     # | 
 | 5326 |     #     expm1(2x) = expm1(x)*(expm1(x)+2) | 
 | 5327 |     # | 
 | 5328 |     # R times to compute the sequence expm1(z/2**R), | 
 | 5329 |     # expm1(z/2**(R-1)), ... , exp(z/2), exp(z). | 
 | 5330 |  | 
 | 5331 |     # Find R such that x/2**R/M <= 2**-L | 
 | 5332 |     R = _nbits((x<<L)//M) | 
 | 5333 |  | 
 | 5334 |     # Taylor series.  (2**L)**T > M | 
 | 5335 |     T = -int(-10*len(str(M))//(3*L)) | 
 | 5336 |     y = _div_nearest(x, T) | 
 | 5337 |     Mshift = M<<R | 
 | 5338 |     for i in range(T-1, 0, -1): | 
 | 5339 |         y = _div_nearest(x*(Mshift + y), Mshift * i) | 
 | 5340 |  | 
 | 5341 |     # Expansion | 
 | 5342 |     for k in range(R-1, -1, -1): | 
 | 5343 |         Mshift = M<<(k+2) | 
 | 5344 |         y = _div_nearest(y*(y+Mshift), Mshift) | 
 | 5345 |  | 
 | 5346 |     return M+y | 
 | 5347 |  | 
 | 5348 | def _dexp(c, e, p): | 
 | 5349 |     """Compute an approximation to exp(c*10**e), with p decimal places of | 
 | 5350 |     precision. | 
 | 5351 |  | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5352 |     Returns integers d, f such that: | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5353 |  | 
 | 5354 |       10**(p-1) <= d <= 10**p, and | 
 | 5355 |       (d-1)*10**f < exp(c*10**e) < (d+1)*10**f | 
 | 5356 |  | 
 | 5357 |     In other words, d*10**f is an approximation to exp(c*10**e) with p | 
 | 5358 |     digits of precision, and with an error in d of at most 1.  This is | 
 | 5359 |     almost, but not quite, the same as the error being < 1ulp: when d | 
 | 5360 |     = 10**(p-1) the error could be up to 10 ulp.""" | 
 | 5361 |  | 
 | 5362 |     # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision | 
 | 5363 |     p += 2 | 
 | 5364 |  | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5365 |     # compute log(10) with extra precision = adjusted exponent of c*10**e | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5366 |     extra = max(0, e + len(str(c)) - 1) | 
 | 5367 |     q = p + extra | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5368 |  | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5369 |     # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q), | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5370 |     # rounding down | 
 | 5371 |     shift = e+q | 
 | 5372 |     if shift >= 0: | 
 | 5373 |         cshift = c*10**shift | 
 | 5374 |     else: | 
 | 5375 |         cshift = c//10**-shift | 
| Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5376 |     quot, rem = divmod(cshift, _log10_digits(q)) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5377 |  | 
 | 5378 |     # reduce remainder back to original precision | 
 | 5379 |     rem = _div_nearest(rem, 10**extra) | 
 | 5380 |  | 
 | 5381 |     # error in result of _iexp < 120;  error after division < 0.62 | 
 | 5382 |     return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3 | 
 | 5383 |  | 
 | 5384 | def _dpower(xc, xe, yc, ye, p): | 
 | 5385 |     """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and | 
 | 5386 |     y = yc*10**ye, compute x**y.  Returns a pair of integers (c, e) such that: | 
 | 5387 |  | 
 | 5388 |       10**(p-1) <= c <= 10**p, and | 
 | 5389 |       (c-1)*10**e < x**y < (c+1)*10**e | 
 | 5390 |  | 
 | 5391 |     in other words, c*10**e is an approximation to x**y with p digits | 
 | 5392 |     of precision, and with an error in c of at most 1.  (This is | 
 | 5393 |     almost, but not quite, the same as the error being < 1ulp: when c | 
 | 5394 |     == 10**(p-1) we can only guarantee error < 10ulp.) | 
 | 5395 |  | 
 | 5396 |     We assume that: x is positive and not equal to 1, and y is nonzero. | 
 | 5397 |     """ | 
 | 5398 |  | 
 | 5399 |     # Find b such that 10**(b-1) <= |y| <= 10**b | 
 | 5400 |     b = len(str(abs(yc))) + ye | 
 | 5401 |  | 
 | 5402 |     # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point | 
 | 5403 |     lxc = _dlog(xc, xe, p+b+1) | 
 | 5404 |  | 
 | 5405 |     # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1) | 
 | 5406 |     shift = ye-b | 
 | 5407 |     if shift >= 0: | 
 | 5408 |         pc = lxc*yc*10**shift | 
 | 5409 |     else: | 
 | 5410 |         pc = _div_nearest(lxc*yc, 10**-shift) | 
 | 5411 |  | 
 | 5412 |     if pc == 0: | 
 | 5413 |         # we prefer a result that isn't exactly 1; this makes it | 
 | 5414 |         # easier to compute a correctly rounded result in __pow__ | 
 | 5415 |         if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1: | 
 | 5416 |             coeff, exp = 10**(p-1)+1, 1-p | 
 | 5417 |         else: | 
 | 5418 |             coeff, exp = 10**p-1, -p | 
 | 5419 |     else: | 
 | 5420 |         coeff, exp = _dexp(pc, -(p+1), p+1) | 
 | 5421 |         coeff = _div_nearest(coeff, 10) | 
 | 5422 |         exp += 1 | 
 | 5423 |  | 
 | 5424 |     return coeff, exp | 
 | 5425 |  | 
 | 5426 | def _log10_lb(c, correction = { | 
 | 5427 |         '1': 100, '2': 70, '3': 53, '4': 40, '5': 31, | 
 | 5428 |         '6': 23, '7': 16, '8': 10, '9': 5}): | 
 | 5429 |     """Compute a lower bound for 100*log10(c) for a positive integer c.""" | 
 | 5430 |     if c <= 0: | 
 | 5431 |         raise ValueError("The argument to _log10_lb should be nonnegative.") | 
 | 5432 |     str_c = str(c) | 
 | 5433 |     return 100*len(str_c) - correction[str_c[0]] | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5434 |  | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 5435 | ##### Helper Functions #################################################### | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5436 |  | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5437 | def _convert_other(other, raiseit=False): | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5438 |     """Convert other to Decimal. | 
 | 5439 |  | 
 | 5440 |     Verifies that it's ok to use in an implicit construction. | 
 | 5441 |     """ | 
 | 5442 |     if isinstance(other, Decimal): | 
 | 5443 |         return other | 
| Walter Dörwald | aa97f04 | 2007-05-03 21:05:51 +0000 | [diff] [blame] | 5444 |     if isinstance(other, int): | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5445 |         return Decimal(other) | 
| Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5446 |     if raiseit: | 
 | 5447 |         raise TypeError("Unable to convert %s to Decimal" % other) | 
| Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 5448 |     return NotImplemented | 
| Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5449 |  | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 5450 | ##### Setup Specific Contexts ############################################ | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5451 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5452 | # The default context prototype used by Context() | 
| Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 5453 | # Is mutable, so that new contexts can have different default values | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5454 |  | 
 | 5455 | DefaultContext = Context( | 
| Raymond Hettinger | 6ea4845 | 2004-07-03 12:26:21 +0000 | [diff] [blame] | 5456 |         prec=28, rounding=ROUND_HALF_EVEN, | 
| Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 5457 |         traps=[DivisionByZero, Overflow, InvalidOperation], | 
 | 5458 |         flags=[], | 
| Raymond Hettinger | 99148e7 | 2004-07-14 19:56:56 +0000 | [diff] [blame] | 5459 |         Emax=999999999, | 
 | 5460 |         Emin=-999999999, | 
| Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 5461 |         capitals=1 | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5462 | ) | 
 | 5463 |  | 
 | 5464 | # Pre-made alternate contexts offered by the specification | 
 | 5465 | # Don't change these; the user should be able to select these | 
 | 5466 | # contexts and be able to reproduce results from other implementations | 
 | 5467 | # of the spec. | 
 | 5468 |  | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5469 | BasicContext = Context( | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5470 |         prec=9, rounding=ROUND_HALF_UP, | 
| Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 5471 |         traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow], | 
 | 5472 |         flags=[], | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5473 | ) | 
 | 5474 |  | 
| Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5475 | ExtendedContext = Context( | 
| Raymond Hettinger | 6ea4845 | 2004-07-03 12:26:21 +0000 | [diff] [blame] | 5476 |         prec=9, rounding=ROUND_HALF_EVEN, | 
| Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 5477 |         traps=[], | 
 | 5478 |         flags=[], | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5479 | ) | 
 | 5480 |  | 
 | 5481 |  | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5482 | ##### crud for parsing strings ############################################# | 
| Christian Heimes | 23daade | 2008-02-25 12:39:23 +0000 | [diff] [blame] | 5483 | # | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5484 | # Regular expression used for parsing numeric strings.  Additional | 
 | 5485 | # comments: | 
 | 5486 | # | 
 | 5487 | # 1. Uncomment the two '\s*' lines to allow leading and/or trailing | 
 | 5488 | # whitespace.  But note that the specification disallows whitespace in | 
 | 5489 | # a numeric string. | 
 | 5490 | # | 
 | 5491 | # 2. For finite numbers (not infinities and NaNs) the body of the | 
 | 5492 | # number between the optional sign and the optional exponent must have | 
 | 5493 | # at least one decimal digit, possibly after the decimal point.  The | 
| Antoine Pitrou | fd03645 | 2008-08-19 17:56:33 +0000 | [diff] [blame] | 5494 | # lookahead expression '(?=[0-9]|\.[0-9])' checks this. | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5495 | # | 
 | 5496 | # As the flag UNICODE is not enabled here, we're explicitly avoiding any | 
 | 5497 | # other meaning for \d than the numbers [0-9]. | 
 | 5498 |  | 
 | 5499 | import re | 
| Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 5500 | _parser = re.compile(r"""        # A numeric string consists of: | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5501 | #    \s* | 
| Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 5502 |     (?P<sign>[-+])?              # an optional sign, followed by either... | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5503 |     ( | 
| Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 5504 |         (?=[0-9]|\.[0-9])        # ...a number (with at least one digit) | 
 | 5505 |         (?P<int>[0-9]*)          # having a (possibly empty) integer part | 
 | 5506 |         (\.(?P<frac>[0-9]*))?    # followed by an optional fractional part | 
 | 5507 |         (E(?P<exp>[-+]?[0-9]+))? # followed by an optional exponent, or... | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5508 |     | | 
| Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 5509 |         Inf(inity)?              # ...an infinity, or... | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5510 |     | | 
| Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 5511 |         (?P<signal>s)?           # ...an (optionally signaling) | 
 | 5512 |         NaN                      # NaN | 
 | 5513 |         (?P<diag>[0-9]*)         # with (possibly empty) diagnostic info. | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5514 |     ) | 
 | 5515 | #    \s* | 
| Christian Heimes | a62da1d | 2008-01-12 19:39:10 +0000 | [diff] [blame] | 5516 |     \Z | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5517 | """, re.VERBOSE | re.IGNORECASE).match | 
 | 5518 |  | 
| Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 5519 | _all_zeros = re.compile('0*$').match | 
 | 5520 | _exact_half = re.compile('50*$').match | 
| Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 5521 |  | 
 | 5522 | ##### PEP3101 support functions ############################################## | 
 | 5523 | # The functions parse_format_specifier and format_align have little to do | 
 | 5524 | # with the Decimal class, and could potentially be reused for other pure | 
 | 5525 | # Python numeric classes that want to implement __format__ | 
 | 5526 | # | 
 | 5527 | # A format specifier for Decimal looks like: | 
 | 5528 | # | 
 | 5529 | #   [[fill]align][sign][0][minimumwidth][.precision][type] | 
 | 5530 | # | 
 | 5531 |  | 
 | 5532 | _parse_format_specifier_regex = re.compile(r"""\A | 
 | 5533 | (?: | 
 | 5534 |    (?P<fill>.)? | 
 | 5535 |    (?P<align>[<>=^]) | 
 | 5536 | )? | 
 | 5537 | (?P<sign>[-+ ])? | 
 | 5538 | (?P<zeropad>0)? | 
 | 5539 | (?P<minimumwidth>(?!0)\d+)? | 
 | 5540 | (?:\.(?P<precision>0|(?!0)\d+))? | 
 | 5541 | (?P<type>[eEfFgG%])? | 
 | 5542 | \Z | 
 | 5543 | """, re.VERBOSE) | 
 | 5544 |  | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5545 | del re | 
 | 5546 |  | 
| Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 5547 | def _parse_format_specifier(format_spec): | 
 | 5548 |     """Parse and validate a format specifier. | 
 | 5549 |  | 
 | 5550 |     Turns a standard numeric format specifier into a dict, with the | 
 | 5551 |     following entries: | 
 | 5552 |  | 
 | 5553 |       fill: fill character to pad field to minimum width | 
 | 5554 |       align: alignment type, either '<', '>', '=' or '^' | 
 | 5555 |       sign: either '+', '-' or ' ' | 
 | 5556 |       minimumwidth: nonnegative integer giving minimum width | 
 | 5557 |       precision: nonnegative integer giving precision, or None | 
 | 5558 |       type: one of the characters 'eEfFgG%', or None | 
 | 5559 |       unicode: either True or False (always True for Python 3.x) | 
 | 5560 |  | 
 | 5561 |     """ | 
 | 5562 |     m = _parse_format_specifier_regex.match(format_spec) | 
 | 5563 |     if m is None: | 
 | 5564 |         raise ValueError("Invalid format specifier: " + format_spec) | 
 | 5565 |  | 
 | 5566 |     # get the dictionary | 
 | 5567 |     format_dict = m.groupdict() | 
 | 5568 |  | 
 | 5569 |     # defaults for fill and alignment | 
 | 5570 |     fill = format_dict['fill'] | 
 | 5571 |     align = format_dict['align'] | 
 | 5572 |     if format_dict.pop('zeropad') is not None: | 
 | 5573 |         # in the face of conflict, refuse the temptation to guess | 
 | 5574 |         if fill is not None and fill != '0': | 
 | 5575 |             raise ValueError("Fill character conflicts with '0'" | 
 | 5576 |                              " in format specifier: " + format_spec) | 
 | 5577 |         if align is not None and align != '=': | 
 | 5578 |             raise ValueError("Alignment conflicts with '0' in " | 
 | 5579 |                              "format specifier: " + format_spec) | 
 | 5580 |         fill = '0' | 
 | 5581 |         align = '=' | 
 | 5582 |     format_dict['fill'] = fill or ' ' | 
 | 5583 |     format_dict['align'] = align or '<' | 
 | 5584 |  | 
 | 5585 |     if format_dict['sign'] is None: | 
 | 5586 |         format_dict['sign'] = '-' | 
 | 5587 |  | 
 | 5588 |     # turn minimumwidth and precision entries into integers. | 
 | 5589 |     # minimumwidth defaults to 0; precision remains None if not given | 
 | 5590 |     format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0') | 
 | 5591 |     if format_dict['precision'] is not None: | 
 | 5592 |         format_dict['precision'] = int(format_dict['precision']) | 
 | 5593 |  | 
 | 5594 |     # if format type is 'g' or 'G' then a precision of 0 makes little | 
 | 5595 |     # sense; convert it to 1.  Same if format type is unspecified. | 
 | 5596 |     if format_dict['precision'] == 0: | 
 | 5597 |         if format_dict['type'] in 'gG' or format_dict['type'] is None: | 
 | 5598 |             format_dict['precision'] = 1 | 
 | 5599 |  | 
 | 5600 |     # record whether return type should be str or unicode | 
| Christian Heimes | 295f4fa | 2008-02-29 15:03:39 +0000 | [diff] [blame] | 5601 |     format_dict['unicode'] = True | 
| Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 5602 |  | 
 | 5603 |     return format_dict | 
 | 5604 |  | 
 | 5605 | def _format_align(body, spec_dict): | 
 | 5606 |     """Given an unpadded, non-aligned numeric string, add padding and | 
 | 5607 |     aligment to conform with the given format specifier dictionary (as | 
 | 5608 |     output from parse_format_specifier). | 
 | 5609 |  | 
 | 5610 |     It's assumed that if body is negative then it starts with '-'. | 
 | 5611 |     Any leading sign ('-' or '+') is stripped from the body before | 
 | 5612 |     applying the alignment and padding rules, and replaced in the | 
 | 5613 |     appropriate position. | 
 | 5614 |  | 
 | 5615 |     """ | 
 | 5616 |     # figure out the sign; we only examine the first character, so if | 
 | 5617 |     # body has leading whitespace the results may be surprising. | 
 | 5618 |     if len(body) > 0 and body[0] in '-+': | 
 | 5619 |         sign = body[0] | 
 | 5620 |         body = body[1:] | 
 | 5621 |     else: | 
 | 5622 |         sign = '' | 
 | 5623 |  | 
 | 5624 |     if sign != '-': | 
 | 5625 |         if spec_dict['sign'] in ' +': | 
 | 5626 |             sign = spec_dict['sign'] | 
 | 5627 |         else: | 
 | 5628 |             sign = '' | 
 | 5629 |  | 
 | 5630 |     # how much extra space do we have to play with? | 
 | 5631 |     minimumwidth = spec_dict['minimumwidth'] | 
 | 5632 |     fill = spec_dict['fill'] | 
 | 5633 |     padding = fill*(max(minimumwidth - (len(sign+body)), 0)) | 
 | 5634 |  | 
 | 5635 |     align = spec_dict['align'] | 
 | 5636 |     if align == '<': | 
 | 5637 |         result = padding + sign + body | 
 | 5638 |     elif align == '>': | 
 | 5639 |         result = sign + body + padding | 
 | 5640 |     elif align == '=': | 
 | 5641 |         result = sign + padding + body | 
 | 5642 |     else: #align == '^' | 
 | 5643 |         half = len(padding)//2 | 
 | 5644 |         result = padding[:half] + sign + body + padding[half:] | 
 | 5645 |  | 
| Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 5646 |     return result | 
| Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5647 |  | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 5648 | ##### Useful Constants (internal use only) ################################ | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5649 |  | 
| Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 5650 | # Reusable defaults | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 5651 | _Infinity = Decimal('Inf') | 
 | 5652 | _NegativeInfinity = Decimal('-Inf') | 
| Mark Dickinson | f923641 | 2009-01-02 23:23:21 +0000 | [diff] [blame] | 5653 | _NaN = Decimal('NaN') | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 5654 | _Zero = Decimal(0) | 
 | 5655 | _One = Decimal(1) | 
 | 5656 | _NegativeOne = Decimal(-1) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5657 |  | 
| Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 5658 | # _SignedInfinity[sign] is infinity w/ that sign | 
 | 5659 | _SignedInfinity = (_Infinity, _NegativeInfinity) | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5660 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5661 |  | 
| Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5662 |  | 
 | 5663 | if __name__ == '__main__': | 
 | 5664 |     import doctest, sys | 
 | 5665 |     doctest.testmod(sys.modules[__name__]) |