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 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +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 |
| 38 | of the expected Decimal("0.00") returned by decimal floating point). |
| 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) |
| 45 | Decimal("0") |
| 46 | >>> Decimal("1") |
| 47 | Decimal("1") |
| 48 | >>> Decimal("-.0123") |
| 49 | Decimal("-0.0123") |
| 50 | >>> Decimal(123456) |
| 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") |
| 58 | >>> dig = Decimal(1) |
| 59 | >>> print dig / Decimal(3) |
| 60 | 0.333333333 |
| 61 | >>> getcontext().prec = 18 |
| 62 | >>> print dig / Decimal(3) |
| 63 | 0.333333333333333333 |
| 64 | >>> print dig.sqrt() |
| 65 | 1 |
| 66 | >>> print Decimal(3).sqrt() |
| 67 | 1.73205080756887729 |
| 68 | >>> print Decimal(3) ** 123 |
| 69 | 4.85192780976896427E+58 |
| 70 | >>> inf = Decimal(1) / Decimal(0) |
| 71 | >>> print inf |
| 72 | Infinity |
| 73 | >>> neginf = Decimal(-1) / Decimal(0) |
| 74 | >>> print neginf |
| 75 | -Infinity |
| 76 | >>> print neginf + inf |
| 77 | NaN |
| 78 | >>> print neginf * inf |
| 79 | -Infinity |
| 80 | >>> print dig / 0 |
| 81 | Infinity |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 82 | >>> getcontext().traps[DivisionByZero] = 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 83 | >>> print dig / 0 |
| 84 | Traceback (most recent call last): |
| 85 | ... |
| 86 | ... |
| 87 | ... |
| 88 | DivisionByZero: x / 0 |
| 89 | >>> c = Context() |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 90 | >>> c.traps[InvalidOperation] = 0 |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +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)) |
| 94 | Decimal("NaN") |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 95 | >>> c.traps[InvalidOperation] = 1 |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +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 |
| 99 | >>> print c.flags[InvalidOperation] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 100 | 0 |
| 101 | >>> print c.divide(Decimal(0), Decimal(0)) |
| 102 | Traceback (most recent call last): |
| 103 | ... |
| 104 | ... |
| 105 | ... |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 106 | InvalidOperation: 0 / 0 |
| 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 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 111 | >>> print c.divide(Decimal(0), Decimal(0)) |
| 112 | NaN |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +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', |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +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 |
Nick Coghlan | 8b6999b | 2006-08-31 12:00:43 +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 | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 138 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 139 | # Rounding |
Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 140 | ROUND_DOWN = 'ROUND_DOWN' |
| 141 | ROUND_HALF_UP = 'ROUND_HALF_UP' |
| 142 | ROUND_HALF_EVEN = 'ROUND_HALF_EVEN' |
| 143 | ROUND_CEILING = 'ROUND_CEILING' |
| 144 | ROUND_FLOOR = 'ROUND_FLOOR' |
| 145 | ROUND_UP = 'ROUND_UP' |
| 146 | ROUND_HALF_DOWN = 'ROUND_HALF_DOWN' |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 147 | ROUND_05UP = 'ROUND_05UP' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 148 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 149 | # Rounding decision (not part of the public API) |
Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 150 | NEVER_ROUND = 'NEVER_ROUND' # Round in division (non-divmod), sqrt ONLY |
| 151 | ALWAYS_ROUND = 'ALWAYS_ROUND' # Every operation rounds at end. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 152 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 153 | # Errors |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 154 | |
| 155 | class DecimalException(ArithmeticError): |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 156 | """Base exception class. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 157 | |
| 158 | Used exceptions derive from this. |
| 159 | If an exception derives from another exception besides this (such as |
| 160 | Underflow (Inexact, Rounded, Subnormal) that indicates that it is only |
| 161 | called if the others are present. This isn't actually used for |
| 162 | anything, though. |
| 163 | |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 164 | handle -- Called when context._raise_error is called and the |
| 165 | trap_enabler is set. First argument is self, second is the |
| 166 | context. More arguments can be given, those being after |
| 167 | the explanation in _raise_error (For example, |
| 168 | context._raise_error(NewError, '(-x)!', self._sign) would |
| 169 | call NewError().handle(context, self._sign).) |
| 170 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 171 | To define a new exception, it should be sufficient to have it derive |
| 172 | from DecimalException. |
| 173 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 174 | def handle(self, context, *args): |
| 175 | pass |
| 176 | |
| 177 | |
| 178 | class Clamped(DecimalException): |
| 179 | """Exponent of a 0 changed to fit bounds. |
| 180 | |
| 181 | This occurs and signals clamped if the exponent of a result has been |
| 182 | altered in order to fit the constraints of a specific concrete |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 183 | representation. This may occur when the exponent of a zero result would |
| 184 | be outside the bounds of a representation, or when a large normal |
| 185 | number would have an encoded exponent that cannot be represented. In |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 186 | this latter case, the exponent is reduced to fit and the corresponding |
| 187 | number of zero digits are appended to the coefficient ("fold-down"). |
| 188 | """ |
| 189 | |
| 190 | |
| 191 | class InvalidOperation(DecimalException): |
| 192 | """An invalid operation was performed. |
| 193 | |
| 194 | Various bad things cause this: |
| 195 | |
| 196 | Something creates a signaling NaN |
| 197 | -INF + INF |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 198 | 0 * (+-)INF |
| 199 | (+-)INF / (+-)INF |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 200 | x % 0 |
| 201 | (+-)INF % x |
| 202 | x._rescale( non-integer ) |
| 203 | sqrt(-x) , x > 0 |
| 204 | 0 ** 0 |
| 205 | x ** (non-integer) |
| 206 | x ** (+-)INF |
| 207 | An operand is invalid |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 208 | |
| 209 | The result of the operation after these is a quiet positive NaN, |
| 210 | except when the cause is a signaling NaN, in which case the result is |
| 211 | also a quiet NaN, but with the original sign, and an optional |
| 212 | diagnostic information. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 213 | """ |
| 214 | def handle(self, context, *args): |
| 215 | if args: |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 216 | if args[0] == 1: # sNaN, must drop 's' but keep diagnostics |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 217 | ans = _dec_from_triple(args[1]._sign, args[1]._int, 'n', True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 218 | return ans._fix_nan(context) |
| 219 | elif args[0] == 2: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 220 | return _dec_from_triple(args[1], args[2], 'n', True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 221 | return NaN |
| 222 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 223 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 224 | class ConversionSyntax(InvalidOperation): |
| 225 | """Trying to convert badly formed string. |
| 226 | |
| 227 | This occurs and signals invalid-operation if an string is being |
| 228 | converted to a number and it does not conform to the numeric string |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 229 | syntax. The result is [0,qNaN]. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 230 | """ |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 231 | def handle(self, context, *args): |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 232 | return NaN |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 233 | |
| 234 | class DivisionByZero(DecimalException, ZeroDivisionError): |
| 235 | """Division by 0. |
| 236 | |
| 237 | This occurs and signals division-by-zero if division of a finite number |
| 238 | by zero was attempted (during a divide-integer or divide operation, or a |
| 239 | power operation with negative right-hand operand), and the dividend was |
| 240 | not zero. |
| 241 | |
| 242 | The result of the operation is [sign,inf], where sign is the exclusive |
| 243 | or of the signs of the operands for divide, or is 1 for an odd power of |
| 244 | -0, for power. |
| 245 | """ |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 246 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 247 | def handle(self, context, sign, *args): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 248 | return Infsign[sign] |
| 249 | |
| 250 | class DivisionImpossible(InvalidOperation): |
| 251 | """Cannot perform the division adequately. |
| 252 | |
| 253 | This occurs and signals invalid-operation if the integer result of a |
| 254 | divide-integer or remainder operation had too many digits (would be |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 255 | longer than precision). The result is [0,qNaN]. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 256 | """ |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 257 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 258 | def handle(self, context, *args): |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 259 | return NaN |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 260 | |
| 261 | class DivisionUndefined(InvalidOperation, ZeroDivisionError): |
| 262 | """Undefined result of division. |
| 263 | |
| 264 | This occurs and signals invalid-operation if division by zero was |
| 265 | attempted (during a divide-integer, divide, or remainder operation), and |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 266 | the dividend is also zero. The result is [0,qNaN]. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 267 | """ |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 268 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 269 | def handle(self, context, *args): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 270 | return NaN |
| 271 | |
| 272 | class Inexact(DecimalException): |
| 273 | """Had to round, losing information. |
| 274 | |
| 275 | This occurs and signals inexact whenever the result of an operation is |
| 276 | not exact (that is, it needed to be rounded and any discarded digits |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 277 | were non-zero), or if an overflow or underflow condition occurs. The |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 278 | result in all cases is unchanged. |
| 279 | |
| 280 | The inexact signal may be tested (or trapped) to determine if a given |
| 281 | operation (or sequence of operations) was inexact. |
| 282 | """ |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 283 | pass |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 284 | |
| 285 | class InvalidContext(InvalidOperation): |
| 286 | """Invalid context. Unknown rounding, for example. |
| 287 | |
| 288 | This occurs and signals invalid-operation if an invalid context was |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 289 | detected during an operation. This can occur if contexts are not checked |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 290 | on creation and either the precision exceeds the capability of the |
| 291 | underlying concrete representation or an unknown or unsupported rounding |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 292 | was specified. These aspects of the context need only be checked when |
| 293 | the values are required to be used. The result is [0,qNaN]. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 294 | """ |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 295 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 296 | def handle(self, context, *args): |
| 297 | return NaN |
| 298 | |
| 299 | class Rounded(DecimalException): |
| 300 | """Number got rounded (not necessarily changed during rounding). |
| 301 | |
| 302 | This occurs and signals rounded whenever the result of an operation is |
| 303 | rounded (that is, some zero or non-zero digits were discarded from the |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 304 | coefficient), or if an overflow or underflow condition occurs. The |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 305 | result in all cases is unchanged. |
| 306 | |
| 307 | The rounded signal may be tested (or trapped) to determine if a given |
| 308 | operation (or sequence of operations) caused a loss of precision. |
| 309 | """ |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 310 | pass |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 311 | |
| 312 | class Subnormal(DecimalException): |
| 313 | """Exponent < Emin before rounding. |
| 314 | |
| 315 | This occurs and signals subnormal whenever the result of a conversion or |
| 316 | operation is subnormal (that is, its adjusted exponent is less than |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 317 | Emin, before any rounding). The result in all cases is unchanged. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 318 | |
| 319 | The subnormal signal may be tested (or trapped) to determine if a given |
| 320 | or operation (or sequence of operations) yielded a subnormal result. |
| 321 | """ |
| 322 | pass |
| 323 | |
| 324 | class Overflow(Inexact, Rounded): |
| 325 | """Numerical overflow. |
| 326 | |
| 327 | This occurs and signals overflow if the adjusted exponent of a result |
| 328 | (from a conversion or from an operation that is not an attempt to divide |
| 329 | by zero), after rounding, would be greater than the largest value that |
| 330 | can be handled by the implementation (the value Emax). |
| 331 | |
| 332 | The result depends on the rounding mode: |
| 333 | |
| 334 | For round-half-up and round-half-even (and for round-half-down and |
| 335 | round-up, if implemented), the result of the operation is [sign,inf], |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 336 | 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] | 337 | result is the largest finite number that can be represented in the |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 338 | current precision, with the sign of the intermediate result. For |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 339 | round-ceiling, the result is the same as for round-down if the sign of |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 340 | 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] | 341 | the result is the same as for round-down if the sign of the intermediate |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 342 | 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] | 343 | will also be raised. |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 344 | """ |
| 345 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 346 | def handle(self, context, sign, *args): |
| 347 | if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN, |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 348 | ROUND_HALF_DOWN, ROUND_UP): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 349 | return Infsign[sign] |
| 350 | if sign == 0: |
| 351 | if context.rounding == ROUND_CEILING: |
| 352 | return Infsign[sign] |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 353 | return _dec_from_triple(sign, '9'*context.prec, |
| 354 | context.Emax-context.prec+1) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 355 | if sign == 1: |
| 356 | if context.rounding == ROUND_FLOOR: |
| 357 | return Infsign[sign] |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 358 | return _dec_from_triple(sign, '9'*context.prec, |
| 359 | context.Emax-context.prec+1) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 360 | |
| 361 | |
| 362 | class Underflow(Inexact, Rounded, Subnormal): |
| 363 | """Numerical underflow with result rounded to 0. |
| 364 | |
| 365 | This occurs and signals underflow if a result is inexact and the |
| 366 | adjusted exponent of the result would be smaller (more negative) than |
| 367 | the smallest value that can be handled by the implementation (the value |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 368 | Emin). That is, the result is both inexact and subnormal. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 369 | |
| 370 | The result after an underflow will be a subnormal number rounded, if |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 371 | 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] | 372 | in 0 with the sign of the intermediate result and an exponent of Etiny. |
| 373 | |
| 374 | In all cases, Inexact, Rounded, and Subnormal will also be raised. |
| 375 | """ |
| 376 | |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 377 | # List of public traps and flags |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 378 | _signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded, |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 379 | Underflow, InvalidOperation, Subnormal] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 380 | |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 381 | # Map conditions (per the spec) to signals |
| 382 | _condition_map = {ConversionSyntax:InvalidOperation, |
| 383 | DivisionImpossible:InvalidOperation, |
| 384 | DivisionUndefined:InvalidOperation, |
| 385 | InvalidContext:InvalidOperation} |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 386 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 387 | ##### Context Functions ################################################## |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 388 | |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 389 | # The getcontext() and setcontext() function manage access to a thread-local |
| 390 | # current context. Py2.4 offers direct support for thread locals. If that |
| 391 | # is not available, use threading.currentThread() which is slower but will |
Raymond Hettinger | 7e71fa5 | 2004-12-18 19:07:19 +0000 | [diff] [blame] | 392 | # work for older Pythons. If threads are not part of the build, create a |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 393 | # mock threading object with threading.local() returning the module namespace. |
Raymond Hettinger | 7e71fa5 | 2004-12-18 19:07:19 +0000 | [diff] [blame] | 394 | |
| 395 | try: |
| 396 | import threading |
| 397 | except ImportError: |
| 398 | # Python was compiled without threads; create a mock object instead |
| 399 | import sys |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 400 | class MockThreading(object): |
Raymond Hettinger | 7e71fa5 | 2004-12-18 19:07:19 +0000 | [diff] [blame] | 401 | def local(self, sys=sys): |
| 402 | return sys.modules[__name__] |
| 403 | threading = MockThreading() |
| 404 | del sys, MockThreading |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 405 | |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 406 | try: |
| 407 | threading.local |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 408 | |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 409 | except AttributeError: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 410 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 411 | # To fix reloading, force it to create a new context |
| 412 | # Old contexts have different exceptions in their dicts, making problems. |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 413 | if hasattr(threading.currentThread(), '__decimal_context__'): |
| 414 | del threading.currentThread().__decimal_context__ |
| 415 | |
| 416 | def setcontext(context): |
| 417 | """Set this thread's context to context.""" |
| 418 | if context in (DefaultContext, BasicContext, ExtendedContext): |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 419 | context = context.copy() |
Raymond Hettinger | 61992ef | 2004-08-06 23:42:16 +0000 | [diff] [blame] | 420 | context.clear_flags() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 421 | threading.currentThread().__decimal_context__ = context |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 422 | |
| 423 | def getcontext(): |
| 424 | """Returns this thread's context. |
| 425 | |
| 426 | If this thread does not yet have a context, returns |
| 427 | a new context and sets this thread's context. |
| 428 | New contexts are copies of DefaultContext. |
| 429 | """ |
| 430 | try: |
| 431 | return threading.currentThread().__decimal_context__ |
| 432 | except AttributeError: |
| 433 | context = Context() |
| 434 | threading.currentThread().__decimal_context__ = context |
| 435 | return context |
| 436 | |
| 437 | else: |
| 438 | |
| 439 | local = threading.local() |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 440 | if hasattr(local, '__decimal_context__'): |
| 441 | del local.__decimal_context__ |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 442 | |
| 443 | def getcontext(_local=local): |
| 444 | """Returns this thread's context. |
| 445 | |
| 446 | If this thread does not yet have a context, returns |
| 447 | a new context and sets this thread's context. |
| 448 | New contexts are copies of DefaultContext. |
| 449 | """ |
| 450 | try: |
| 451 | return _local.__decimal_context__ |
| 452 | except AttributeError: |
| 453 | context = Context() |
| 454 | _local.__decimal_context__ = context |
| 455 | return context |
| 456 | |
| 457 | def setcontext(context, _local=local): |
| 458 | """Set this thread's context to context.""" |
| 459 | if context in (DefaultContext, BasicContext, ExtendedContext): |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 460 | context = context.copy() |
Raymond Hettinger | 61992ef | 2004-08-06 23:42:16 +0000 | [diff] [blame] | 461 | context.clear_flags() |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 462 | _local.__decimal_context__ = context |
| 463 | |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 464 | del threading, local # Don't contaminate the namespace |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 465 | |
Nick Coghlan | 8b6999b | 2006-08-31 12:00:43 +0000 | [diff] [blame] | 466 | def localcontext(ctx=None): |
| 467 | """Return a context manager for a copy of the supplied context |
| 468 | |
| 469 | Uses a copy of the current context if no context is specified |
| 470 | The returned context manager creates a local decimal context |
| 471 | in a with statement: |
| 472 | def sin(x): |
| 473 | with localcontext() as ctx: |
| 474 | ctx.prec += 2 |
| 475 | # Rest of sin calculation algorithm |
| 476 | # uses a precision 2 greater than normal |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 477 | return +s # Convert result to normal precision |
Nick Coghlan | 8b6999b | 2006-08-31 12:00:43 +0000 | [diff] [blame] | 478 | |
| 479 | def sin(x): |
| 480 | with localcontext(ExtendedContext): |
| 481 | # Rest of sin calculation algorithm |
| 482 | # uses the Extended Context from the |
| 483 | # General Decimal Arithmetic Specification |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 484 | return +s # Convert result to normal context |
Nick Coghlan | 8b6999b | 2006-08-31 12:00:43 +0000 | [diff] [blame] | 485 | |
| 486 | """ |
Neal Norwitz | 681d867 | 2006-09-02 18:51:34 +0000 | [diff] [blame] | 487 | # The string below can't be included in the docstring until Python 2.6 |
Nick Coghlan | 8b6999b | 2006-08-31 12:00:43 +0000 | [diff] [blame] | 488 | # as the doctest module doesn't understand __future__ statements |
| 489 | """ |
| 490 | >>> from __future__ import with_statement |
| 491 | >>> print getcontext().prec |
| 492 | 28 |
| 493 | >>> with localcontext(): |
| 494 | ... ctx = getcontext() |
Raymond Hettinger | 495df47 | 2007-02-08 01:42:35 +0000 | [diff] [blame] | 495 | ... ctx.prec += 2 |
Nick Coghlan | 8b6999b | 2006-08-31 12:00:43 +0000 | [diff] [blame] | 496 | ... print ctx.prec |
| 497 | ... |
| 498 | 30 |
| 499 | >>> with localcontext(ExtendedContext): |
| 500 | ... print getcontext().prec |
| 501 | ... |
| 502 | 9 |
| 503 | >>> print getcontext().prec |
| 504 | 28 |
| 505 | """ |
Nick Coghlan | ced1218 | 2006-09-02 03:54:17 +0000 | [diff] [blame] | 506 | if ctx is None: ctx = getcontext() |
| 507 | return _ContextManager(ctx) |
Nick Coghlan | 8b6999b | 2006-08-31 12:00:43 +0000 | [diff] [blame] | 508 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 509 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 510 | ##### Decimal class ####################################################### |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 511 | |
| 512 | class Decimal(object): |
| 513 | """Floating point class for decimal arithmetic.""" |
| 514 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 515 | __slots__ = ('_exp','_int','_sign', '_is_special') |
| 516 | # Generally, the value of the Decimal instance is given by |
| 517 | # (-1)**_sign * _int * 10**_exp |
| 518 | # Special values are signified by _is_special == True |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 519 | |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 520 | # We're immutable, so use __new__ not __init__ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 521 | def __new__(cls, value="0", context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 522 | """Create a decimal point instance. |
| 523 | |
| 524 | >>> Decimal('3.14') # string input |
| 525 | Decimal("3.14") |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 526 | >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 527 | Decimal("3.14") |
| 528 | >>> Decimal(314) # int or long |
| 529 | Decimal("314") |
| 530 | >>> Decimal(Decimal(314)) # another decimal instance |
| 531 | Decimal("314") |
| 532 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 533 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 534 | # Note that the coefficient, self._int, is actually stored as |
| 535 | # a string rather than as a tuple of digits. This speeds up |
| 536 | # the "digits to integer" and "integer to digits" conversions |
| 537 | # that are used in almost every arithmetic operation on |
| 538 | # Decimals. This is an internal detail: the as_tuple function |
| 539 | # and the Decimal constructor still deal with tuples of |
| 540 | # digits. |
| 541 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 542 | self = object.__new__(cls) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 543 | |
Facundo Batista | 0d157a0 | 2007-11-30 17:15:25 +0000 | [diff] [blame] | 544 | # From a string |
| 545 | # REs insist on real strings, so we can too. |
| 546 | if isinstance(value, basestring): |
| 547 | m = _parser(value) |
| 548 | if m is None: |
| 549 | if context is None: |
| 550 | context = getcontext() |
| 551 | return context._raise_error(ConversionSyntax, |
| 552 | "Invalid literal for Decimal: %r" % value) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 553 | |
Facundo Batista | 0d157a0 | 2007-11-30 17:15:25 +0000 | [diff] [blame] | 554 | if m.group('sign') == "-": |
| 555 | self._sign = 1 |
| 556 | else: |
| 557 | self._sign = 0 |
| 558 | intpart = m.group('int') |
| 559 | if intpart is not None: |
| 560 | # finite number |
| 561 | fracpart = m.group('frac') |
| 562 | exp = int(m.group('exp') or '0') |
| 563 | if fracpart is not None: |
| 564 | self._int = (intpart+fracpart).lstrip('0') or '0' |
| 565 | self._exp = exp - len(fracpart) |
| 566 | else: |
| 567 | self._int = intpart.lstrip('0') or '0' |
| 568 | self._exp = exp |
| 569 | self._is_special = False |
| 570 | else: |
| 571 | diag = m.group('diag') |
| 572 | if diag is not None: |
| 573 | # NaN |
| 574 | self._int = diag.lstrip('0') |
| 575 | if m.group('signal'): |
| 576 | self._exp = 'N' |
| 577 | else: |
| 578 | self._exp = 'n' |
| 579 | else: |
| 580 | # infinity |
| 581 | self._int = '0' |
| 582 | self._exp = 'F' |
| 583 | self._is_special = True |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 584 | return self |
| 585 | |
| 586 | # From an integer |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 587 | if isinstance(value, (int,long)): |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 588 | if value >= 0: |
| 589 | self._sign = 0 |
| 590 | else: |
| 591 | self._sign = 1 |
| 592 | self._exp = 0 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 593 | self._int = str(abs(value)) |
Facundo Batista | 0d157a0 | 2007-11-30 17:15:25 +0000 | [diff] [blame] | 594 | self._is_special = False |
| 595 | return self |
| 596 | |
| 597 | # From another decimal |
| 598 | if isinstance(value, Decimal): |
| 599 | self._exp = value._exp |
| 600 | self._sign = value._sign |
| 601 | self._int = value._int |
| 602 | self._is_special = value._is_special |
| 603 | return self |
| 604 | |
| 605 | # From an internal working value |
| 606 | if isinstance(value, _WorkRep): |
| 607 | self._sign = value.sign |
| 608 | self._int = str(value.int) |
| 609 | self._exp = int(value.exp) |
| 610 | self._is_special = False |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 611 | return self |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 612 | |
| 613 | # tuple/list conversion (possibly from as_tuple()) |
| 614 | if isinstance(value, (list,tuple)): |
| 615 | if len(value) != 3: |
Facundo Batista | 9b5e231 | 2007-10-19 19:25:57 +0000 | [diff] [blame] | 616 | raise ValueError('Invalid tuple size in creation of Decimal ' |
| 617 | 'from list or tuple. The list or tuple ' |
| 618 | 'should have exactly three elements.') |
| 619 | # process sign. The isinstance test rejects floats |
| 620 | if not (isinstance(value[0], (int, long)) and value[0] in (0,1)): |
| 621 | raise ValueError("Invalid sign. The first value in the tuple " |
| 622 | "should be an integer; either 0 for a " |
| 623 | "positive number or 1 for a negative number.") |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 624 | self._sign = value[0] |
Facundo Batista | 9b5e231 | 2007-10-19 19:25:57 +0000 | [diff] [blame] | 625 | if value[2] == 'F': |
| 626 | # infinity: value[1] is ignored |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 627 | self._int = '0' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 628 | self._exp = value[2] |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 629 | self._is_special = True |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 630 | else: |
Facundo Batista | 9b5e231 | 2007-10-19 19:25:57 +0000 | [diff] [blame] | 631 | # process and validate the digits in value[1] |
| 632 | digits = [] |
| 633 | for digit in value[1]: |
| 634 | if isinstance(digit, (int, long)) and 0 <= digit <= 9: |
| 635 | # skip leading zeros |
| 636 | if digits or digit != 0: |
| 637 | digits.append(digit) |
| 638 | else: |
| 639 | raise ValueError("The second value in the tuple must " |
| 640 | "be composed of integers in the range " |
| 641 | "0 through 9.") |
| 642 | if value[2] in ('n', 'N'): |
| 643 | # NaN: digits form the diagnostic |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 644 | self._int = ''.join(map(str, digits)) |
Facundo Batista | 9b5e231 | 2007-10-19 19:25:57 +0000 | [diff] [blame] | 645 | self._exp = value[2] |
| 646 | self._is_special = True |
| 647 | elif isinstance(value[2], (int, long)): |
| 648 | # finite number: digits give the coefficient |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 649 | self._int = ''.join(map(str, digits or [0])) |
Facundo Batista | 9b5e231 | 2007-10-19 19:25:57 +0000 | [diff] [blame] | 650 | self._exp = value[2] |
| 651 | self._is_special = False |
| 652 | else: |
| 653 | raise ValueError("The third value in the tuple must " |
| 654 | "be an integer, or one of the " |
| 655 | "strings 'F', 'n', 'N'.") |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 656 | return self |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 657 | |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 658 | if isinstance(value, float): |
| 659 | raise TypeError("Cannot convert float to Decimal. " + |
| 660 | "First convert the float to a string") |
| 661 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 662 | raise TypeError("Cannot convert %r to Decimal" % value) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 663 | |
| 664 | def _isnan(self): |
| 665 | """Returns whether the number is not actually one. |
| 666 | |
| 667 | 0 if a number |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 668 | 1 if NaN (it could be a normal quiet NaN or a phantom one) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 669 | 2 if sNaN |
| 670 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 671 | if self._is_special: |
| 672 | exp = self._exp |
| 673 | if exp == 'n': |
| 674 | return 1 |
| 675 | elif exp == 'N': |
| 676 | return 2 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 677 | return 0 |
| 678 | |
| 679 | def _isinfinity(self): |
| 680 | """Returns whether the number is infinite |
| 681 | |
| 682 | 0 if finite or not a number |
| 683 | 1 if +INF |
| 684 | -1 if -INF |
| 685 | """ |
| 686 | if self._exp == 'F': |
| 687 | if self._sign: |
| 688 | return -1 |
| 689 | return 1 |
| 690 | return 0 |
| 691 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 692 | def _check_nans(self, other=None, context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 693 | """Returns whether the number is not actually one. |
| 694 | |
| 695 | if self, other are sNaN, signal |
| 696 | if self, other are NaN return nan |
| 697 | return 0 |
| 698 | |
| 699 | Done before operations. |
| 700 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 701 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 702 | self_is_nan = self._isnan() |
| 703 | if other is None: |
| 704 | other_is_nan = False |
| 705 | else: |
| 706 | other_is_nan = other._isnan() |
| 707 | |
| 708 | if self_is_nan or other_is_nan: |
| 709 | if context is None: |
| 710 | context = getcontext() |
| 711 | |
| 712 | if self_is_nan == 2: |
| 713 | return context._raise_error(InvalidOperation, 'sNaN', |
| 714 | 1, self) |
| 715 | if other_is_nan == 2: |
| 716 | return context._raise_error(InvalidOperation, 'sNaN', |
| 717 | 1, other) |
| 718 | if self_is_nan: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 719 | return self._fix_nan(context) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 720 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 721 | return other._fix_nan(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 722 | return 0 |
| 723 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 724 | def __nonzero__(self): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 725 | """Return True if self is nonzero; otherwise return False. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 726 | |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 727 | NaNs and infinities are considered nonzero. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 728 | """ |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 729 | return self._is_special or self._int != '0' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 730 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 731 | def __cmp__(self, other): |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 732 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 733 | if other is NotImplemented: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 734 | # Never return NotImplemented |
| 735 | return 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 736 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 737 | if self._is_special or other._is_special: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 738 | # check for nans, without raising on a signaling nan |
| 739 | if self._isnan() or other._isnan(): |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 740 | return 1 # Comparison involving NaN's always reports self > other |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 741 | |
| 742 | # INF = INF |
| 743 | return cmp(self._isinfinity(), other._isinfinity()) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 744 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 745 | # check for zeros; note that cmp(0, -0) should return 0 |
| 746 | if not self: |
| 747 | if not other: |
| 748 | return 0 |
| 749 | else: |
| 750 | return -((-1)**other._sign) |
| 751 | if not other: |
| 752 | return (-1)**self._sign |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 753 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 754 | # If different signs, neg one is less |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 755 | if other._sign < self._sign: |
| 756 | return -1 |
| 757 | if self._sign < other._sign: |
| 758 | return 1 |
| 759 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 760 | self_adjusted = self.adjusted() |
| 761 | other_adjusted = other.adjusted() |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 762 | if self_adjusted == other_adjusted: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 763 | self_padded = self._int + '0'*(self._exp - other._exp) |
| 764 | other_padded = other._int + '0'*(other._exp - self._exp) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 765 | return cmp(self_padded, other_padded) * (-1)**self._sign |
| 766 | elif self_adjusted > other_adjusted: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 767 | return (-1)**self._sign |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 768 | else: # self_adjusted < other_adjusted |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 769 | return -((-1)**self._sign) |
| 770 | |
Raymond Hettinger | 0aeac10 | 2004-07-05 22:53:03 +0000 | [diff] [blame] | 771 | def __eq__(self, other): |
| 772 | if not isinstance(other, (Decimal, int, long)): |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 773 | return NotImplemented |
Raymond Hettinger | 0aeac10 | 2004-07-05 22:53:03 +0000 | [diff] [blame] | 774 | return self.__cmp__(other) == 0 |
| 775 | |
| 776 | def __ne__(self, other): |
| 777 | if not isinstance(other, (Decimal, int, long)): |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 778 | return NotImplemented |
Raymond Hettinger | 0aeac10 | 2004-07-05 22:53:03 +0000 | [diff] [blame] | 779 | return self.__cmp__(other) != 0 |
| 780 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 781 | def compare(self, other, context=None): |
| 782 | """Compares one to another. |
| 783 | |
| 784 | -1 => a < b |
| 785 | 0 => a = b |
| 786 | 1 => a > b |
| 787 | NaN => one is NaN |
| 788 | Like __cmp__, but returns Decimal instances. |
| 789 | """ |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 790 | other = _convert_other(other, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 791 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 792 | # Compare(NaN, NaN) = NaN |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 793 | if (self._is_special or other and other._is_special): |
| 794 | ans = self._check_nans(other, context) |
| 795 | if ans: |
| 796 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 797 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 798 | return Decimal(self.__cmp__(other)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 799 | |
| 800 | def __hash__(self): |
| 801 | """x.__hash__() <==> hash(x)""" |
| 802 | # Decimal integers must hash the same as the ints |
| 803 | # Non-integer decimals are normalized and hashed as strings |
Georg Brandl | 1fb9f52 | 2006-05-11 19:57:09 +0000 | [diff] [blame] | 804 | # Normalization assures that hash(100E-1) == hash(10) |
Raymond Hettinger | bea3f6f | 2005-03-15 04:59:17 +0000 | [diff] [blame] | 805 | if self._is_special: |
| 806 | if self._isnan(): |
| 807 | raise TypeError('Cannot hash a NaN value.') |
| 808 | return hash(str(self)) |
Facundo Batista | 8c20244 | 2007-09-19 17:53:25 +0000 | [diff] [blame] | 809 | if not self: |
| 810 | return 0 |
| 811 | if self._isinteger(): |
| 812 | op = _WorkRep(self.to_integral_value()) |
| 813 | # to make computation feasible for Decimals with large |
| 814 | # exponent, we use the fact that hash(n) == hash(m) for |
| 815 | # any two nonzero integers n and m such that (i) n and m |
| 816 | # have the same sign, and (ii) n is congruent to m modulo |
| 817 | # 2**64-1. So we can replace hash((-1)**s*c*10**e) with |
| 818 | # hash((-1)**s*c*pow(10, e, 2**64-1). |
| 819 | return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 820 | return hash(str(self.normalize())) |
| 821 | |
| 822 | def as_tuple(self): |
| 823 | """Represents the number as a triple tuple. |
| 824 | |
| 825 | To show the internals exactly as they are. |
| 826 | """ |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 827 | return (self._sign, tuple(map(int, self._int)), self._exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 828 | |
| 829 | def __repr__(self): |
| 830 | """Represents the number as an instance of Decimal.""" |
| 831 | # Invariant: eval(repr(d)) == d |
| 832 | return 'Decimal("%s")' % str(self) |
| 833 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 834 | def __str__(self, eng=False, context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 835 | """Return string representation of the number in scientific notation. |
| 836 | |
| 837 | Captures all of the information in the underlying representation. |
| 838 | """ |
| 839 | |
Facundo Batista | 62edb71 | 2007-12-03 16:29:52 +0000 | [diff] [blame] | 840 | sign = ['', '-'][self._sign] |
Raymond Hettinger | e5a0a96 | 2005-06-20 09:49:42 +0000 | [diff] [blame] | 841 | if self._is_special: |
Facundo Batista | 62edb71 | 2007-12-03 16:29:52 +0000 | [diff] [blame] | 842 | if self._exp == 'F': |
| 843 | return sign + 'Infinity' |
| 844 | elif self._exp == 'n': |
| 845 | return sign + 'NaN' + self._int |
| 846 | else: # self._exp == 'N' |
| 847 | return sign + 'sNaN' + self._int |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 848 | |
Facundo Batista | 62edb71 | 2007-12-03 16:29:52 +0000 | [diff] [blame] | 849 | # number of digits of self._int to left of decimal point |
| 850 | leftdigits = self._exp + len(self._int) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 851 | |
Facundo Batista | 62edb71 | 2007-12-03 16:29:52 +0000 | [diff] [blame] | 852 | # dotplace is number of digits of self._int to the left of the |
| 853 | # decimal point in the mantissa of the output string (that is, |
| 854 | # after adjusting the exponent) |
| 855 | if self._exp <= 0 and leftdigits > -6: |
| 856 | # no exponent required |
| 857 | dotplace = leftdigits |
| 858 | elif not eng: |
| 859 | # usual scientific notation: 1 digit on left of the point |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 860 | dotplace = 1 |
Facundo Batista | 62edb71 | 2007-12-03 16:29:52 +0000 | [diff] [blame] | 861 | elif self._int == '0': |
| 862 | # engineering notation, zero |
| 863 | dotplace = (leftdigits + 1) % 3 - 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 864 | else: |
Facundo Batista | 62edb71 | 2007-12-03 16:29:52 +0000 | [diff] [blame] | 865 | # engineering notation, nonzero |
| 866 | dotplace = (leftdigits - 1) % 3 + 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 867 | |
Facundo Batista | 62edb71 | 2007-12-03 16:29:52 +0000 | [diff] [blame] | 868 | if dotplace <= 0: |
| 869 | intpart = '0' |
| 870 | fracpart = '.' + '0'*(-dotplace) + self._int |
| 871 | elif dotplace >= len(self._int): |
| 872 | intpart = self._int+'0'*(dotplace-len(self._int)) |
| 873 | fracpart = '' |
| 874 | else: |
| 875 | intpart = self._int[:dotplace] |
| 876 | fracpart = '.' + self._int[dotplace:] |
| 877 | if leftdigits == dotplace: |
| 878 | exp = '' |
| 879 | else: |
| 880 | if context is None: |
| 881 | context = getcontext() |
| 882 | exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace) |
| 883 | |
| 884 | return sign + intpart + fracpart + exp |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 885 | |
| 886 | def to_eng_string(self, context=None): |
| 887 | """Convert to engineering-type string. |
| 888 | |
| 889 | Engineering notation has an exponent which is a multiple of 3, so there |
| 890 | are up to 3 digits left of the decimal place. |
| 891 | |
| 892 | Same rules for when in exponential and when as a value as in __str__. |
| 893 | """ |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 894 | return self.__str__(eng=True, context=context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 895 | |
| 896 | def __neg__(self, context=None): |
| 897 | """Returns a copy with the sign switched. |
| 898 | |
| 899 | Rounds, if it has reason. |
| 900 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 901 | if self._is_special: |
| 902 | ans = self._check_nans(context=context) |
| 903 | if ans: |
| 904 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 905 | |
| 906 | if not self: |
| 907 | # -Decimal('0') is Decimal('0'), not Decimal('-0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 908 | ans = self.copy_sign(Dec_0) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 909 | else: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 910 | ans = self.copy_negate() |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 911 | |
| 912 | if context is None: |
| 913 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 914 | if context._rounding_decision == ALWAYS_ROUND: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 915 | return ans._fix(context) |
| 916 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 917 | |
| 918 | def __pos__(self, context=None): |
| 919 | """Returns a copy, unless it is a sNaN. |
| 920 | |
| 921 | Rounds the number (if more then precision digits) |
| 922 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 923 | if self._is_special: |
| 924 | ans = self._check_nans(context=context) |
| 925 | if ans: |
| 926 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 927 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 928 | if not self: |
| 929 | # + (-0) = 0 |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 930 | ans = self.copy_sign(Dec_0) |
| 931 | else: |
| 932 | ans = Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 933 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 934 | if context is None: |
| 935 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 936 | if context._rounding_decision == ALWAYS_ROUND: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 937 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 938 | return ans |
| 939 | |
| 940 | def __abs__(self, round=1, context=None): |
| 941 | """Returns the absolute value of self. |
| 942 | |
| 943 | If the second argument is 0, do not round. |
| 944 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 945 | if self._is_special: |
| 946 | ans = self._check_nans(context=context) |
| 947 | if ans: |
| 948 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 949 | |
| 950 | if not round: |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 951 | if context is None: |
| 952 | context = getcontext() |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 953 | context = context._shallow_copy() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 954 | context._set_rounding_decision(NEVER_ROUND) |
| 955 | |
| 956 | if self._sign: |
| 957 | ans = self.__neg__(context=context) |
| 958 | else: |
| 959 | ans = self.__pos__(context=context) |
| 960 | |
| 961 | return ans |
| 962 | |
| 963 | def __add__(self, other, context=None): |
| 964 | """Returns self + other. |
| 965 | |
| 966 | -INF + INF (or the reverse) cause InvalidOperation errors. |
| 967 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 968 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 969 | if other is NotImplemented: |
| 970 | return other |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 971 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 972 | if context is None: |
| 973 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 974 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 975 | if self._is_special or other._is_special: |
| 976 | ans = self._check_nans(other, context) |
| 977 | if ans: |
| 978 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 979 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 980 | if self._isinfinity(): |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 981 | # If both INF, same sign => same as both, opposite => error. |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 982 | if self._sign != other._sign and other._isinfinity(): |
| 983 | return context._raise_error(InvalidOperation, '-INF + INF') |
| 984 | return Decimal(self) |
| 985 | if other._isinfinity(): |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 986 | return Decimal(other) # Can't both be infinity here |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 987 | |
| 988 | shouldround = context._rounding_decision == ALWAYS_ROUND |
| 989 | |
| 990 | exp = min(self._exp, other._exp) |
| 991 | negativezero = 0 |
| 992 | if context.rounding == ROUND_FLOOR and self._sign != other._sign: |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 993 | # 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] | 994 | negativezero = 1 |
| 995 | |
| 996 | if not self and not other: |
| 997 | sign = min(self._sign, other._sign) |
| 998 | if negativezero: |
| 999 | sign = 1 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1000 | ans = _dec_from_triple(sign, '0', exp) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1001 | if shouldround: |
| 1002 | ans = ans._fix(context) |
| 1003 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1004 | if not self: |
Facundo Batista | 99b5548 | 2004-10-26 23:38:46 +0000 | [diff] [blame] | 1005 | exp = max(exp, other._exp - context.prec-1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1006 | ans = other._rescale(exp, context.rounding) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1007 | if shouldround: |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1008 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1009 | return ans |
| 1010 | if not other: |
Facundo Batista | 99b5548 | 2004-10-26 23:38:46 +0000 | [diff] [blame] | 1011 | exp = max(exp, self._exp - context.prec-1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1012 | ans = self._rescale(exp, context.rounding) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1013 | if shouldround: |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1014 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1015 | return ans |
| 1016 | |
| 1017 | op1 = _WorkRep(self) |
| 1018 | op2 = _WorkRep(other) |
| 1019 | op1, op2 = _normalize(op1, op2, shouldround, context.prec) |
| 1020 | |
| 1021 | result = _WorkRep() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1022 | if op1.sign != op2.sign: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1023 | # Equal and opposite |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1024 | if op1.int == op2.int: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1025 | ans = _dec_from_triple(negativezero, '0', exp) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1026 | if shouldround: |
| 1027 | ans = ans._fix(context) |
| 1028 | return ans |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1029 | if op1.int < op2.int: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1030 | op1, op2 = op2, op1 |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 1031 | # OK, now abs(op1) > abs(op2) |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1032 | if op1.sign == 1: |
| 1033 | result.sign = 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1034 | op1.sign, op2.sign = op2.sign, op1.sign |
| 1035 | else: |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1036 | result.sign = 0 |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 1037 | # So we know the sign, and op1 > 0. |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1038 | elif op1.sign == 1: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1039 | result.sign = 1 |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1040 | op1.sign, op2.sign = (0, 0) |
| 1041 | else: |
| 1042 | result.sign = 0 |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 1043 | # Now, op1 > abs(op2) > 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1044 | |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1045 | if op2.sign == 0: |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1046 | result.int = op1.int + op2.int |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1047 | else: |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1048 | result.int = op1.int - op2.int |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1049 | |
| 1050 | result.exp = op1.exp |
| 1051 | ans = Decimal(result) |
| 1052 | if shouldround: |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1053 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1054 | return ans |
| 1055 | |
| 1056 | __radd__ = __add__ |
| 1057 | |
| 1058 | def __sub__(self, other, context=None): |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1059 | """Return self - other""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1060 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1061 | if other is NotImplemented: |
| 1062 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1063 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1064 | if self._is_special or other._is_special: |
| 1065 | ans = self._check_nans(other, context=context) |
| 1066 | if ans: |
| 1067 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1068 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1069 | # self - other is computed as self + other.copy_negate() |
| 1070 | return self.__add__(other.copy_negate(), context=context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1071 | |
| 1072 | def __rsub__(self, other, context=None): |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1073 | """Return other - self""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1074 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1075 | if other is NotImplemented: |
| 1076 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1077 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1078 | return other.__sub__(self, context=context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1079 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1080 | def __mul__(self, other, context=None): |
| 1081 | """Return self * other. |
| 1082 | |
| 1083 | (+-) INF * 0 (or its reverse) raise InvalidOperation. |
| 1084 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1085 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1086 | if other is NotImplemented: |
| 1087 | return other |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1088 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1089 | if context is None: |
| 1090 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1091 | |
Raymond Hettinger | d87ac8f | 2004-07-09 10:52:54 +0000 | [diff] [blame] | 1092 | resultsign = self._sign ^ other._sign |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1093 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1094 | if self._is_special or other._is_special: |
| 1095 | ans = self._check_nans(other, context) |
| 1096 | if ans: |
| 1097 | return ans |
| 1098 | |
| 1099 | if self._isinfinity(): |
| 1100 | if not other: |
| 1101 | return context._raise_error(InvalidOperation, '(+-)INF * 0') |
| 1102 | return Infsign[resultsign] |
| 1103 | |
| 1104 | if other._isinfinity(): |
| 1105 | if not self: |
| 1106 | return context._raise_error(InvalidOperation, '0 * (+-)INF') |
| 1107 | return Infsign[resultsign] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1108 | |
| 1109 | resultexp = self._exp + other._exp |
| 1110 | shouldround = context._rounding_decision == ALWAYS_ROUND |
| 1111 | |
| 1112 | # Special case for multiplying by zero |
| 1113 | if not self or not other: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1114 | ans = _dec_from_triple(resultsign, '0', resultexp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1115 | if shouldround: |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 1116 | # Fixing in case the exponent is out of bounds |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1117 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1118 | return ans |
| 1119 | |
| 1120 | # Special case for multiplying by power of 10 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1121 | if self._int == '1': |
| 1122 | ans = _dec_from_triple(resultsign, other._int, resultexp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1123 | if shouldround: |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1124 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1125 | return ans |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1126 | if other._int == '1': |
| 1127 | ans = _dec_from_triple(resultsign, self._int, resultexp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1128 | if shouldround: |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1129 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1130 | return ans |
| 1131 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1132 | op1 = _WorkRep(self) |
| 1133 | op2 = _WorkRep(other) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1134 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1135 | ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1136 | if shouldround: |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1137 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1138 | |
| 1139 | return ans |
| 1140 | __rmul__ = __mul__ |
| 1141 | |
| 1142 | def __div__(self, other, context=None): |
| 1143 | """Return self / other.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1144 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1145 | if other is NotImplemented: |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1146 | return NotImplemented |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1147 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1148 | if context is None: |
| 1149 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1150 | |
Raymond Hettinger | d87ac8f | 2004-07-09 10:52:54 +0000 | [diff] [blame] | 1151 | sign = self._sign ^ other._sign |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1152 | |
| 1153 | if self._is_special or other._is_special: |
| 1154 | ans = self._check_nans(other, context) |
| 1155 | if ans: |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1156 | return ans |
| 1157 | |
| 1158 | if self._isinfinity() and other._isinfinity(): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1159 | return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1160 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1161 | if self._isinfinity(): |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1162 | return Infsign[sign] |
| 1163 | |
| 1164 | if other._isinfinity(): |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1165 | context._raise_error(Clamped, 'Division by infinity') |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1166 | return _dec_from_triple(sign, '0', context.Etiny()) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1167 | |
| 1168 | # Special cases for zeroes |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1169 | if not other: |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1170 | if not self: |
| 1171 | return context._raise_error(DivisionUndefined, '0 / 0') |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1172 | return context._raise_error(DivisionByZero, 'x / 0', sign) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1173 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1174 | if not self: |
| 1175 | exp = self._exp - other._exp |
| 1176 | coeff = 0 |
| 1177 | else: |
| 1178 | # OK, so neither = 0, INF or NaN |
| 1179 | shift = len(other._int) - len(self._int) + context.prec + 1 |
| 1180 | exp = self._exp - other._exp - shift |
| 1181 | op1 = _WorkRep(self) |
| 1182 | op2 = _WorkRep(other) |
| 1183 | if shift >= 0: |
| 1184 | coeff, remainder = divmod(op1.int * 10**shift, op2.int) |
| 1185 | else: |
| 1186 | coeff, remainder = divmod(op1.int, op2.int * 10**-shift) |
| 1187 | if remainder: |
| 1188 | # result is not exact; adjust to ensure correct rounding |
| 1189 | if coeff % 5 == 0: |
| 1190 | coeff += 1 |
| 1191 | else: |
| 1192 | # result is exact; get as close to ideal exponent as possible |
| 1193 | ideal_exp = self._exp - other._exp |
| 1194 | while exp < ideal_exp and coeff % 10 == 0: |
| 1195 | coeff //= 10 |
| 1196 | exp += 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1197 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1198 | ans = _dec_from_triple(sign, str(coeff), exp) |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1199 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1200 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1201 | __truediv__ = __div__ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1202 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1203 | def _divide(self, other, context): |
| 1204 | """Return (self // other, self % other), to context.prec precision. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1205 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1206 | Assumes that neither self nor other is a NaN, that self is not |
| 1207 | infinite and that other is nonzero. |
| 1208 | """ |
| 1209 | sign = self._sign ^ other._sign |
| 1210 | if other._isinfinity(): |
| 1211 | ideal_exp = self._exp |
| 1212 | else: |
| 1213 | ideal_exp = min(self._exp, other._exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1214 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1215 | expdiff = self.adjusted() - other.adjusted() |
| 1216 | if not self or other._isinfinity() or expdiff <= -2: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1217 | return (_dec_from_triple(sign, '0', 0), |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1218 | self._rescale(ideal_exp, context.rounding)) |
| 1219 | if expdiff <= context.prec: |
| 1220 | op1 = _WorkRep(self) |
| 1221 | op2 = _WorkRep(other) |
| 1222 | if op1.exp >= op2.exp: |
| 1223 | op1.int *= 10**(op1.exp - op2.exp) |
| 1224 | else: |
| 1225 | op2.int *= 10**(op2.exp - op1.exp) |
| 1226 | q, r = divmod(op1.int, op2.int) |
| 1227 | if q < 10**context.prec: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1228 | return (_dec_from_triple(sign, str(q), 0), |
| 1229 | _dec_from_triple(self._sign, str(r), ideal_exp)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1230 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1231 | # Here the quotient is too large to be representable |
| 1232 | ans = context._raise_error(DivisionImpossible, |
| 1233 | 'quotient too large in //, % or divmod') |
| 1234 | return ans, ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1235 | |
| 1236 | def __rdiv__(self, other, context=None): |
| 1237 | """Swaps self/other and returns __div__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1238 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1239 | if other is NotImplemented: |
| 1240 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1241 | return other.__div__(self, context=context) |
| 1242 | __rtruediv__ = __rdiv__ |
| 1243 | |
| 1244 | def __divmod__(self, other, context=None): |
| 1245 | """ |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1246 | Return (self // other, self % other) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1247 | """ |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1248 | other = _convert_other(other) |
| 1249 | if other is NotImplemented: |
| 1250 | return other |
| 1251 | |
| 1252 | if context is None: |
| 1253 | context = getcontext() |
| 1254 | |
| 1255 | ans = self._check_nans(other, context) |
| 1256 | if ans: |
| 1257 | return (ans, ans) |
| 1258 | |
| 1259 | sign = self._sign ^ other._sign |
| 1260 | if self._isinfinity(): |
| 1261 | if other._isinfinity(): |
| 1262 | ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)') |
| 1263 | return ans, ans |
| 1264 | else: |
| 1265 | return (Infsign[sign], |
| 1266 | context._raise_error(InvalidOperation, 'INF % x')) |
| 1267 | |
| 1268 | if not other: |
| 1269 | if not self: |
| 1270 | ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)') |
| 1271 | return ans, ans |
| 1272 | else: |
| 1273 | return (context._raise_error(DivisionByZero, 'x // 0', sign), |
| 1274 | context._raise_error(InvalidOperation, 'x % 0')) |
| 1275 | |
| 1276 | quotient, remainder = self._divide(other, context) |
| 1277 | if context._rounding_decision == ALWAYS_ROUND: |
| 1278 | remainder = remainder._fix(context) |
| 1279 | return quotient, remainder |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1280 | |
| 1281 | def __rdivmod__(self, other, context=None): |
| 1282 | """Swaps self/other and returns __divmod__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1283 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1284 | if other is NotImplemented: |
| 1285 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1286 | return other.__divmod__(self, context=context) |
| 1287 | |
| 1288 | def __mod__(self, other, context=None): |
| 1289 | """ |
| 1290 | self % other |
| 1291 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1292 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1293 | if other is NotImplemented: |
| 1294 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1295 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1296 | if context is None: |
| 1297 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1298 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1299 | ans = self._check_nans(other, context) |
| 1300 | if ans: |
| 1301 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1302 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1303 | if self._isinfinity(): |
| 1304 | return context._raise_error(InvalidOperation, 'INF % x') |
| 1305 | elif not other: |
| 1306 | if self: |
| 1307 | return context._raise_error(InvalidOperation, 'x % 0') |
| 1308 | else: |
| 1309 | return context._raise_error(DivisionUndefined, '0 % 0') |
| 1310 | |
| 1311 | remainder = self._divide(other, context)[1] |
| 1312 | if context._rounding_decision == ALWAYS_ROUND: |
| 1313 | remainder = remainder._fix(context) |
| 1314 | return remainder |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1315 | |
| 1316 | def __rmod__(self, other, context=None): |
| 1317 | """Swaps self/other and returns __mod__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1318 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1319 | if other is NotImplemented: |
| 1320 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1321 | return other.__mod__(self, context=context) |
| 1322 | |
| 1323 | def remainder_near(self, other, context=None): |
| 1324 | """ |
| 1325 | Remainder nearest to 0- abs(remainder-near) <= other/2 |
| 1326 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1327 | if context is None: |
| 1328 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1329 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1330 | other = _convert_other(other, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1331 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1332 | ans = self._check_nans(other, context) |
| 1333 | if ans: |
| 1334 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1335 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1336 | # self == +/-infinity -> InvalidOperation |
| 1337 | if self._isinfinity(): |
| 1338 | return context._raise_error(InvalidOperation, |
| 1339 | 'remainder_near(infinity, x)') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1340 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1341 | # other == 0 -> either InvalidOperation or DivisionUndefined |
| 1342 | if not other: |
| 1343 | if self: |
| 1344 | return context._raise_error(InvalidOperation, |
| 1345 | 'remainder_near(x, 0)') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1346 | else: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1347 | return context._raise_error(DivisionUndefined, |
| 1348 | 'remainder_near(0, 0)') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1349 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1350 | # other = +/-infinity -> remainder = self |
| 1351 | if other._isinfinity(): |
| 1352 | ans = Decimal(self) |
| 1353 | return ans._fix(context) |
| 1354 | |
| 1355 | # self = 0 -> remainder = self, with ideal exponent |
| 1356 | ideal_exponent = min(self._exp, other._exp) |
| 1357 | if not self: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1358 | ans = _dec_from_triple(self._sign, '0', ideal_exponent) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1359 | return ans._fix(context) |
| 1360 | |
| 1361 | # catch most cases of large or small quotient |
| 1362 | expdiff = self.adjusted() - other.adjusted() |
| 1363 | if expdiff >= context.prec + 1: |
| 1364 | # expdiff >= prec+1 => abs(self/other) > 10**prec |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1365 | return context._raise_error(DivisionImpossible) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1366 | if expdiff <= -2: |
| 1367 | # expdiff <= -2 => abs(self/other) < 0.1 |
| 1368 | ans = self._rescale(ideal_exponent, context.rounding) |
| 1369 | return ans._fix(context) |
| 1370 | |
| 1371 | # adjust both arguments to have the same exponent, then divide |
| 1372 | op1 = _WorkRep(self) |
| 1373 | op2 = _WorkRep(other) |
| 1374 | if op1.exp >= op2.exp: |
| 1375 | op1.int *= 10**(op1.exp - op2.exp) |
| 1376 | else: |
| 1377 | op2.int *= 10**(op2.exp - op1.exp) |
| 1378 | q, r = divmod(op1.int, op2.int) |
| 1379 | # remainder is r*10**ideal_exponent; other is +/-op2.int * |
| 1380 | # 10**ideal_exponent. Apply correction to ensure that |
| 1381 | # abs(remainder) <= abs(other)/2 |
| 1382 | if 2*r + (q&1) > op2.int: |
| 1383 | r -= op2.int |
| 1384 | q += 1 |
| 1385 | |
| 1386 | if q >= 10**context.prec: |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1387 | return context._raise_error(DivisionImpossible) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1388 | |
| 1389 | # result has same sign as self unless r is negative |
| 1390 | sign = self._sign |
| 1391 | if r < 0: |
| 1392 | sign = 1-sign |
| 1393 | r = -r |
| 1394 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1395 | ans = _dec_from_triple(sign, str(r), ideal_exponent) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1396 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1397 | |
| 1398 | def __floordiv__(self, other, context=None): |
| 1399 | """self // other""" |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1400 | other = _convert_other(other) |
| 1401 | if other is NotImplemented: |
| 1402 | return other |
| 1403 | |
| 1404 | if context is None: |
| 1405 | context = getcontext() |
| 1406 | |
| 1407 | ans = self._check_nans(other, context) |
| 1408 | if ans: |
| 1409 | return ans |
| 1410 | |
| 1411 | if self._isinfinity(): |
| 1412 | if other._isinfinity(): |
| 1413 | return context._raise_error(InvalidOperation, 'INF // INF') |
| 1414 | else: |
| 1415 | return Infsign[self._sign ^ other._sign] |
| 1416 | |
| 1417 | if not other: |
| 1418 | if self: |
| 1419 | return context._raise_error(DivisionByZero, 'x // 0', |
| 1420 | self._sign ^ other._sign) |
| 1421 | else: |
| 1422 | return context._raise_error(DivisionUndefined, '0 // 0') |
| 1423 | |
| 1424 | return self._divide(other, context)[0] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1425 | |
| 1426 | def __rfloordiv__(self, other, context=None): |
| 1427 | """Swaps self/other and returns __floordiv__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1428 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1429 | if other is NotImplemented: |
| 1430 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1431 | return other.__floordiv__(self, context=context) |
| 1432 | |
| 1433 | def __float__(self): |
| 1434 | """Float representation.""" |
| 1435 | return float(str(self)) |
| 1436 | |
| 1437 | def __int__(self): |
Brett Cannon | 46b0802 | 2005-03-01 03:12:26 +0000 | [diff] [blame] | 1438 | """Converts self to an int, truncating if necessary.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1439 | if self._is_special: |
| 1440 | if self._isnan(): |
| 1441 | context = getcontext() |
| 1442 | return context._raise_error(InvalidContext) |
| 1443 | elif self._isinfinity(): |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 1444 | raise OverflowError("Cannot convert infinity to long") |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1445 | s = (-1)**self._sign |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1446 | if self._exp >= 0: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1447 | return s*int(self._int)*10**self._exp |
Raymond Hettinger | 605ed02 | 2004-11-24 07:28:48 +0000 | [diff] [blame] | 1448 | else: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1449 | return s*int(self._int[:self._exp] or '0') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1450 | |
| 1451 | def __long__(self): |
| 1452 | """Converts to a long. |
| 1453 | |
| 1454 | Equivalent to long(int(self)) |
| 1455 | """ |
| 1456 | return long(self.__int__()) |
| 1457 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1458 | def _fix_nan(self, context): |
| 1459 | """Decapitate the payload of a NaN to fit the context""" |
| 1460 | payload = self._int |
| 1461 | |
| 1462 | # maximum length of payload is precision if _clamp=0, |
| 1463 | # precision-1 if _clamp=1. |
| 1464 | max_payload_len = context.prec - context._clamp |
| 1465 | if len(payload) > max_payload_len: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1466 | payload = payload[len(payload)-max_payload_len:].lstrip('0') |
| 1467 | return _dec_from_triple(self._sign, payload, self._exp, True) |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 1468 | return Decimal(self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1469 | |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1470 | def _fix(self, context): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1471 | """Round if it is necessary to keep self within prec precision. |
| 1472 | |
| 1473 | Rounds and fixes the exponent. Does not raise on a sNaN. |
| 1474 | |
| 1475 | Arguments: |
| 1476 | self - Decimal instance |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1477 | context - context used. |
| 1478 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1479 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1480 | if context is None: |
| 1481 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1482 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1483 | if self._is_special: |
| 1484 | if self._isnan(): |
| 1485 | # decapitate payload if necessary |
| 1486 | return self._fix_nan(context) |
| 1487 | else: |
| 1488 | # self is +/-Infinity; return unaltered |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 1489 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1490 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1491 | # if self is zero then exponent should be between Etiny and |
| 1492 | # Emax if _clamp==0, and between Etiny and Etop if _clamp==1. |
| 1493 | Etiny = context.Etiny() |
| 1494 | Etop = context.Etop() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1495 | if not self: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1496 | exp_max = [context.Emax, Etop][context._clamp] |
| 1497 | new_exp = min(max(self._exp, Etiny), exp_max) |
| 1498 | if new_exp != self._exp: |
| 1499 | context._raise_error(Clamped) |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1500 | return _dec_from_triple(self._sign, '0', new_exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1501 | else: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 1502 | return Decimal(self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1503 | |
| 1504 | # exp_min is the smallest allowable exponent of the result, |
| 1505 | # equal to max(self.adjusted()-context.prec+1, Etiny) |
| 1506 | exp_min = len(self._int) + self._exp - context.prec |
| 1507 | if exp_min > Etop: |
| 1508 | # overflow: exp_min > Etop iff self.adjusted() > Emax |
| 1509 | context._raise_error(Inexact) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1510 | context._raise_error(Rounded) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1511 | return context._raise_error(Overflow, 'above Emax', self._sign) |
| 1512 | self_is_subnormal = exp_min < Etiny |
| 1513 | if self_is_subnormal: |
| 1514 | context._raise_error(Subnormal) |
| 1515 | exp_min = Etiny |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1516 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1517 | # round if self has too many digits |
| 1518 | if self._exp < exp_min: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1519 | context._raise_error(Rounded) |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1520 | digits = len(self._int) + self._exp - exp_min |
| 1521 | if digits < 0: |
| 1522 | self = _dec_from_triple(self._sign, '1', exp_min-1) |
| 1523 | digits = 0 |
| 1524 | this_function = getattr(self, self._pick_rounding_function[context.rounding]) |
| 1525 | changed = this_function(digits) |
| 1526 | coeff = self._int[:digits] or '0' |
| 1527 | if changed == 1: |
| 1528 | coeff = str(int(coeff)+1) |
| 1529 | ans = _dec_from_triple(self._sign, coeff, exp_min) |
| 1530 | |
| 1531 | if changed: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1532 | context._raise_error(Inexact) |
| 1533 | if self_is_subnormal: |
| 1534 | context._raise_error(Underflow) |
| 1535 | if not ans: |
| 1536 | # raise Clamped on underflow to 0 |
| 1537 | context._raise_error(Clamped) |
| 1538 | elif len(ans._int) == context.prec+1: |
| 1539 | # we get here only if rescaling rounds the |
| 1540 | # cofficient up to exactly 10**context.prec |
| 1541 | if ans._exp < Etop: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1542 | ans = _dec_from_triple(ans._sign, |
| 1543 | ans._int[:-1], ans._exp+1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1544 | else: |
| 1545 | # Inexact and Rounded have already been raised |
| 1546 | ans = context._raise_error(Overflow, 'above Emax', |
| 1547 | self._sign) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1548 | return ans |
| 1549 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1550 | # fold down if _clamp == 1 and self has too few digits |
| 1551 | if context._clamp == 1 and self._exp > Etop: |
| 1552 | context._raise_error(Clamped) |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1553 | self_padded = self._int + '0'*(self._exp - Etop) |
| 1554 | return _dec_from_triple(self._sign, self_padded, Etop) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1555 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1556 | # here self was representable to begin with; return unchanged |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 1557 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1558 | |
| 1559 | _pick_rounding_function = {} |
| 1560 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1561 | # for each of the rounding functions below: |
| 1562 | # self is a finite, nonzero Decimal |
| 1563 | # prec is an integer satisfying 0 <= prec < len(self._int) |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1564 | # |
| 1565 | # each function returns either -1, 0, or 1, as follows: |
| 1566 | # 1 indicates that self should be rounded up (away from zero) |
| 1567 | # 0 indicates that self should be truncated, and that all the |
| 1568 | # digits to be truncated are zeros (so the value is unchanged) |
| 1569 | # -1 indicates that there are nonzero digits to be truncated |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1570 | |
| 1571 | def _round_down(self, prec): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1572 | """Also known as round-towards-0, truncate.""" |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1573 | if _all_zeros(self._int, prec): |
| 1574 | return 0 |
| 1575 | else: |
| 1576 | return -1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1577 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1578 | def _round_up(self, prec): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1579 | """Rounds away from 0.""" |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1580 | return -self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1581 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1582 | def _round_half_up(self, prec): |
| 1583 | """Rounds 5 up (away from 0)""" |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1584 | if self._int[prec] in '56789': |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1585 | return 1 |
| 1586 | elif _all_zeros(self._int, prec): |
| 1587 | return 0 |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1588 | else: |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1589 | return -1 |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1590 | |
| 1591 | def _round_half_down(self, prec): |
| 1592 | """Round 5 down""" |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1593 | if _exact_half(self._int, prec): |
| 1594 | return -1 |
| 1595 | else: |
| 1596 | return self._round_half_up(prec) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1597 | |
| 1598 | def _round_half_even(self, prec): |
| 1599 | """Round 5 to even, rest to nearest.""" |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1600 | if _exact_half(self._int, prec) and \ |
| 1601 | (prec == 0 or self._int[prec-1] in '02468'): |
| 1602 | return -1 |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1603 | else: |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1604 | return self._round_half_up(prec) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1605 | |
| 1606 | def _round_ceiling(self, prec): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1607 | """Rounds up (not away from 0 if negative.)""" |
| 1608 | if self._sign: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1609 | return self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1610 | else: |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1611 | return -self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1612 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1613 | def _round_floor(self, prec): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1614 | """Rounds down (not towards 0 if negative)""" |
| 1615 | if not self._sign: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1616 | return self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1617 | else: |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1618 | return -self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1619 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1620 | def _round_05up(self, prec): |
| 1621 | """Round down unless digit prec-1 is 0 or 5.""" |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1622 | if prec and self._int[prec-1] not in '05': |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1623 | return self._round_down(prec) |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1624 | else: |
| 1625 | return -self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1626 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1627 | def fma(self, other, third, context=None): |
| 1628 | """Fused multiply-add. |
| 1629 | |
| 1630 | Returns self*other+third with no rounding of the intermediate |
| 1631 | product self*other. |
| 1632 | |
| 1633 | self and other are multiplied together, with no rounding of |
| 1634 | the result. The third operand is then added to the result, |
| 1635 | and a single final rounding is performed. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1636 | """ |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1637 | |
| 1638 | other = _convert_other(other, raiseit=True) |
Facundo Batista | 58f6f2e | 2007-12-04 16:31:53 +0000 | [diff] [blame] | 1639 | |
| 1640 | # compute product; raise InvalidOperation if either operand is |
| 1641 | # a signaling NaN or if the product is zero times infinity. |
| 1642 | if self._is_special or other._is_special: |
| 1643 | if context is None: |
| 1644 | context = getcontext() |
| 1645 | if self._exp == 'N': |
| 1646 | return context._raise_error(InvalidOperation, 'sNaN', |
| 1647 | 1, self) |
| 1648 | if other._exp == 'N': |
| 1649 | return context._raise_error(InvalidOperation, 'sNaN', |
| 1650 | 1, other) |
| 1651 | if self._exp == 'n': |
| 1652 | product = self |
| 1653 | elif other._exp == 'n': |
| 1654 | product = other |
| 1655 | elif self._exp == 'F': |
| 1656 | if not other: |
| 1657 | return context._raise_error(InvalidOperation, |
| 1658 | 'INF * 0 in fma') |
| 1659 | product = Infsign[self._sign ^ other._sign] |
| 1660 | elif other._exp == 'F': |
| 1661 | if not self: |
| 1662 | return context._raise_error(InvalidOperation, |
| 1663 | '0 * INF in fma') |
| 1664 | product = Infsign[self._sign ^ other._sign] |
| 1665 | else: |
| 1666 | product = _dec_from_triple(self._sign ^ other._sign, |
| 1667 | str(int(self._int) * int(other._int)), |
| 1668 | self._exp + other._exp) |
| 1669 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1670 | third = _convert_other(third, raiseit=True) |
Facundo Batista | 58f6f2e | 2007-12-04 16:31:53 +0000 | [diff] [blame] | 1671 | return product.__add__(third, context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1672 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1673 | def _power_modulo(self, other, modulo, context=None): |
| 1674 | """Three argument version of __pow__""" |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1675 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1676 | # if can't convert other and modulo to Decimal, raise |
| 1677 | # TypeError; there's no point returning NotImplemented (no |
| 1678 | # equivalent of __rpow__ for three argument pow) |
| 1679 | other = _convert_other(other, raiseit=True) |
| 1680 | modulo = _convert_other(modulo, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1681 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1682 | if context is None: |
| 1683 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1684 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1685 | # deal with NaNs: if there are any sNaNs then first one wins, |
| 1686 | # (i.e. behaviour for NaNs is identical to that of fma) |
| 1687 | self_is_nan = self._isnan() |
| 1688 | other_is_nan = other._isnan() |
| 1689 | modulo_is_nan = modulo._isnan() |
| 1690 | if self_is_nan or other_is_nan or modulo_is_nan: |
| 1691 | if self_is_nan == 2: |
| 1692 | return context._raise_error(InvalidOperation, 'sNaN', |
| 1693 | 1, self) |
| 1694 | if other_is_nan == 2: |
| 1695 | return context._raise_error(InvalidOperation, 'sNaN', |
| 1696 | 1, other) |
| 1697 | if modulo_is_nan == 2: |
| 1698 | return context._raise_error(InvalidOperation, 'sNaN', |
| 1699 | 1, modulo) |
| 1700 | if self_is_nan: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 1701 | return self._fix_nan(context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1702 | if other_is_nan: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 1703 | return other._fix_nan(context) |
| 1704 | return modulo._fix_nan(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1705 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1706 | # check inputs: we apply same restrictions as Python's pow() |
| 1707 | if not (self._isinteger() and |
| 1708 | other._isinteger() and |
| 1709 | modulo._isinteger()): |
| 1710 | return context._raise_error(InvalidOperation, |
| 1711 | 'pow() 3rd argument not allowed ' |
| 1712 | 'unless all arguments are integers') |
| 1713 | if other < 0: |
| 1714 | return context._raise_error(InvalidOperation, |
| 1715 | 'pow() 2nd argument cannot be ' |
| 1716 | 'negative when 3rd argument specified') |
| 1717 | if not modulo: |
| 1718 | return context._raise_error(InvalidOperation, |
| 1719 | 'pow() 3rd argument cannot be 0') |
| 1720 | |
| 1721 | # additional restriction for decimal: the modulus must be less |
| 1722 | # than 10**prec in absolute value |
| 1723 | if modulo.adjusted() >= context.prec: |
| 1724 | return context._raise_error(InvalidOperation, |
| 1725 | 'insufficient precision: pow() 3rd ' |
| 1726 | 'argument must not have more than ' |
| 1727 | 'precision digits') |
| 1728 | |
| 1729 | # define 0**0 == NaN, for consistency with two-argument pow |
| 1730 | # (even though it hurts!) |
| 1731 | if not other and not self: |
| 1732 | return context._raise_error(InvalidOperation, |
| 1733 | 'at least one of pow() 1st argument ' |
| 1734 | 'and 2nd argument must be nonzero ;' |
| 1735 | '0**0 is not defined') |
| 1736 | |
| 1737 | # compute sign of result |
| 1738 | if other._iseven(): |
| 1739 | sign = 0 |
| 1740 | else: |
| 1741 | sign = self._sign |
| 1742 | |
| 1743 | # convert modulo to a Python integer, and self and other to |
| 1744 | # Decimal integers (i.e. force their exponents to be >= 0) |
| 1745 | modulo = abs(int(modulo)) |
| 1746 | base = _WorkRep(self.to_integral_value()) |
| 1747 | exponent = _WorkRep(other.to_integral_value()) |
| 1748 | |
| 1749 | # compute result using integer pow() |
| 1750 | base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo |
| 1751 | for i in xrange(exponent.exp): |
| 1752 | base = pow(base, 10, modulo) |
| 1753 | base = pow(base, exponent.int, modulo) |
| 1754 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1755 | return _dec_from_triple(sign, str(base), 0) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1756 | |
| 1757 | def _power_exact(self, other, p): |
| 1758 | """Attempt to compute self**other exactly. |
| 1759 | |
| 1760 | Given Decimals self and other and an integer p, attempt to |
| 1761 | compute an exact result for the power self**other, with p |
| 1762 | digits of precision. Return None if self**other is not |
| 1763 | exactly representable in p digits. |
| 1764 | |
| 1765 | Assumes that elimination of special cases has already been |
| 1766 | performed: self and other must both be nonspecial; self must |
| 1767 | be positive and not numerically equal to 1; other must be |
| 1768 | nonzero. For efficiency, other._exp should not be too large, |
| 1769 | so that 10**abs(other._exp) is a feasible calculation.""" |
| 1770 | |
| 1771 | # In the comments below, we write x for the value of self and |
| 1772 | # y for the value of other. Write x = xc*10**xe and y = |
| 1773 | # yc*10**ye. |
| 1774 | |
| 1775 | # The main purpose of this method is to identify the *failure* |
| 1776 | # of x**y to be exactly representable with as little effort as |
| 1777 | # possible. So we look for cheap and easy tests that |
| 1778 | # eliminate the possibility of x**y being exact. Only if all |
| 1779 | # these tests are passed do we go on to actually compute x**y. |
| 1780 | |
| 1781 | # Here's the main idea. First normalize both x and y. We |
| 1782 | # express y as a rational m/n, with m and n relatively prime |
| 1783 | # and n>0. Then for x**y to be exactly representable (at |
| 1784 | # *any* precision), xc must be the nth power of a positive |
| 1785 | # integer and xe must be divisible by n. If m is negative |
| 1786 | # then additionally xc must be a power of either 2 or 5, hence |
| 1787 | # a power of 2**n or 5**n. |
| 1788 | # |
| 1789 | # There's a limit to how small |y| can be: if y=m/n as above |
| 1790 | # then: |
| 1791 | # |
| 1792 | # (1) if xc != 1 then for the result to be representable we |
| 1793 | # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So |
| 1794 | # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <= |
| 1795 | # 2**(1/|y|), hence xc**|y| < 2 and the result is not |
| 1796 | # representable. |
| 1797 | # |
| 1798 | # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if |
| 1799 | # |y| < 1/|xe| then the result is not representable. |
| 1800 | # |
| 1801 | # Note that since x is not equal to 1, at least one of (1) and |
| 1802 | # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) < |
| 1803 | # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye. |
| 1804 | # |
| 1805 | # There's also a limit to how large y can be, at least if it's |
| 1806 | # positive: the normalized result will have coefficient xc**y, |
| 1807 | # so if it's representable then xc**y < 10**p, and y < |
| 1808 | # p/log10(xc). Hence if y*log10(xc) >= p then the result is |
| 1809 | # not exactly representable. |
| 1810 | |
| 1811 | # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye, |
| 1812 | # so |y| < 1/xe and the result is not representable. |
| 1813 | # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y| |
| 1814 | # < 1/nbits(xc). |
| 1815 | |
| 1816 | x = _WorkRep(self) |
| 1817 | xc, xe = x.int, x.exp |
| 1818 | while xc % 10 == 0: |
| 1819 | xc //= 10 |
| 1820 | xe += 1 |
| 1821 | |
| 1822 | y = _WorkRep(other) |
| 1823 | yc, ye = y.int, y.exp |
| 1824 | while yc % 10 == 0: |
| 1825 | yc //= 10 |
| 1826 | ye += 1 |
| 1827 | |
| 1828 | # case where xc == 1: result is 10**(xe*y), with xe*y |
| 1829 | # required to be an integer |
| 1830 | if xc == 1: |
| 1831 | if ye >= 0: |
| 1832 | exponent = xe*yc*10**ye |
| 1833 | else: |
| 1834 | exponent, remainder = divmod(xe*yc, 10**-ye) |
| 1835 | if remainder: |
| 1836 | return None |
| 1837 | if y.sign == 1: |
| 1838 | exponent = -exponent |
| 1839 | # if other is a nonnegative integer, use ideal exponent |
| 1840 | if other._isinteger() and other._sign == 0: |
| 1841 | ideal_exponent = self._exp*int(other) |
| 1842 | zeros = min(exponent-ideal_exponent, p-1) |
| 1843 | else: |
| 1844 | zeros = 0 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1845 | return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1846 | |
| 1847 | # case where y is negative: xc must be either a power |
| 1848 | # of 2 or a power of 5. |
| 1849 | if y.sign == 1: |
| 1850 | last_digit = xc % 10 |
| 1851 | if last_digit in (2,4,6,8): |
| 1852 | # quick test for power of 2 |
| 1853 | if xc & -xc != xc: |
| 1854 | return None |
| 1855 | # now xc is a power of 2; e is its exponent |
| 1856 | e = _nbits(xc)-1 |
| 1857 | # find e*y and xe*y; both must be integers |
| 1858 | if ye >= 0: |
| 1859 | y_as_int = yc*10**ye |
| 1860 | e = e*y_as_int |
| 1861 | xe = xe*y_as_int |
| 1862 | else: |
| 1863 | ten_pow = 10**-ye |
| 1864 | e, remainder = divmod(e*yc, ten_pow) |
| 1865 | if remainder: |
| 1866 | return None |
| 1867 | xe, remainder = divmod(xe*yc, ten_pow) |
| 1868 | if remainder: |
| 1869 | return None |
| 1870 | |
| 1871 | if e*65 >= p*93: # 93/65 > log(10)/log(5) |
| 1872 | return None |
| 1873 | xc = 5**e |
| 1874 | |
| 1875 | elif last_digit == 5: |
| 1876 | # e >= log_5(xc) if xc is a power of 5; we have |
| 1877 | # equality all the way up to xc=5**2658 |
| 1878 | e = _nbits(xc)*28//65 |
| 1879 | xc, remainder = divmod(5**e, xc) |
| 1880 | if remainder: |
| 1881 | return None |
| 1882 | while xc % 5 == 0: |
| 1883 | xc //= 5 |
| 1884 | e -= 1 |
| 1885 | if ye >= 0: |
| 1886 | y_as_integer = yc*10**ye |
| 1887 | e = e*y_as_integer |
| 1888 | xe = xe*y_as_integer |
| 1889 | else: |
| 1890 | ten_pow = 10**-ye |
| 1891 | e, remainder = divmod(e*yc, ten_pow) |
| 1892 | if remainder: |
| 1893 | return None |
| 1894 | xe, remainder = divmod(xe*yc, ten_pow) |
| 1895 | if remainder: |
| 1896 | return None |
| 1897 | if e*3 >= p*10: # 10/3 > log(10)/log(2) |
| 1898 | return None |
| 1899 | xc = 2**e |
| 1900 | else: |
| 1901 | return None |
| 1902 | |
| 1903 | if xc >= 10**p: |
| 1904 | return None |
| 1905 | xe = -e-xe |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1906 | return _dec_from_triple(0, str(xc), xe) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1907 | |
| 1908 | # now y is positive; find m and n such that y = m/n |
| 1909 | if ye >= 0: |
| 1910 | m, n = yc*10**ye, 1 |
| 1911 | else: |
| 1912 | if xe != 0 and len(str(abs(yc*xe))) <= -ye: |
| 1913 | return None |
| 1914 | xc_bits = _nbits(xc) |
| 1915 | if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye: |
| 1916 | return None |
| 1917 | m, n = yc, 10**(-ye) |
| 1918 | while m % 2 == n % 2 == 0: |
| 1919 | m //= 2 |
| 1920 | n //= 2 |
| 1921 | while m % 5 == n % 5 == 0: |
| 1922 | m //= 5 |
| 1923 | n //= 5 |
| 1924 | |
| 1925 | # compute nth root of xc*10**xe |
| 1926 | if n > 1: |
| 1927 | # if 1 < xc < 2**n then xc isn't an nth power |
| 1928 | if xc != 1 and xc_bits <= n: |
| 1929 | return None |
| 1930 | |
| 1931 | xe, rem = divmod(xe, n) |
| 1932 | if rem != 0: |
| 1933 | return None |
| 1934 | |
| 1935 | # compute nth root of xc using Newton's method |
| 1936 | a = 1L << -(-_nbits(xc)//n) # initial estimate |
| 1937 | while True: |
| 1938 | q, r = divmod(xc, a**(n-1)) |
| 1939 | if a <= q: |
| 1940 | break |
| 1941 | else: |
| 1942 | a = (a*(n-1) + q)//n |
| 1943 | if not (a == q and r == 0): |
| 1944 | return None |
| 1945 | xc = a |
| 1946 | |
| 1947 | # now xc*10**xe is the nth root of the original xc*10**xe |
| 1948 | # compute mth power of xc*10**xe |
| 1949 | |
| 1950 | # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m > |
| 1951 | # 10**p and the result is not representable. |
| 1952 | if xc > 1 and m > p*100//_log10_lb(xc): |
| 1953 | return None |
| 1954 | xc = xc**m |
| 1955 | xe *= m |
| 1956 | if xc > 10**p: |
| 1957 | return None |
| 1958 | |
| 1959 | # by this point the result *is* exactly representable |
| 1960 | # adjust the exponent to get as close as possible to the ideal |
| 1961 | # exponent, if necessary |
| 1962 | str_xc = str(xc) |
| 1963 | if other._isinteger() and other._sign == 0: |
| 1964 | ideal_exponent = self._exp*int(other) |
| 1965 | zeros = min(xe-ideal_exponent, p-len(str_xc)) |
| 1966 | else: |
| 1967 | zeros = 0 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1968 | return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1969 | |
| 1970 | def __pow__(self, other, modulo=None, context=None): |
| 1971 | """Return self ** other [ % modulo]. |
| 1972 | |
| 1973 | With two arguments, compute self**other. |
| 1974 | |
| 1975 | With three arguments, compute (self**other) % modulo. For the |
| 1976 | three argument form, the following restrictions on the |
| 1977 | arguments hold: |
| 1978 | |
| 1979 | - all three arguments must be integral |
| 1980 | - other must be nonnegative |
| 1981 | - either self or other (or both) must be nonzero |
| 1982 | - modulo must be nonzero and must have at most p digits, |
| 1983 | where p is the context precision. |
| 1984 | |
| 1985 | If any of these restrictions is violated the InvalidOperation |
| 1986 | flag is raised. |
| 1987 | |
| 1988 | The result of pow(self, other, modulo) is identical to the |
| 1989 | result that would be obtained by computing (self**other) % |
| 1990 | modulo with unbounded precision, but is computed more |
| 1991 | efficiently. It is always exact. |
| 1992 | """ |
| 1993 | |
| 1994 | if modulo is not None: |
| 1995 | return self._power_modulo(other, modulo, context) |
| 1996 | |
| 1997 | other = _convert_other(other) |
| 1998 | if other is NotImplemented: |
| 1999 | return other |
| 2000 | |
| 2001 | if context is None: |
| 2002 | context = getcontext() |
| 2003 | |
| 2004 | # either argument is a NaN => result is NaN |
| 2005 | ans = self._check_nans(other, context) |
| 2006 | if ans: |
| 2007 | return ans |
| 2008 | |
| 2009 | # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity) |
| 2010 | if not other: |
| 2011 | if not self: |
| 2012 | return context._raise_error(InvalidOperation, '0 ** 0') |
| 2013 | else: |
| 2014 | return Dec_p1 |
| 2015 | |
| 2016 | # result has sign 1 iff self._sign is 1 and other is an odd integer |
| 2017 | result_sign = 0 |
| 2018 | if self._sign == 1: |
| 2019 | if other._isinteger(): |
| 2020 | if not other._iseven(): |
| 2021 | result_sign = 1 |
| 2022 | else: |
| 2023 | # -ve**noninteger = NaN |
| 2024 | # (-0)**noninteger = 0**noninteger |
| 2025 | if self: |
| 2026 | return context._raise_error(InvalidOperation, |
| 2027 | 'x ** y with x negative and y not an integer') |
| 2028 | # negate self, without doing any unwanted rounding |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2029 | self = self.copy_negate() |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2030 | |
| 2031 | # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity |
| 2032 | if not self: |
| 2033 | if other._sign == 0: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2034 | return _dec_from_triple(result_sign, '0', 0) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2035 | else: |
| 2036 | return Infsign[result_sign] |
| 2037 | |
| 2038 | # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2039 | if self._isinfinity(): |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2040 | if other._sign == 0: |
| 2041 | return Infsign[result_sign] |
| 2042 | else: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2043 | return _dec_from_triple(result_sign, '0', 0) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2044 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2045 | # 1**other = 1, but the choice of exponent and the flags |
| 2046 | # depend on the exponent of self, and on whether other is a |
| 2047 | # positive integer, a negative integer, or neither |
| 2048 | if self == Dec_p1: |
| 2049 | if other._isinteger(): |
| 2050 | # exp = max(self._exp*max(int(other), 0), |
| 2051 | # 1-context.prec) but evaluating int(other) directly |
| 2052 | # is dangerous until we know other is small (other |
| 2053 | # could be 1e999999999) |
| 2054 | if other._sign == 1: |
| 2055 | multiplier = 0 |
| 2056 | elif other > context.prec: |
| 2057 | multiplier = context.prec |
| 2058 | else: |
| 2059 | multiplier = int(other) |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 2060 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2061 | exp = self._exp * multiplier |
| 2062 | if exp < 1-context.prec: |
| 2063 | exp = 1-context.prec |
| 2064 | context._raise_error(Rounded) |
| 2065 | else: |
| 2066 | context._raise_error(Inexact) |
| 2067 | context._raise_error(Rounded) |
| 2068 | exp = 1-context.prec |
| 2069 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2070 | return _dec_from_triple(result_sign, '1'+'0'*-exp, exp) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2071 | |
| 2072 | # compute adjusted exponent of self |
| 2073 | self_adj = self.adjusted() |
| 2074 | |
| 2075 | # self ** infinity is infinity if self > 1, 0 if self < 1 |
| 2076 | # self ** -infinity is infinity if self < 1, 0 if self > 1 |
| 2077 | if other._isinfinity(): |
| 2078 | if (other._sign == 0) == (self_adj < 0): |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2079 | return _dec_from_triple(result_sign, '0', 0) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2080 | else: |
| 2081 | return Infsign[result_sign] |
| 2082 | |
| 2083 | # from here on, the result always goes through the call |
| 2084 | # to _fix at the end of this function. |
| 2085 | ans = None |
| 2086 | |
| 2087 | # crude test to catch cases of extreme overflow/underflow. If |
| 2088 | # log10(self)*other >= 10**bound and bound >= len(str(Emax)) |
| 2089 | # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence |
| 2090 | # self**other >= 10**(Emax+1), so overflow occurs. The test |
| 2091 | # for underflow is similar. |
| 2092 | bound = self._log10_exp_bound() + other.adjusted() |
| 2093 | if (self_adj >= 0) == (other._sign == 0): |
| 2094 | # self > 1 and other +ve, or self < 1 and other -ve |
| 2095 | # possibility of overflow |
| 2096 | if bound >= len(str(context.Emax)): |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2097 | ans = _dec_from_triple(result_sign, '1', context.Emax+1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2098 | else: |
| 2099 | # self > 1 and other -ve, or self < 1 and other +ve |
| 2100 | # possibility of underflow to 0 |
| 2101 | Etiny = context.Etiny() |
| 2102 | if bound >= len(str(-Etiny)): |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2103 | ans = _dec_from_triple(result_sign, '1', Etiny-1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2104 | |
| 2105 | # try for an exact result with precision +1 |
| 2106 | if ans is None: |
| 2107 | ans = self._power_exact(other, context.prec + 1) |
| 2108 | if ans is not None and result_sign == 1: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2109 | ans = _dec_from_triple(1, ans._int, ans._exp) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2110 | |
| 2111 | # usual case: inexact result, x**y computed directly as exp(y*log(x)) |
| 2112 | if ans is None: |
| 2113 | p = context.prec |
| 2114 | x = _WorkRep(self) |
| 2115 | xc, xe = x.int, x.exp |
| 2116 | y = _WorkRep(other) |
| 2117 | yc, ye = y.int, y.exp |
| 2118 | if y.sign == 1: |
| 2119 | yc = -yc |
| 2120 | |
| 2121 | # compute correctly rounded result: start with precision +3, |
| 2122 | # then increase precision until result is unambiguously roundable |
| 2123 | extra = 3 |
| 2124 | while True: |
| 2125 | coeff, exp = _dpower(xc, xe, yc, ye, p+extra) |
| 2126 | if coeff % (5*10**(len(str(coeff))-p-1)): |
| 2127 | break |
| 2128 | extra += 3 |
| 2129 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2130 | ans = _dec_from_triple(result_sign, str(coeff), exp) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2131 | |
| 2132 | # the specification says that for non-integer other we need to |
| 2133 | # raise Inexact, even when the result is actually exact. In |
| 2134 | # the same way, we need to raise Underflow here if the result |
| 2135 | # is subnormal. (The call to _fix will take care of raising |
| 2136 | # Rounded and Subnormal, as usual.) |
| 2137 | if not other._isinteger(): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2138 | context._raise_error(Inexact) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2139 | # pad with zeros up to length context.prec+1 if necessary |
| 2140 | if len(ans._int) <= context.prec: |
| 2141 | expdiff = context.prec+1 - len(ans._int) |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2142 | ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff, |
| 2143 | ans._exp-expdiff) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2144 | if ans.adjusted() < context.Emin: |
| 2145 | context._raise_error(Underflow) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2146 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2147 | # unlike exp, ln and log10, the power function respects the |
| 2148 | # rounding mode; no need to use ROUND_HALF_EVEN here |
| 2149 | ans = ans._fix(context) |
| 2150 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2151 | |
| 2152 | def __rpow__(self, other, context=None): |
| 2153 | """Swaps self/other and returns __pow__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2154 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 2155 | if other is NotImplemented: |
| 2156 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2157 | return other.__pow__(self, context=context) |
| 2158 | |
| 2159 | def normalize(self, context=None): |
| 2160 | """Normalize- strip trailing 0s, change anything equal to 0 to 0e0""" |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2161 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2162 | if context is None: |
| 2163 | context = getcontext() |
| 2164 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2165 | if self._is_special: |
| 2166 | ans = self._check_nans(context=context) |
| 2167 | if ans: |
| 2168 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2169 | |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 2170 | dup = self._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2171 | if dup._isinfinity(): |
| 2172 | return dup |
| 2173 | |
| 2174 | if not dup: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2175 | return _dec_from_triple(dup._sign, '0', 0) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2176 | exp_max = [context.Emax, context.Etop()][context._clamp] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2177 | end = len(dup._int) |
| 2178 | exp = dup._exp |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2179 | while dup._int[end-1] == '0' and exp < exp_max: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2180 | exp += 1 |
| 2181 | end -= 1 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2182 | return _dec_from_triple(dup._sign, dup._int[:end], exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2183 | |
Facundo Batista | bd2fe83 | 2007-09-13 18:42:09 +0000 | [diff] [blame] | 2184 | def quantize(self, exp, rounding=None, context=None, watchexp=True): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2185 | """Quantize self so its exponent is the same as that of exp. |
| 2186 | |
| 2187 | Similar to self._rescale(exp._exp) but with error checking. |
| 2188 | """ |
Facundo Batista | bd2fe83 | 2007-09-13 18:42:09 +0000 | [diff] [blame] | 2189 | exp = _convert_other(exp, raiseit=True) |
| 2190 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2191 | if context is None: |
| 2192 | context = getcontext() |
| 2193 | if rounding is None: |
| 2194 | rounding = context.rounding |
| 2195 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2196 | if self._is_special or exp._is_special: |
| 2197 | ans = self._check_nans(exp, context) |
| 2198 | if ans: |
| 2199 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2200 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2201 | if exp._isinfinity() or self._isinfinity(): |
| 2202 | if exp._isinfinity() and self._isinfinity(): |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2203 | return Decimal(self) # if both are inf, it is OK |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2204 | return context._raise_error(InvalidOperation, |
| 2205 | 'quantize with one INF') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2206 | |
Facundo Batista | bd2fe83 | 2007-09-13 18:42:09 +0000 | [diff] [blame] | 2207 | # if we're not watching exponents, do a simple rescale |
| 2208 | if not watchexp: |
| 2209 | ans = self._rescale(exp._exp, rounding) |
| 2210 | # raise Inexact and Rounded where appropriate |
| 2211 | if ans._exp > self._exp: |
| 2212 | context._raise_error(Rounded) |
| 2213 | if ans != self: |
| 2214 | context._raise_error(Inexact) |
| 2215 | return ans |
| 2216 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2217 | # exp._exp should be between Etiny and Emax |
| 2218 | if not (context.Etiny() <= exp._exp <= context.Emax): |
| 2219 | return context._raise_error(InvalidOperation, |
| 2220 | 'target exponent out of bounds in quantize') |
| 2221 | |
| 2222 | if not self: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2223 | ans = _dec_from_triple(self._sign, '0', exp._exp) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2224 | return ans._fix(context) |
| 2225 | |
| 2226 | self_adjusted = self.adjusted() |
| 2227 | if self_adjusted > context.Emax: |
| 2228 | return context._raise_error(InvalidOperation, |
| 2229 | 'exponent of quantize result too large for current context') |
| 2230 | if self_adjusted - exp._exp + 1 > context.prec: |
| 2231 | return context._raise_error(InvalidOperation, |
| 2232 | 'quantize result has too many digits for current context') |
| 2233 | |
| 2234 | ans = self._rescale(exp._exp, rounding) |
| 2235 | if ans.adjusted() > context.Emax: |
| 2236 | return context._raise_error(InvalidOperation, |
| 2237 | 'exponent of quantize result too large for current context') |
| 2238 | if len(ans._int) > context.prec: |
| 2239 | return context._raise_error(InvalidOperation, |
| 2240 | 'quantize result has too many digits for current context') |
| 2241 | |
| 2242 | # raise appropriate flags |
| 2243 | if ans._exp > self._exp: |
| 2244 | context._raise_error(Rounded) |
| 2245 | if ans != self: |
| 2246 | context._raise_error(Inexact) |
| 2247 | if ans and ans.adjusted() < context.Emin: |
| 2248 | context._raise_error(Subnormal) |
| 2249 | |
| 2250 | # call to fix takes care of any necessary folddown |
| 2251 | ans = ans._fix(context) |
| 2252 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2253 | |
| 2254 | def same_quantum(self, other): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2255 | """Return True if self and other have the same exponent; otherwise |
| 2256 | return False. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2257 | |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2258 | If either operand is a special value, the following rules are used: |
| 2259 | * return True if both operands are infinities |
| 2260 | * return True if both operands are NaNs |
| 2261 | * otherwise, return False. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2262 | """ |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2263 | other = _convert_other(other, raiseit=True) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2264 | if self._is_special or other._is_special: |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2265 | return (self.is_nan() and other.is_nan() or |
| 2266 | self.is_infinite() and other.is_infinite()) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2267 | return self._exp == other._exp |
| 2268 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2269 | def _rescale(self, exp, rounding): |
| 2270 | """Rescale self so that the exponent is exp, either by padding with zeros |
| 2271 | or by truncating digits, using the given rounding mode. |
| 2272 | |
| 2273 | Specials are returned without change. This operation is |
| 2274 | quiet: it raises no flags, and uses no information from the |
| 2275 | context. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2276 | |
| 2277 | exp = exp to scale to (an integer) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2278 | rounding = rounding mode |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2279 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2280 | if self._is_special: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2281 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2282 | if not self: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2283 | return _dec_from_triple(self._sign, '0', exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2284 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2285 | if self._exp >= exp: |
| 2286 | # pad answer with zeros if necessary |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2287 | return _dec_from_triple(self._sign, |
| 2288 | self._int + '0'*(self._exp - exp), exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2289 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2290 | # too many digits; round and lose data. If self.adjusted() < |
| 2291 | # exp-1, replace self by 10**(exp-1) before rounding |
| 2292 | digits = len(self._int) + self._exp - exp |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2293 | if digits < 0: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2294 | self = _dec_from_triple(self._sign, '1', exp-1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2295 | digits = 0 |
| 2296 | this_function = getattr(self, self._pick_rounding_function[rounding]) |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 2297 | changed = this_function(digits) |
| 2298 | coeff = self._int[:digits] or '0' |
| 2299 | if changed == 1: |
| 2300 | coeff = str(int(coeff)+1) |
| 2301 | return _dec_from_triple(self._sign, coeff, exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2302 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2303 | def to_integral_exact(self, rounding=None, context=None): |
| 2304 | """Rounds to a nearby integer. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2305 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2306 | If no rounding mode is specified, take the rounding mode from |
| 2307 | the context. This method raises the Rounded and Inexact flags |
| 2308 | when appropriate. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2309 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2310 | See also: to_integral_value, which does exactly the same as |
| 2311 | this method except that it doesn't raise Inexact or Rounded. |
| 2312 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2313 | if self._is_special: |
| 2314 | ans = self._check_nans(context=context) |
| 2315 | if ans: |
| 2316 | return ans |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2317 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2318 | if self._exp >= 0: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2319 | return Decimal(self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2320 | if not self: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2321 | return _dec_from_triple(self._sign, '0', 0) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2322 | if context is None: |
| 2323 | context = getcontext() |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2324 | if rounding is None: |
| 2325 | rounding = context.rounding |
| 2326 | context._raise_error(Rounded) |
| 2327 | ans = self._rescale(0, rounding) |
| 2328 | if ans != self: |
| 2329 | context._raise_error(Inexact) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2330 | return ans |
| 2331 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2332 | def to_integral_value(self, rounding=None, context=None): |
| 2333 | """Rounds to the nearest integer, without raising inexact, rounded.""" |
| 2334 | if context is None: |
| 2335 | context = getcontext() |
| 2336 | if rounding is None: |
| 2337 | rounding = context.rounding |
| 2338 | if self._is_special: |
| 2339 | ans = self._check_nans(context=context) |
| 2340 | if ans: |
| 2341 | return ans |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2342 | return Decimal(self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2343 | if self._exp >= 0: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2344 | return Decimal(self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2345 | else: |
| 2346 | return self._rescale(0, rounding) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2347 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2348 | # the method name changed, but we provide also the old one, for compatibility |
| 2349 | to_integral = to_integral_value |
| 2350 | |
| 2351 | def sqrt(self, context=None): |
| 2352 | """Return the square root of self.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2353 | if self._is_special: |
| 2354 | ans = self._check_nans(context=context) |
| 2355 | if ans: |
| 2356 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2357 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2358 | if self._isinfinity() and self._sign == 0: |
| 2359 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2360 | |
| 2361 | if not self: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2362 | # exponent = self._exp // 2. sqrt(-0) = -0 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2363 | ans = _dec_from_triple(self._sign, '0', self._exp // 2) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2364 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2365 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2366 | if context is None: |
| 2367 | context = getcontext() |
| 2368 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2369 | if self._sign == 1: |
| 2370 | return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0') |
| 2371 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2372 | # At this point self represents a positive number. Let p be |
| 2373 | # the desired precision and express self in the form c*100**e |
| 2374 | # with c a positive real number and e an integer, c and e |
| 2375 | # being chosen so that 100**(p-1) <= c < 100**p. Then the |
| 2376 | # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1) |
| 2377 | # <= sqrt(c) < 10**p, so the closest representable Decimal at |
| 2378 | # precision p is n*10**e where n = round_half_even(sqrt(c)), |
| 2379 | # the closest integer to sqrt(c) with the even integer chosen |
| 2380 | # in the case of a tie. |
| 2381 | # |
| 2382 | # To ensure correct rounding in all cases, we use the |
| 2383 | # following trick: we compute the square root to an extra |
| 2384 | # place (precision p+1 instead of precision p), rounding down. |
| 2385 | # Then, if the result is inexact and its last digit is 0 or 5, |
| 2386 | # we increase the last digit to 1 or 6 respectively; if it's |
| 2387 | # exact we leave the last digit alone. Now the final round to |
| 2388 | # p places (or fewer in the case of underflow) will round |
| 2389 | # correctly and raise the appropriate flags. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2390 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2391 | # use an extra digit of precision |
| 2392 | prec = context.prec+1 |
| 2393 | |
| 2394 | # write argument in the form c*100**e where e = self._exp//2 |
| 2395 | # is the 'ideal' exponent, to be used if the square root is |
| 2396 | # exactly representable. l is the number of 'digits' of c in |
| 2397 | # base 100, so that 100**(l-1) <= c < 100**l. |
| 2398 | op = _WorkRep(self) |
| 2399 | e = op.exp >> 1 |
| 2400 | if op.exp & 1: |
| 2401 | c = op.int * 10 |
| 2402 | l = (len(self._int) >> 1) + 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2403 | else: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2404 | c = op.int |
| 2405 | l = len(self._int)+1 >> 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2406 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2407 | # rescale so that c has exactly prec base 100 'digits' |
| 2408 | shift = prec-l |
| 2409 | if shift >= 0: |
| 2410 | c *= 100**shift |
| 2411 | exact = True |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2412 | else: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2413 | c, remainder = divmod(c, 100**-shift) |
| 2414 | exact = not remainder |
| 2415 | e -= shift |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 2416 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2417 | # find n = floor(sqrt(c)) using Newton's method |
| 2418 | n = 10**prec |
| 2419 | while True: |
| 2420 | q = c//n |
| 2421 | if n <= q: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2422 | break |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2423 | else: |
| 2424 | n = n + q >> 1 |
| 2425 | exact = exact and n*n == c |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2426 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2427 | if exact: |
| 2428 | # result is exact; rescale to use ideal exponent e |
| 2429 | if shift >= 0: |
| 2430 | # assert n % 10**shift == 0 |
| 2431 | n //= 10**shift |
| 2432 | else: |
| 2433 | n *= 10**-shift |
| 2434 | e += shift |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2435 | else: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2436 | # result is not exact; fix last digit as described above |
| 2437 | if n % 5 == 0: |
| 2438 | n += 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2439 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2440 | ans = _dec_from_triple(0, str(n), e) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2441 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2442 | # round, and fit to current context |
| 2443 | context = context._shallow_copy() |
| 2444 | rounding = context._set_rounding(ROUND_HALF_EVEN) |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 2445 | ans = ans._fix(context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2446 | context.rounding = rounding |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2447 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2448 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2449 | |
| 2450 | def max(self, other, context=None): |
| 2451 | """Returns the larger value. |
| 2452 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2453 | Like max(self, other) except if one is not a number, returns |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2454 | NaN (and signals if one is sNaN). Also rounds. |
| 2455 | """ |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2456 | other = _convert_other(other, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2457 | |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2458 | if context is None: |
| 2459 | context = getcontext() |
| 2460 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2461 | if self._is_special or other._is_special: |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 2462 | # 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] | 2463 | # number is always returned |
| 2464 | sn = self._isnan() |
| 2465 | on = other._isnan() |
| 2466 | if sn or on: |
| 2467 | if on == 1 and sn != 2: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2468 | return self._fix_nan(context) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2469 | if sn == 1 and on != 2: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2470 | return other._fix_nan(context) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2471 | return self._check_nans(other, context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2472 | |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2473 | c = self.__cmp__(other) |
| 2474 | if c == 0: |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 2475 | # If both operands are finite and equal in numerical value |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2476 | # then an ordering is applied: |
| 2477 | # |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 2478 | # If the signs differ then max returns the operand with the |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2479 | # positive sign and min returns the operand with the negative sign |
| 2480 | # |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 2481 | # If the signs are the same then the exponent is used to select |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2482 | # the result. This is exactly the ordering used in compare_total. |
| 2483 | c = self.compare_total(other) |
| 2484 | |
| 2485 | if c == -1: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2486 | ans = other |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2487 | else: |
| 2488 | ans = self |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2489 | |
Raymond Hettinger | 76e60d6 | 2004-10-20 06:58:28 +0000 | [diff] [blame] | 2490 | if context._rounding_decision == ALWAYS_ROUND: |
| 2491 | return ans._fix(context) |
| 2492 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2493 | |
| 2494 | def min(self, other, context=None): |
| 2495 | """Returns the smaller value. |
| 2496 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 2497 | Like min(self, other) except if one is not a number, returns |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2498 | NaN (and signals if one is sNaN). Also rounds. |
| 2499 | """ |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2500 | other = _convert_other(other, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2501 | |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2502 | if context is None: |
| 2503 | context = getcontext() |
| 2504 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2505 | if self._is_special or other._is_special: |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 2506 | # 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] | 2507 | # number is always returned |
| 2508 | sn = self._isnan() |
| 2509 | on = other._isnan() |
| 2510 | if sn or on: |
| 2511 | if on == 1 and sn != 2: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2512 | return self._fix_nan(context) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2513 | if sn == 1 and on != 2: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2514 | return other._fix_nan(context) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2515 | return self._check_nans(other, context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2516 | |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2517 | c = self.__cmp__(other) |
| 2518 | if c == 0: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2519 | c = self.compare_total(other) |
| 2520 | |
| 2521 | if c == -1: |
| 2522 | ans = self |
| 2523 | else: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2524 | ans = other |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2525 | |
Raymond Hettinger | 76e60d6 | 2004-10-20 06:58:28 +0000 | [diff] [blame] | 2526 | if context._rounding_decision == ALWAYS_ROUND: |
| 2527 | return ans._fix(context) |
| 2528 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2529 | |
| 2530 | def _isinteger(self): |
| 2531 | """Returns whether self is an integer""" |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2532 | if self._is_special: |
| 2533 | return False |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2534 | if self._exp >= 0: |
| 2535 | return True |
| 2536 | rest = self._int[self._exp:] |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2537 | return rest == '0'*len(rest) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2538 | |
| 2539 | def _iseven(self): |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2540 | """Returns True if self is even. Assumes self is an integer.""" |
| 2541 | if not self or self._exp > 0: |
| 2542 | return True |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2543 | return self._int[-1+self._exp] in '02468' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2544 | |
| 2545 | def adjusted(self): |
| 2546 | """Return the adjusted exponent of self""" |
| 2547 | try: |
| 2548 | return self._exp + len(self._int) - 1 |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 2549 | # If NaN or Infinity, self._exp is string |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2550 | except TypeError: |
| 2551 | return 0 |
| 2552 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2553 | def canonical(self, context=None): |
| 2554 | """Returns the same Decimal object. |
| 2555 | |
| 2556 | As we do not have different encodings for the same number, the |
| 2557 | received object already is in its canonical form. |
| 2558 | """ |
| 2559 | return self |
| 2560 | |
| 2561 | def compare_signal(self, other, context=None): |
| 2562 | """Compares self to the other operand numerically. |
| 2563 | |
| 2564 | It's pretty much like compare(), but all NaNs signal, with signaling |
| 2565 | NaNs taking precedence over quiet NaNs. |
| 2566 | """ |
| 2567 | if context is None: |
| 2568 | context = getcontext() |
| 2569 | |
| 2570 | self_is_nan = self._isnan() |
| 2571 | other_is_nan = other._isnan() |
| 2572 | if self_is_nan == 2: |
| 2573 | return context._raise_error(InvalidOperation, 'sNaN', |
| 2574 | 1, self) |
| 2575 | if other_is_nan == 2: |
| 2576 | return context._raise_error(InvalidOperation, 'sNaN', |
| 2577 | 1, other) |
| 2578 | if self_is_nan: |
| 2579 | return context._raise_error(InvalidOperation, 'NaN in compare_signal', |
| 2580 | 1, self) |
| 2581 | if other_is_nan: |
| 2582 | return context._raise_error(InvalidOperation, 'NaN in compare_signal', |
| 2583 | 1, other) |
| 2584 | return self.compare(other, context=context) |
| 2585 | |
| 2586 | def compare_total(self, other): |
| 2587 | """Compares self to other using the abstract representations. |
| 2588 | |
| 2589 | This is not like the standard compare, which use their numerical |
| 2590 | value. Note that a total ordering is defined for all possible abstract |
| 2591 | representations. |
| 2592 | """ |
| 2593 | # if one is negative and the other is positive, it's easy |
| 2594 | if self._sign and not other._sign: |
| 2595 | return Dec_n1 |
| 2596 | if not self._sign and other._sign: |
| 2597 | return Dec_p1 |
| 2598 | sign = self._sign |
| 2599 | |
| 2600 | # let's handle both NaN types |
| 2601 | self_nan = self._isnan() |
| 2602 | other_nan = other._isnan() |
| 2603 | if self_nan or other_nan: |
| 2604 | if self_nan == other_nan: |
| 2605 | if self._int < other._int: |
| 2606 | if sign: |
| 2607 | return Dec_p1 |
| 2608 | else: |
| 2609 | return Dec_n1 |
| 2610 | if self._int > other._int: |
| 2611 | if sign: |
| 2612 | return Dec_n1 |
| 2613 | else: |
| 2614 | return Dec_p1 |
| 2615 | return Dec_0 |
| 2616 | |
| 2617 | if sign: |
| 2618 | if self_nan == 1: |
| 2619 | return Dec_n1 |
| 2620 | if other_nan == 1: |
| 2621 | return Dec_p1 |
| 2622 | if self_nan == 2: |
| 2623 | return Dec_n1 |
| 2624 | if other_nan == 2: |
| 2625 | return Dec_p1 |
| 2626 | else: |
| 2627 | if self_nan == 1: |
| 2628 | return Dec_p1 |
| 2629 | if other_nan == 1: |
| 2630 | return Dec_n1 |
| 2631 | if self_nan == 2: |
| 2632 | return Dec_p1 |
| 2633 | if other_nan == 2: |
| 2634 | return Dec_n1 |
| 2635 | |
| 2636 | if self < other: |
| 2637 | return Dec_n1 |
| 2638 | if self > other: |
| 2639 | return Dec_p1 |
| 2640 | |
| 2641 | if self._exp < other._exp: |
| 2642 | if sign: |
| 2643 | return Dec_p1 |
| 2644 | else: |
| 2645 | return Dec_n1 |
| 2646 | if self._exp > other._exp: |
| 2647 | if sign: |
| 2648 | return Dec_n1 |
| 2649 | else: |
| 2650 | return Dec_p1 |
| 2651 | return Dec_0 |
| 2652 | |
| 2653 | |
| 2654 | def compare_total_mag(self, other): |
| 2655 | """Compares self to other using abstract repr., ignoring sign. |
| 2656 | |
| 2657 | Like compare_total, but with operand's sign ignored and assumed to be 0. |
| 2658 | """ |
| 2659 | s = self.copy_abs() |
| 2660 | o = other.copy_abs() |
| 2661 | return s.compare_total(o) |
| 2662 | |
| 2663 | def copy_abs(self): |
| 2664 | """Returns a copy with the sign set to 0. """ |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2665 | return _dec_from_triple(0, self._int, self._exp, self._is_special) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2666 | |
| 2667 | def copy_negate(self): |
| 2668 | """Returns a copy with the sign inverted.""" |
| 2669 | if self._sign: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2670 | return _dec_from_triple(0, self._int, self._exp, self._is_special) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2671 | else: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2672 | return _dec_from_triple(1, self._int, self._exp, self._is_special) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2673 | |
| 2674 | def copy_sign(self, other): |
| 2675 | """Returns self with the sign of other.""" |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2676 | return _dec_from_triple(other._sign, self._int, |
| 2677 | self._exp, self._is_special) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2678 | |
| 2679 | def exp(self, context=None): |
| 2680 | """Returns e ** self.""" |
| 2681 | |
| 2682 | if context is None: |
| 2683 | context = getcontext() |
| 2684 | |
| 2685 | # exp(NaN) = NaN |
| 2686 | ans = self._check_nans(context=context) |
| 2687 | if ans: |
| 2688 | return ans |
| 2689 | |
| 2690 | # exp(-Infinity) = 0 |
| 2691 | if self._isinfinity() == -1: |
| 2692 | return Dec_0 |
| 2693 | |
| 2694 | # exp(0) = 1 |
| 2695 | if not self: |
| 2696 | return Dec_p1 |
| 2697 | |
| 2698 | # exp(Infinity) = Infinity |
| 2699 | if self._isinfinity() == 1: |
| 2700 | return Decimal(self) |
| 2701 | |
| 2702 | # the result is now guaranteed to be inexact (the true |
| 2703 | # mathematical result is transcendental). There's no need to |
| 2704 | # raise Rounded and Inexact here---they'll always be raised as |
| 2705 | # a result of the call to _fix. |
| 2706 | p = context.prec |
| 2707 | adj = self.adjusted() |
| 2708 | |
| 2709 | # we only need to do any computation for quite a small range |
| 2710 | # of adjusted exponents---for example, -29 <= adj <= 10 for |
| 2711 | # the default context. For smaller exponent the result is |
| 2712 | # indistinguishable from 1 at the given precision, while for |
| 2713 | # larger exponent the result either overflows or underflows. |
| 2714 | if self._sign == 0 and adj > len(str((context.Emax+1)*3)): |
| 2715 | # overflow |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2716 | ans = _dec_from_triple(0, '1', context.Emax+1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2717 | elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)): |
| 2718 | # underflow to 0 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2719 | ans = _dec_from_triple(0, '1', context.Etiny()-1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2720 | elif self._sign == 0 and adj < -p: |
| 2721 | # p+1 digits; final round will raise correct flags |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2722 | ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2723 | elif self._sign == 1 and adj < -p-1: |
| 2724 | # p+1 digits; final round will raise correct flags |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2725 | ans = _dec_from_triple(0, '9'*(p+1), -p-1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2726 | # general case |
| 2727 | else: |
| 2728 | op = _WorkRep(self) |
| 2729 | c, e = op.int, op.exp |
| 2730 | if op.sign == 1: |
| 2731 | c = -c |
| 2732 | |
| 2733 | # compute correctly rounded result: increase precision by |
| 2734 | # 3 digits at a time until we get an unambiguously |
| 2735 | # roundable result |
| 2736 | extra = 3 |
| 2737 | while True: |
| 2738 | coeff, exp = _dexp(c, e, p+extra) |
| 2739 | if coeff % (5*10**(len(str(coeff))-p-1)): |
| 2740 | break |
| 2741 | extra += 3 |
| 2742 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2743 | ans = _dec_from_triple(0, str(coeff), exp) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2744 | |
| 2745 | # at this stage, ans should round correctly with *any* |
| 2746 | # rounding mode, not just with ROUND_HALF_EVEN |
| 2747 | context = context._shallow_copy() |
| 2748 | rounding = context._set_rounding(ROUND_HALF_EVEN) |
| 2749 | ans = ans._fix(context) |
| 2750 | context.rounding = rounding |
| 2751 | |
| 2752 | return ans |
| 2753 | |
| 2754 | def is_canonical(self): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2755 | """Return True if self is canonical; otherwise return False. |
| 2756 | |
| 2757 | Currently, the encoding of a Decimal instance is always |
| 2758 | canonical, so this method returns True for any Decimal. |
| 2759 | """ |
| 2760 | return True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2761 | |
| 2762 | def is_finite(self): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2763 | """Return True if self is finite; otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2764 | |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2765 | A Decimal instance is considered finite if it is neither |
| 2766 | infinite nor a NaN. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2767 | """ |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2768 | return not self._is_special |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2769 | |
| 2770 | def is_infinite(self): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2771 | """Return True if self is infinite; otherwise return False.""" |
| 2772 | return self._exp == 'F' |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2773 | |
| 2774 | def is_nan(self): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2775 | """Return True if self is a qNaN or sNaN; otherwise return False.""" |
| 2776 | return self._exp in ('n', 'N') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2777 | |
| 2778 | def is_normal(self, context=None): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2779 | """Return True if self is a normal number; otherwise return False.""" |
| 2780 | if self._is_special or not self: |
| 2781 | return False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2782 | if context is None: |
| 2783 | context = getcontext() |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2784 | return context.Emin <= self.adjusted() <= context.Emax |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2785 | |
| 2786 | def is_qnan(self): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2787 | """Return True if self is a quiet NaN; otherwise return False.""" |
| 2788 | return self._exp == 'n' |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2789 | |
| 2790 | def is_signed(self): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2791 | """Return True if self is negative; otherwise return False.""" |
| 2792 | return self._sign == 1 |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2793 | |
| 2794 | def is_snan(self): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2795 | """Return True if self is a signaling NaN; otherwise return False.""" |
| 2796 | return self._exp == 'N' |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2797 | |
| 2798 | def is_subnormal(self, context=None): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2799 | """Return True if self is subnormal; otherwise return False.""" |
| 2800 | if self._is_special or not self: |
| 2801 | return False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2802 | if context is None: |
| 2803 | context = getcontext() |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2804 | return self.adjusted() < context.Emin |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2805 | |
| 2806 | def is_zero(self): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2807 | """Return True if self is a zero; otherwise return False.""" |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2808 | return not self._is_special and self._int == '0' |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2809 | |
| 2810 | def _ln_exp_bound(self): |
| 2811 | """Compute a lower bound for the adjusted exponent of self.ln(). |
| 2812 | In other words, compute r such that self.ln() >= 10**r. Assumes |
| 2813 | that self is finite and positive and that self != 1. |
| 2814 | """ |
| 2815 | |
| 2816 | # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1 |
| 2817 | adj = self._exp + len(self._int) - 1 |
| 2818 | if adj >= 1: |
| 2819 | # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10) |
| 2820 | return len(str(adj*23//10)) - 1 |
| 2821 | if adj <= -2: |
| 2822 | # argument <= 0.1 |
| 2823 | return len(str((-1-adj)*23//10)) - 1 |
| 2824 | op = _WorkRep(self) |
| 2825 | c, e = op.int, op.exp |
| 2826 | if adj == 0: |
| 2827 | # 1 < self < 10 |
| 2828 | num = str(c-10**-e) |
| 2829 | den = str(c) |
| 2830 | return len(num) - len(den) - (num < den) |
| 2831 | # adj == -1, 0.1 <= self < 1 |
| 2832 | return e + len(str(10**-e - c)) - 1 |
| 2833 | |
| 2834 | |
| 2835 | def ln(self, context=None): |
| 2836 | """Returns the natural (base e) logarithm of self.""" |
| 2837 | |
| 2838 | if context is None: |
| 2839 | context = getcontext() |
| 2840 | |
| 2841 | # ln(NaN) = NaN |
| 2842 | ans = self._check_nans(context=context) |
| 2843 | if ans: |
| 2844 | return ans |
| 2845 | |
| 2846 | # ln(0.0) == -Infinity |
| 2847 | if not self: |
| 2848 | return negInf |
| 2849 | |
| 2850 | # ln(Infinity) = Infinity |
| 2851 | if self._isinfinity() == 1: |
| 2852 | return Inf |
| 2853 | |
| 2854 | # ln(1.0) == 0.0 |
| 2855 | if self == Dec_p1: |
| 2856 | return Dec_0 |
| 2857 | |
| 2858 | # ln(negative) raises InvalidOperation |
| 2859 | if self._sign == 1: |
| 2860 | return context._raise_error(InvalidOperation, |
| 2861 | 'ln of a negative value') |
| 2862 | |
| 2863 | # result is irrational, so necessarily inexact |
| 2864 | op = _WorkRep(self) |
| 2865 | c, e = op.int, op.exp |
| 2866 | p = context.prec |
| 2867 | |
| 2868 | # correctly rounded result: repeatedly increase precision by 3 |
| 2869 | # until we get an unambiguously roundable result |
| 2870 | places = p - self._ln_exp_bound() + 2 # at least p+3 places |
| 2871 | while True: |
| 2872 | coeff = _dlog(c, e, places) |
| 2873 | # assert len(str(abs(coeff)))-p >= 1 |
| 2874 | if coeff % (5*10**(len(str(abs(coeff)))-p-1)): |
| 2875 | break |
| 2876 | places += 3 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2877 | ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2878 | |
| 2879 | context = context._shallow_copy() |
| 2880 | rounding = context._set_rounding(ROUND_HALF_EVEN) |
| 2881 | ans = ans._fix(context) |
| 2882 | context.rounding = rounding |
| 2883 | return ans |
| 2884 | |
| 2885 | def _log10_exp_bound(self): |
| 2886 | """Compute a lower bound for the adjusted exponent of self.log10(). |
| 2887 | In other words, find r such that self.log10() >= 10**r. |
| 2888 | Assumes that self is finite and positive and that self != 1. |
| 2889 | """ |
| 2890 | |
| 2891 | # For x >= 10 or x < 0.1 we only need a bound on the integer |
| 2892 | # part of log10(self), and this comes directly from the |
| 2893 | # exponent of x. For 0.1 <= x <= 10 we use the inequalities |
| 2894 | # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| > |
| 2895 | # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0 |
| 2896 | |
| 2897 | adj = self._exp + len(self._int) - 1 |
| 2898 | if adj >= 1: |
| 2899 | # self >= 10 |
| 2900 | return len(str(adj))-1 |
| 2901 | if adj <= -2: |
| 2902 | # self < 0.1 |
| 2903 | return len(str(-1-adj))-1 |
| 2904 | op = _WorkRep(self) |
| 2905 | c, e = op.int, op.exp |
| 2906 | if adj == 0: |
| 2907 | # 1 < self < 10 |
| 2908 | num = str(c-10**-e) |
| 2909 | den = str(231*c) |
| 2910 | return len(num) - len(den) - (num < den) + 2 |
| 2911 | # adj == -1, 0.1 <= self < 1 |
| 2912 | num = str(10**-e-c) |
| 2913 | return len(num) + e - (num < "231") - 1 |
| 2914 | |
| 2915 | def log10(self, context=None): |
| 2916 | """Returns the base 10 logarithm of self.""" |
| 2917 | |
| 2918 | if context is None: |
| 2919 | context = getcontext() |
| 2920 | |
| 2921 | # log10(NaN) = NaN |
| 2922 | ans = self._check_nans(context=context) |
| 2923 | if ans: |
| 2924 | return ans |
| 2925 | |
| 2926 | # log10(0.0) == -Infinity |
| 2927 | if not self: |
| 2928 | return negInf |
| 2929 | |
| 2930 | # log10(Infinity) = Infinity |
| 2931 | if self._isinfinity() == 1: |
| 2932 | return Inf |
| 2933 | |
| 2934 | # log10(negative or -Infinity) raises InvalidOperation |
| 2935 | if self._sign == 1: |
| 2936 | return context._raise_error(InvalidOperation, |
| 2937 | 'log10 of a negative value') |
| 2938 | |
| 2939 | # log10(10**n) = n |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2940 | if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1): |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2941 | # answer may need rounding |
| 2942 | ans = Decimal(self._exp + len(self._int) - 1) |
| 2943 | else: |
| 2944 | # result is irrational, so necessarily inexact |
| 2945 | op = _WorkRep(self) |
| 2946 | c, e = op.int, op.exp |
| 2947 | p = context.prec |
| 2948 | |
| 2949 | # correctly rounded result: repeatedly increase precision |
| 2950 | # until result is unambiguously roundable |
| 2951 | places = p-self._log10_exp_bound()+2 |
| 2952 | while True: |
| 2953 | coeff = _dlog10(c, e, places) |
| 2954 | # assert len(str(abs(coeff)))-p >= 1 |
| 2955 | if coeff % (5*10**(len(str(abs(coeff)))-p-1)): |
| 2956 | break |
| 2957 | places += 3 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2958 | ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2959 | |
| 2960 | context = context._shallow_copy() |
| 2961 | rounding = context._set_rounding(ROUND_HALF_EVEN) |
| 2962 | ans = ans._fix(context) |
| 2963 | context.rounding = rounding |
| 2964 | return ans |
| 2965 | |
| 2966 | def logb(self, context=None): |
| 2967 | """ Returns the exponent of the magnitude of self's MSD. |
| 2968 | |
| 2969 | The result is the integer which is the exponent of the magnitude |
| 2970 | of the most significant digit of self (as though it were truncated |
| 2971 | to a single digit while maintaining the value of that digit and |
| 2972 | without limiting the resulting exponent). |
| 2973 | """ |
| 2974 | # logb(NaN) = NaN |
| 2975 | ans = self._check_nans(context=context) |
| 2976 | if ans: |
| 2977 | return ans |
| 2978 | |
| 2979 | if context is None: |
| 2980 | context = getcontext() |
| 2981 | |
| 2982 | # logb(+/-Inf) = +Inf |
| 2983 | if self._isinfinity(): |
| 2984 | return Inf |
| 2985 | |
| 2986 | # logb(0) = -Inf, DivisionByZero |
| 2987 | if not self: |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 2988 | return context._raise_error(DivisionByZero, 'logb(0)', 1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2989 | |
| 2990 | # otherwise, simply return the adjusted exponent of self, as a |
| 2991 | # Decimal. Note that no attempt is made to fit the result |
| 2992 | # into the current context. |
| 2993 | return Decimal(self.adjusted()) |
| 2994 | |
| 2995 | def _islogical(self): |
| 2996 | """Return True if self is a logical operand. |
| 2997 | |
| 2998 | For being logical, it must be a finite numbers with a sign of 0, |
| 2999 | an exponent of 0, and a coefficient whose digits must all be |
| 3000 | either 0 or 1. |
| 3001 | """ |
| 3002 | if self._sign != 0 or self._exp != 0: |
| 3003 | return False |
| 3004 | for dig in self._int: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3005 | if dig not in '01': |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3006 | return False |
| 3007 | return True |
| 3008 | |
| 3009 | def _fill_logical(self, context, opa, opb): |
| 3010 | dif = context.prec - len(opa) |
| 3011 | if dif > 0: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3012 | opa = '0'*dif + opa |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3013 | elif dif < 0: |
| 3014 | opa = opa[-context.prec:] |
| 3015 | dif = context.prec - len(opb) |
| 3016 | if dif > 0: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3017 | opb = '0'*dif + opb |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3018 | elif dif < 0: |
| 3019 | opb = opb[-context.prec:] |
| 3020 | return opa, opb |
| 3021 | |
| 3022 | def logical_and(self, other, context=None): |
| 3023 | """Applies an 'and' operation between self and other's digits.""" |
| 3024 | if context is None: |
| 3025 | context = getcontext() |
| 3026 | if not self._islogical() or not other._islogical(): |
| 3027 | return context._raise_error(InvalidOperation) |
| 3028 | |
| 3029 | # fill to context.prec |
| 3030 | (opa, opb) = self._fill_logical(context, self._int, other._int) |
| 3031 | |
| 3032 | # make the operation, and clean starting zeroes |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3033 | result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)]) |
| 3034 | return _dec_from_triple(0, result.lstrip('0') or '0', 0) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3035 | |
| 3036 | def logical_invert(self, context=None): |
| 3037 | """Invert all its digits.""" |
| 3038 | if context is None: |
| 3039 | context = getcontext() |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3040 | return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0), |
| 3041 | context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3042 | |
| 3043 | def logical_or(self, other, context=None): |
| 3044 | """Applies an 'or' operation between self and other's digits.""" |
| 3045 | if context is None: |
| 3046 | context = getcontext() |
| 3047 | if not self._islogical() or not other._islogical(): |
| 3048 | return context._raise_error(InvalidOperation) |
| 3049 | |
| 3050 | # fill to context.prec |
| 3051 | (opa, opb) = self._fill_logical(context, self._int, other._int) |
| 3052 | |
| 3053 | # make the operation, and clean starting zeroes |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3054 | result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb)) |
| 3055 | return _dec_from_triple(0, result.lstrip('0') or '0', 0) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3056 | |
| 3057 | def logical_xor(self, other, context=None): |
| 3058 | """Applies an 'xor' operation between self and other's digits.""" |
| 3059 | if context is None: |
| 3060 | context = getcontext() |
| 3061 | if not self._islogical() or not other._islogical(): |
| 3062 | return context._raise_error(InvalidOperation) |
| 3063 | |
| 3064 | # fill to context.prec |
| 3065 | (opa, opb) = self._fill_logical(context, self._int, other._int) |
| 3066 | |
| 3067 | # make the operation, and clean starting zeroes |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3068 | result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb)) |
| 3069 | return _dec_from_triple(0, result.lstrip('0') or '0', 0) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3070 | |
| 3071 | def max_mag(self, other, context=None): |
| 3072 | """Compares the values numerically with their sign ignored.""" |
| 3073 | other = _convert_other(other, raiseit=True) |
| 3074 | |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 3075 | if context is None: |
| 3076 | context = getcontext() |
| 3077 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3078 | if self._is_special or other._is_special: |
| 3079 | # If one operand is a quiet NaN and the other is number, then the |
| 3080 | # number is always returned |
| 3081 | sn = self._isnan() |
| 3082 | on = other._isnan() |
| 3083 | if sn or on: |
| 3084 | if on == 1 and sn != 2: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 3085 | return self._fix_nan(context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3086 | if sn == 1 and on != 2: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 3087 | return other._fix_nan(context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3088 | return self._check_nans(other, context) |
| 3089 | |
| 3090 | c = self.copy_abs().__cmp__(other.copy_abs()) |
| 3091 | if c == 0: |
| 3092 | c = self.compare_total(other) |
| 3093 | |
| 3094 | if c == -1: |
| 3095 | ans = other |
| 3096 | else: |
| 3097 | ans = self |
| 3098 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3099 | if context._rounding_decision == ALWAYS_ROUND: |
| 3100 | return ans._fix(context) |
| 3101 | return ans |
| 3102 | |
| 3103 | def min_mag(self, other, context=None): |
| 3104 | """Compares the values numerically with their sign ignored.""" |
| 3105 | other = _convert_other(other, raiseit=True) |
| 3106 | |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 3107 | if context is None: |
| 3108 | context = getcontext() |
| 3109 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3110 | if self._is_special or other._is_special: |
| 3111 | # If one operand is a quiet NaN and the other is number, then the |
| 3112 | # number is always returned |
| 3113 | sn = self._isnan() |
| 3114 | on = other._isnan() |
| 3115 | if sn or on: |
| 3116 | if on == 1 and sn != 2: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 3117 | return self._fix_nan(context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3118 | if sn == 1 and on != 2: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 3119 | return other._fix_nan(context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3120 | return self._check_nans(other, context) |
| 3121 | |
| 3122 | c = self.copy_abs().__cmp__(other.copy_abs()) |
| 3123 | if c == 0: |
| 3124 | c = self.compare_total(other) |
| 3125 | |
| 3126 | if c == -1: |
| 3127 | ans = self |
| 3128 | else: |
| 3129 | ans = other |
| 3130 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3131 | if context._rounding_decision == ALWAYS_ROUND: |
| 3132 | return ans._fix(context) |
| 3133 | return ans |
| 3134 | |
| 3135 | def next_minus(self, context=None): |
| 3136 | """Returns the largest representable number smaller than itself.""" |
| 3137 | if context is None: |
| 3138 | context = getcontext() |
| 3139 | |
| 3140 | ans = self._check_nans(context=context) |
| 3141 | if ans: |
| 3142 | return ans |
| 3143 | |
| 3144 | if self._isinfinity() == -1: |
| 3145 | return negInf |
| 3146 | if self._isinfinity() == 1: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3147 | return _dec_from_triple(0, '9'*context.prec, context.Etop()) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3148 | |
| 3149 | context = context.copy() |
| 3150 | context._set_rounding(ROUND_FLOOR) |
| 3151 | context._ignore_all_flags() |
| 3152 | new_self = self._fix(context) |
| 3153 | if new_self != self: |
| 3154 | return new_self |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3155 | return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1), |
| 3156 | context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3157 | |
| 3158 | def next_plus(self, context=None): |
| 3159 | """Returns the smallest representable number larger than itself.""" |
| 3160 | if context is None: |
| 3161 | context = getcontext() |
| 3162 | |
| 3163 | ans = self._check_nans(context=context) |
| 3164 | if ans: |
| 3165 | return ans |
| 3166 | |
| 3167 | if self._isinfinity() == 1: |
| 3168 | return Inf |
| 3169 | if self._isinfinity() == -1: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3170 | return _dec_from_triple(1, '9'*context.prec, context.Etop()) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3171 | |
| 3172 | context = context.copy() |
| 3173 | context._set_rounding(ROUND_CEILING) |
| 3174 | context._ignore_all_flags() |
| 3175 | new_self = self._fix(context) |
| 3176 | if new_self != self: |
| 3177 | return new_self |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3178 | return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1), |
| 3179 | context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3180 | |
| 3181 | def next_toward(self, other, context=None): |
| 3182 | """Returns the number closest to self, in the direction towards other. |
| 3183 | |
| 3184 | The result is the closest representable number to self |
| 3185 | (excluding self) that is in the direction towards other, |
| 3186 | unless both have the same value. If the two operands are |
| 3187 | numerically equal, then the result is a copy of self with the |
| 3188 | sign set to be the same as the sign of other. |
| 3189 | """ |
| 3190 | other = _convert_other(other, raiseit=True) |
| 3191 | |
| 3192 | if context is None: |
| 3193 | context = getcontext() |
| 3194 | |
| 3195 | ans = self._check_nans(other, context) |
| 3196 | if ans: |
| 3197 | return ans |
| 3198 | |
| 3199 | comparison = self.__cmp__(other) |
| 3200 | if comparison == 0: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3201 | return self.copy_sign(other) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3202 | |
| 3203 | if comparison == -1: |
| 3204 | ans = self.next_plus(context) |
| 3205 | else: # comparison == 1 |
| 3206 | ans = self.next_minus(context) |
| 3207 | |
| 3208 | # decide which flags to raise using value of ans |
| 3209 | if ans._isinfinity(): |
| 3210 | context._raise_error(Overflow, |
| 3211 | 'Infinite result from next_toward', |
| 3212 | ans._sign) |
| 3213 | context._raise_error(Rounded) |
| 3214 | context._raise_error(Inexact) |
| 3215 | elif ans.adjusted() < context.Emin: |
| 3216 | context._raise_error(Underflow) |
| 3217 | context._raise_error(Subnormal) |
| 3218 | context._raise_error(Rounded) |
| 3219 | context._raise_error(Inexact) |
| 3220 | # if precision == 1 then we don't raise Clamped for a |
| 3221 | # result 0E-Etiny. |
| 3222 | if not ans: |
| 3223 | context._raise_error(Clamped) |
| 3224 | |
| 3225 | return ans |
| 3226 | |
| 3227 | def number_class(self, context=None): |
| 3228 | """Returns an indication of the class of self. |
| 3229 | |
| 3230 | The class is one of the following strings: |
| 3231 | -sNaN |
| 3232 | -NaN |
| 3233 | -Infinity |
| 3234 | -Normal |
| 3235 | -Subnormal |
| 3236 | -Zero |
| 3237 | +Zero |
| 3238 | +Subnormal |
| 3239 | +Normal |
| 3240 | +Infinity |
| 3241 | """ |
| 3242 | if self.is_snan(): |
| 3243 | return "sNaN" |
| 3244 | if self.is_qnan(): |
| 3245 | return "NaN" |
| 3246 | inf = self._isinfinity() |
| 3247 | if inf == 1: |
| 3248 | return "+Infinity" |
| 3249 | if inf == -1: |
| 3250 | return "-Infinity" |
| 3251 | if self.is_zero(): |
| 3252 | if self._sign: |
| 3253 | return "-Zero" |
| 3254 | else: |
| 3255 | return "+Zero" |
| 3256 | if context is None: |
| 3257 | context = getcontext() |
| 3258 | if self.is_subnormal(context=context): |
| 3259 | if self._sign: |
| 3260 | return "-Subnormal" |
| 3261 | else: |
| 3262 | return "+Subnormal" |
| 3263 | # just a normal, regular, boring number, :) |
| 3264 | if self._sign: |
| 3265 | return "-Normal" |
| 3266 | else: |
| 3267 | return "+Normal" |
| 3268 | |
| 3269 | def radix(self): |
| 3270 | """Just returns 10, as this is Decimal, :)""" |
| 3271 | return Decimal(10) |
| 3272 | |
| 3273 | def rotate(self, other, context=None): |
| 3274 | """Returns a rotated copy of self, value-of-other times.""" |
| 3275 | if context is None: |
| 3276 | context = getcontext() |
| 3277 | |
| 3278 | ans = self._check_nans(other, context) |
| 3279 | if ans: |
| 3280 | return ans |
| 3281 | |
| 3282 | if other._exp != 0: |
| 3283 | return context._raise_error(InvalidOperation) |
| 3284 | if not (-context.prec <= int(other) <= context.prec): |
| 3285 | return context._raise_error(InvalidOperation) |
| 3286 | |
| 3287 | if self._isinfinity(): |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 3288 | return Decimal(self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3289 | |
| 3290 | # get values, pad if necessary |
| 3291 | torot = int(other) |
| 3292 | rotdig = self._int |
| 3293 | topad = context.prec - len(rotdig) |
| 3294 | if topad: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3295 | rotdig = '0'*topad + rotdig |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3296 | |
| 3297 | # let's rotate! |
| 3298 | rotated = rotdig[torot:] + rotdig[:torot] |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3299 | return _dec_from_triple(self._sign, |
| 3300 | rotated.lstrip('0') or '0', self._exp) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3301 | |
| 3302 | def scaleb (self, other, context=None): |
| 3303 | """Returns self operand after adding the second value to its exp.""" |
| 3304 | if context is None: |
| 3305 | context = getcontext() |
| 3306 | |
| 3307 | ans = self._check_nans(other, context) |
| 3308 | if ans: |
| 3309 | return ans |
| 3310 | |
| 3311 | if other._exp != 0: |
| 3312 | return context._raise_error(InvalidOperation) |
| 3313 | liminf = -2 * (context.Emax + context.prec) |
| 3314 | limsup = 2 * (context.Emax + context.prec) |
| 3315 | if not (liminf <= int(other) <= limsup): |
| 3316 | return context._raise_error(InvalidOperation) |
| 3317 | |
| 3318 | if self._isinfinity(): |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 3319 | return Decimal(self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3320 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3321 | d = _dec_from_triple(self._sign, self._int, self._exp + int(other)) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3322 | d = d._fix(context) |
| 3323 | return d |
| 3324 | |
| 3325 | def shift(self, other, context=None): |
| 3326 | """Returns a shifted copy of self, value-of-other times.""" |
| 3327 | if context is None: |
| 3328 | context = getcontext() |
| 3329 | |
| 3330 | ans = self._check_nans(other, context) |
| 3331 | if ans: |
| 3332 | return ans |
| 3333 | |
| 3334 | if other._exp != 0: |
| 3335 | return context._raise_error(InvalidOperation) |
| 3336 | if not (-context.prec <= int(other) <= context.prec): |
| 3337 | return context._raise_error(InvalidOperation) |
| 3338 | |
| 3339 | if self._isinfinity(): |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 3340 | return Decimal(self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3341 | |
| 3342 | # get values, pad if necessary |
| 3343 | torot = int(other) |
| 3344 | if not torot: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 3345 | return Decimal(self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3346 | rotdig = self._int |
| 3347 | topad = context.prec - len(rotdig) |
| 3348 | if topad: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3349 | rotdig = '0'*topad + rotdig |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3350 | |
| 3351 | # let's shift! |
| 3352 | if torot < 0: |
| 3353 | rotated = rotdig[:torot] |
| 3354 | else: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3355 | rotated = rotdig + '0'*torot |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3356 | rotated = rotated[-context.prec:] |
| 3357 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3358 | return _dec_from_triple(self._sign, |
| 3359 | rotated.lstrip('0') or '0', self._exp) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3360 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3361 | # Support for pickling, copy, and deepcopy |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3362 | def __reduce__(self): |
| 3363 | return (self.__class__, (str(self),)) |
| 3364 | |
| 3365 | def __copy__(self): |
| 3366 | if type(self) == Decimal: |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 3367 | return self # I'm immutable; therefore I am my own clone |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3368 | return self.__class__(str(self)) |
| 3369 | |
| 3370 | def __deepcopy__(self, memo): |
| 3371 | if type(self) == Decimal: |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 3372 | return self # My components are also immutable |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3373 | return self.__class__(str(self)) |
| 3374 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3375 | def _dec_from_triple(sign, coefficient, exponent, special=False): |
| 3376 | """Create a decimal instance directly, without any validation, |
| 3377 | normalization (e.g. removal of leading zeros) or argument |
| 3378 | conversion. |
| 3379 | |
| 3380 | This function is for *internal use only*. |
| 3381 | """ |
| 3382 | |
| 3383 | self = object.__new__(Decimal) |
| 3384 | self._sign = sign |
| 3385 | self._int = coefficient |
| 3386 | self._exp = exponent |
| 3387 | self._is_special = special |
| 3388 | |
| 3389 | return self |
| 3390 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3391 | ##### Context class ####################################################### |
Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 3392 | |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 3393 | |
| 3394 | # get rounding method function: |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3395 | rounding_functions = [name for name in Decimal.__dict__.keys() |
| 3396 | if name.startswith('_round_')] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3397 | for name in rounding_functions: |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3398 | # 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] | 3399 | globalname = name[1:].upper() |
| 3400 | val = globals()[globalname] |
| 3401 | Decimal._pick_rounding_function[val] = name |
| 3402 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3403 | del name, val, globalname, rounding_functions |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3404 | |
Nick Coghlan | ced1218 | 2006-09-02 03:54:17 +0000 | [diff] [blame] | 3405 | class _ContextManager(object): |
Nick Coghlan | 8b6999b | 2006-08-31 12:00:43 +0000 | [diff] [blame] | 3406 | """Context manager class to support localcontext(). |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 3407 | |
Nick Coghlan | ced1218 | 2006-09-02 03:54:17 +0000 | [diff] [blame] | 3408 | Sets a copy of the supplied context in __enter__() and restores |
Nick Coghlan | 8b6999b | 2006-08-31 12:00:43 +0000 | [diff] [blame] | 3409 | the previous decimal context in __exit__() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 3410 | """ |
| 3411 | def __init__(self, new_context): |
Nick Coghlan | ced1218 | 2006-09-02 03:54:17 +0000 | [diff] [blame] | 3412 | self.new_context = new_context.copy() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 3413 | def __enter__(self): |
| 3414 | self.saved_context = getcontext() |
| 3415 | setcontext(self.new_context) |
| 3416 | return self.new_context |
| 3417 | def __exit__(self, t, v, tb): |
| 3418 | setcontext(self.saved_context) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 3419 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3420 | class Context(object): |
| 3421 | """Contains the context for a Decimal instance. |
| 3422 | |
| 3423 | Contains: |
| 3424 | prec - precision (for use in rounding, division, square roots..) |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3425 | rounding - rounding type (how you round) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3426 | _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round? |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3427 | traps - If traps[exception] = 1, then the exception is |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3428 | raised when it is caused. Otherwise, a value is |
| 3429 | substituted in. |
| 3430 | flags - When an exception is caused, flags[exception] is incremented. |
| 3431 | (Whether or not the trap_enabler is set) |
| 3432 | Should be reset by user of Decimal instance. |
Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 3433 | Emin - Minimum exponent |
| 3434 | Emax - Maximum exponent |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3435 | capitals - If 1, 1*10^1 is printed as 1E+1. |
| 3436 | If 0, printed as 1e1 |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 3437 | _clamp - If 1, change exponents if too high (Default 0) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3438 | """ |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3439 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3440 | def __init__(self, prec=None, rounding=None, |
Raymond Hettinger | abf8a56 | 2004-10-12 09:12:16 +0000 | [diff] [blame] | 3441 | traps=None, flags=None, |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3442 | _rounding_decision=None, |
Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 3443 | Emin=None, Emax=None, |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 3444 | capitals=None, _clamp=0, |
Raymond Hettinger | abf8a56 | 2004-10-12 09:12:16 +0000 | [diff] [blame] | 3445 | _ignored_flags=None): |
| 3446 | if flags is None: |
| 3447 | flags = [] |
| 3448 | if _ignored_flags is None: |
| 3449 | _ignored_flags = [] |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3450 | if not isinstance(flags, dict): |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 3451 | flags = dict([(s,s in flags) for s in _signals]) |
Raymond Hettinger | b91af52 | 2004-07-14 16:35:30 +0000 | [diff] [blame] | 3452 | del s |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3453 | if traps is not None and not isinstance(traps, dict): |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 3454 | traps = dict([(s,s in traps) for s in _signals]) |
Raymond Hettinger | b91af52 | 2004-07-14 16:35:30 +0000 | [diff] [blame] | 3455 | del s |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3456 | for name, val in locals().items(): |
| 3457 | if val is None: |
Raymond Hettinger | eb26084 | 2005-06-07 18:52:34 +0000 | [diff] [blame] | 3458 | setattr(self, name, _copy.copy(getattr(DefaultContext, name))) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3459 | else: |
| 3460 | setattr(self, name, val) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3461 | del self.self |
| 3462 | |
Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 3463 | def __repr__(self): |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3464 | """Show the current context.""" |
Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 3465 | s = [] |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3466 | s.append('Context(prec=%(prec)d, rounding=%(rounding)s, ' |
| 3467 | 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d' |
| 3468 | % vars(self)) |
| 3469 | names = [f.__name__ for f, v in self.flags.items() if v] |
| 3470 | s.append('flags=[' + ', '.join(names) + ']') |
| 3471 | names = [t.__name__ for t, v in self.traps.items() if v] |
| 3472 | s.append('traps=[' + ', '.join(names) + ']') |
Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 3473 | return ', '.join(s) + ')' |
| 3474 | |
Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 3475 | def clear_flags(self): |
| 3476 | """Reset all flags to zero""" |
| 3477 | for flag in self.flags: |
Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 3478 | self.flags[flag] = 0 |
Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 3479 | |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 3480 | def _shallow_copy(self): |
| 3481 | """Returns a shallow copy from self.""" |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3482 | nc = Context(self.prec, self.rounding, self.traps, self.flags, |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3483 | self._rounding_decision, self.Emin, self.Emax, |
| 3484 | self.capitals, self._clamp, self._ignored_flags) |
| 3485 | return nc |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 3486 | |
| 3487 | def copy(self): |
| 3488 | """Returns a deep copy from self.""" |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3489 | nc = Context(self.prec, self.rounding, self.traps.copy(), |
| 3490 | self.flags.copy(), self._rounding_decision, self.Emin, |
| 3491 | self.Emax, self.capitals, self._clamp, self._ignored_flags) |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 3492 | return nc |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3493 | __copy__ = copy |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3494 | |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 3495 | def _raise_error(self, condition, explanation = None, *args): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3496 | """Handles an error |
| 3497 | |
| 3498 | If the flag is in _ignored_flags, returns the default response. |
| 3499 | Otherwise, it increments the flag, then, if the corresponding |
| 3500 | trap_enabler is set, it reaises the exception. Otherwise, it returns |
| 3501 | the default value after incrementing the flag. |
| 3502 | """ |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 3503 | error = _condition_map.get(condition, condition) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3504 | if error in self._ignored_flags: |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3505 | # Don't touch the flag |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3506 | return error().handle(self, *args) |
| 3507 | |
| 3508 | self.flags[error] += 1 |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3509 | if not self.traps[error]: |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3510 | # The errors define how to handle themselves. |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 3511 | return condition().handle(self, *args) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3512 | |
| 3513 | # Errors should only be risked on copies of the context |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3514 | # self._ignored_flags = [] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3515 | raise error, explanation |
| 3516 | |
| 3517 | def _ignore_all_flags(self): |
| 3518 | """Ignore all flags, if they are raised""" |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 3519 | return self._ignore_flags(*_signals) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3520 | |
| 3521 | def _ignore_flags(self, *flags): |
| 3522 | """Ignore the flags, if they are raised""" |
| 3523 | # Do not mutate-- This way, copies of a context leave the original |
| 3524 | # alone. |
| 3525 | self._ignored_flags = (self._ignored_flags + list(flags)) |
| 3526 | return list(flags) |
| 3527 | |
| 3528 | def _regard_flags(self, *flags): |
| 3529 | """Stop ignoring the flags, if they are raised""" |
| 3530 | if flags and isinstance(flags[0], (tuple,list)): |
| 3531 | flags = flags[0] |
| 3532 | for flag in flags: |
| 3533 | self._ignored_flags.remove(flag) |
| 3534 | |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 3535 | def __hash__(self): |
| 3536 | """A Context cannot be hashed.""" |
| 3537 | # We inherit object.__hash__, so we must deny this explicitly |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3538 | raise TypeError("Cannot hash a Context.") |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 3539 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3540 | def Etiny(self): |
| 3541 | """Returns Etiny (= Emin - prec + 1)""" |
| 3542 | return int(self.Emin - self.prec + 1) |
| 3543 | |
| 3544 | def Etop(self): |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 3545 | """Returns maximum exponent (= Emax - prec + 1)""" |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3546 | return int(self.Emax - self.prec + 1) |
| 3547 | |
| 3548 | def _set_rounding_decision(self, type): |
| 3549 | """Sets the rounding decision. |
| 3550 | |
| 3551 | Sets the rounding decision, and returns the current (previous) |
| 3552 | rounding decision. Often used like: |
| 3553 | |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 3554 | context = context._shallow_copy() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3555 | # That so you don't change the calling context |
| 3556 | # if an error occurs in the middle (say DivisionImpossible is raised). |
| 3557 | |
| 3558 | rounding = context._set_rounding_decision(NEVER_ROUND) |
| 3559 | instance = instance / Decimal(2) |
| 3560 | context._set_rounding_decision(rounding) |
| 3561 | |
| 3562 | This will make it not round for that operation. |
| 3563 | """ |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 3564 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3565 | rounding = self._rounding_decision |
| 3566 | self._rounding_decision = type |
| 3567 | return rounding |
| 3568 | |
| 3569 | def _set_rounding(self, type): |
| 3570 | """Sets the rounding type. |
| 3571 | |
| 3572 | Sets the rounding type, and returns the current (previous) |
| 3573 | rounding type. Often used like: |
| 3574 | |
| 3575 | context = context.copy() |
| 3576 | # so you don't change the calling context |
| 3577 | # if an error occurs in the middle. |
| 3578 | rounding = context._set_rounding(ROUND_UP) |
| 3579 | val = self.__sub__(other, context=context) |
| 3580 | context._set_rounding(rounding) |
| 3581 | |
| 3582 | This will make it round up for that operation. |
| 3583 | """ |
| 3584 | rounding = self.rounding |
| 3585 | self.rounding= type |
| 3586 | return rounding |
| 3587 | |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 3588 | def create_decimal(self, num='0'): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3589 | """Creates a new Decimal instance but using self as context.""" |
| 3590 | d = Decimal(num, context=self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3591 | if d._isnan() and len(d._int) > self.prec - self._clamp: |
| 3592 | return self._raise_error(ConversionSyntax, |
| 3593 | "diagnostic info too long in NaN") |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 3594 | return d._fix(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3595 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3596 | # Methods |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3597 | def abs(self, a): |
| 3598 | """Returns the absolute value of the operand. |
| 3599 | |
| 3600 | If the operand is negative, the result is the same as using the minus |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3601 | operation on the operand. Otherwise, the result is the same as using |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3602 | the plus operation on the operand. |
| 3603 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3604 | >>> ExtendedContext.abs(Decimal('2.1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3605 | Decimal("2.1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3606 | >>> ExtendedContext.abs(Decimal('-100')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3607 | Decimal("100") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3608 | >>> ExtendedContext.abs(Decimal('101.5')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3609 | Decimal("101.5") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3610 | >>> ExtendedContext.abs(Decimal('-101.5')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3611 | Decimal("101.5") |
| 3612 | """ |
| 3613 | return a.__abs__(context=self) |
| 3614 | |
| 3615 | def add(self, a, b): |
| 3616 | """Return the sum of the two operands. |
| 3617 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3618 | >>> ExtendedContext.add(Decimal('12'), Decimal('7.00')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3619 | Decimal("19.00") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3620 | >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3621 | Decimal("1.02E+4") |
| 3622 | """ |
| 3623 | return a.__add__(b, context=self) |
| 3624 | |
| 3625 | def _apply(self, a): |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 3626 | return str(a._fix(self)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3627 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3628 | def canonical(self, a): |
| 3629 | """Returns the same Decimal object. |
| 3630 | |
| 3631 | As we do not have different encodings for the same number, the |
| 3632 | received object already is in its canonical form. |
| 3633 | |
| 3634 | >>> ExtendedContext.canonical(Decimal('2.50')) |
| 3635 | Decimal("2.50") |
| 3636 | """ |
| 3637 | return a.canonical(context=self) |
| 3638 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3639 | def compare(self, a, b): |
| 3640 | """Compares values numerically. |
| 3641 | |
| 3642 | If the signs of the operands differ, a value representing each operand |
| 3643 | ('-1' if the operand is less than zero, '0' if the operand is zero or |
| 3644 | negative zero, or '1' if the operand is greater than zero) is used in |
| 3645 | place of that operand for the comparison instead of the actual |
| 3646 | operand. |
| 3647 | |
| 3648 | The comparison is then effected by subtracting the second operand from |
| 3649 | the first and then returning a value according to the result of the |
| 3650 | subtraction: '-1' if the result is less than zero, '0' if the result is |
| 3651 | zero or negative zero, or '1' if the result is greater than zero. |
| 3652 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3653 | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3654 | Decimal("-1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3655 | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3656 | Decimal("0") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3657 | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3658 | Decimal("0") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3659 | >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3660 | Decimal("1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3661 | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3662 | Decimal("1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3663 | >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3664 | Decimal("-1") |
| 3665 | """ |
| 3666 | return a.compare(b, context=self) |
| 3667 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3668 | def compare_signal(self, a, b): |
| 3669 | """Compares the values of the two operands numerically. |
| 3670 | |
| 3671 | It's pretty much like compare(), but all NaNs signal, with signaling |
| 3672 | NaNs taking precedence over quiet NaNs. |
| 3673 | |
| 3674 | >>> c = ExtendedContext |
| 3675 | >>> c.compare_signal(Decimal('2.1'), Decimal('3')) |
| 3676 | Decimal("-1") |
| 3677 | >>> c.compare_signal(Decimal('2.1'), Decimal('2.1')) |
| 3678 | Decimal("0") |
| 3679 | >>> c.flags[InvalidOperation] = 0 |
| 3680 | >>> print c.flags[InvalidOperation] |
| 3681 | 0 |
| 3682 | >>> c.compare_signal(Decimal('NaN'), Decimal('2.1')) |
| 3683 | Decimal("NaN") |
| 3684 | >>> print c.flags[InvalidOperation] |
| 3685 | 1 |
| 3686 | >>> c.flags[InvalidOperation] = 0 |
| 3687 | >>> print c.flags[InvalidOperation] |
| 3688 | 0 |
| 3689 | >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1')) |
| 3690 | Decimal("NaN") |
| 3691 | >>> print c.flags[InvalidOperation] |
| 3692 | 1 |
| 3693 | """ |
| 3694 | return a.compare_signal(b, context=self) |
| 3695 | |
| 3696 | def compare_total(self, a, b): |
| 3697 | """Compares two operands using their abstract representation. |
| 3698 | |
| 3699 | This is not like the standard compare, which use their numerical |
| 3700 | value. Note that a total ordering is defined for all possible abstract |
| 3701 | representations. |
| 3702 | |
| 3703 | >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9')) |
| 3704 | Decimal("-1") |
| 3705 | >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12')) |
| 3706 | Decimal("-1") |
| 3707 | >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3')) |
| 3708 | Decimal("-1") |
| 3709 | >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30')) |
| 3710 | Decimal("0") |
| 3711 | >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300')) |
| 3712 | Decimal("1") |
| 3713 | >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN')) |
| 3714 | Decimal("-1") |
| 3715 | """ |
| 3716 | return a.compare_total(b) |
| 3717 | |
| 3718 | def compare_total_mag(self, a, b): |
| 3719 | """Compares two operands using their abstract representation ignoring sign. |
| 3720 | |
| 3721 | Like compare_total, but with operand's sign ignored and assumed to be 0. |
| 3722 | """ |
| 3723 | return a.compare_total_mag(b) |
| 3724 | |
| 3725 | def copy_abs(self, a): |
| 3726 | """Returns a copy of the operand with the sign set to 0. |
| 3727 | |
| 3728 | >>> ExtendedContext.copy_abs(Decimal('2.1')) |
| 3729 | Decimal("2.1") |
| 3730 | >>> ExtendedContext.copy_abs(Decimal('-100')) |
| 3731 | Decimal("100") |
| 3732 | """ |
| 3733 | return a.copy_abs() |
| 3734 | |
| 3735 | def copy_decimal(self, a): |
| 3736 | """Returns a copy of the decimal objet. |
| 3737 | |
| 3738 | >>> ExtendedContext.copy_decimal(Decimal('2.1')) |
| 3739 | Decimal("2.1") |
| 3740 | >>> ExtendedContext.copy_decimal(Decimal('-1.00')) |
| 3741 | Decimal("-1.00") |
| 3742 | """ |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 3743 | return Decimal(a) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3744 | |
| 3745 | def copy_negate(self, a): |
| 3746 | """Returns a copy of the operand with the sign inverted. |
| 3747 | |
| 3748 | >>> ExtendedContext.copy_negate(Decimal('101.5')) |
| 3749 | Decimal("-101.5") |
| 3750 | >>> ExtendedContext.copy_negate(Decimal('-101.5')) |
| 3751 | Decimal("101.5") |
| 3752 | """ |
| 3753 | return a.copy_negate() |
| 3754 | |
| 3755 | def copy_sign(self, a, b): |
| 3756 | """Copies the second operand's sign to the first one. |
| 3757 | |
| 3758 | In detail, it returns a copy of the first operand with the sign |
| 3759 | equal to the sign of the second operand. |
| 3760 | |
| 3761 | >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33')) |
| 3762 | Decimal("1.50") |
| 3763 | >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33')) |
| 3764 | Decimal("1.50") |
| 3765 | >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33')) |
| 3766 | Decimal("-1.50") |
| 3767 | >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33')) |
| 3768 | Decimal("-1.50") |
| 3769 | """ |
| 3770 | return a.copy_sign(b) |
| 3771 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3772 | def divide(self, a, b): |
| 3773 | """Decimal division in a specified context. |
| 3774 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3775 | >>> ExtendedContext.divide(Decimal('1'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3776 | Decimal("0.333333333") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3777 | >>> ExtendedContext.divide(Decimal('2'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3778 | Decimal("0.666666667") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3779 | >>> ExtendedContext.divide(Decimal('5'), Decimal('2')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3780 | Decimal("2.5") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3781 | >>> ExtendedContext.divide(Decimal('1'), Decimal('10')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3782 | Decimal("0.1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3783 | >>> ExtendedContext.divide(Decimal('12'), Decimal('12')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3784 | Decimal("1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3785 | >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3786 | Decimal("4.00") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3787 | >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3788 | Decimal("1.20") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3789 | >>> ExtendedContext.divide(Decimal('1000'), Decimal('100')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3790 | Decimal("10") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3791 | >>> ExtendedContext.divide(Decimal('1000'), Decimal('1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3792 | Decimal("1000") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3793 | >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3794 | Decimal("1.20E+6") |
| 3795 | """ |
| 3796 | return a.__div__(b, context=self) |
| 3797 | |
| 3798 | def divide_int(self, a, b): |
| 3799 | """Divides two numbers and returns the integer part of the result. |
| 3800 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3801 | >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3802 | Decimal("0") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3803 | >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3804 | Decimal("3") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3805 | >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3806 | Decimal("3") |
| 3807 | """ |
| 3808 | return a.__floordiv__(b, context=self) |
| 3809 | |
| 3810 | def divmod(self, a, b): |
| 3811 | return a.__divmod__(b, context=self) |
| 3812 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3813 | def exp(self, a): |
| 3814 | """Returns e ** a. |
| 3815 | |
| 3816 | >>> c = ExtendedContext.copy() |
| 3817 | >>> c.Emin = -999 |
| 3818 | >>> c.Emax = 999 |
| 3819 | >>> c.exp(Decimal('-Infinity')) |
| 3820 | Decimal("0") |
| 3821 | >>> c.exp(Decimal('-1')) |
| 3822 | Decimal("0.367879441") |
| 3823 | >>> c.exp(Decimal('0')) |
| 3824 | Decimal("1") |
| 3825 | >>> c.exp(Decimal('1')) |
| 3826 | Decimal("2.71828183") |
| 3827 | >>> c.exp(Decimal('0.693147181')) |
| 3828 | Decimal("2.00000000") |
| 3829 | >>> c.exp(Decimal('+Infinity')) |
| 3830 | Decimal("Infinity") |
| 3831 | """ |
| 3832 | return a.exp(context=self) |
| 3833 | |
| 3834 | def fma(self, a, b, c): |
| 3835 | """Returns a multiplied by b, plus c. |
| 3836 | |
| 3837 | The first two operands are multiplied together, using multiply, |
| 3838 | the third operand is then added to the result of that |
| 3839 | multiplication, using add, all with only one final rounding. |
| 3840 | |
| 3841 | >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7')) |
| 3842 | Decimal("22") |
| 3843 | >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7')) |
| 3844 | Decimal("-8") |
| 3845 | >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578')) |
| 3846 | Decimal("1.38435736E+12") |
| 3847 | """ |
| 3848 | return a.fma(b, c, context=self) |
| 3849 | |
| 3850 | def is_canonical(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3851 | """Return True if the operand is canonical; otherwise return False. |
| 3852 | |
| 3853 | Currently, the encoding of a Decimal instance is always |
| 3854 | canonical, so this method returns True for any Decimal. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3855 | |
| 3856 | >>> ExtendedContext.is_canonical(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3857 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3858 | """ |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3859 | return a.is_canonical() |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3860 | |
| 3861 | def is_finite(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3862 | """Return True if the operand is finite; otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3863 | |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3864 | A Decimal instance is considered finite if it is neither |
| 3865 | infinite nor a NaN. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3866 | |
| 3867 | >>> ExtendedContext.is_finite(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3868 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3869 | >>> ExtendedContext.is_finite(Decimal('-0.3')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3870 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3871 | >>> ExtendedContext.is_finite(Decimal('0')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3872 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3873 | >>> ExtendedContext.is_finite(Decimal('Inf')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3874 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3875 | >>> ExtendedContext.is_finite(Decimal('NaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3876 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3877 | """ |
| 3878 | return a.is_finite() |
| 3879 | |
| 3880 | def is_infinite(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3881 | """Return True if the operand is infinite; otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3882 | |
| 3883 | >>> ExtendedContext.is_infinite(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3884 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3885 | >>> ExtendedContext.is_infinite(Decimal('-Inf')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3886 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3887 | >>> ExtendedContext.is_infinite(Decimal('NaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3888 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3889 | """ |
| 3890 | return a.is_infinite() |
| 3891 | |
| 3892 | def is_nan(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3893 | """Return True if the operand is a qNaN or sNaN; |
| 3894 | otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3895 | |
| 3896 | >>> ExtendedContext.is_nan(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3897 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3898 | >>> ExtendedContext.is_nan(Decimal('NaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3899 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3900 | >>> ExtendedContext.is_nan(Decimal('-sNaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3901 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3902 | """ |
| 3903 | return a.is_nan() |
| 3904 | |
| 3905 | def is_normal(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3906 | """Return True if the operand is a normal number; |
| 3907 | otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3908 | |
| 3909 | >>> c = ExtendedContext.copy() |
| 3910 | >>> c.Emin = -999 |
| 3911 | >>> c.Emax = 999 |
| 3912 | >>> c.is_normal(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3913 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3914 | >>> c.is_normal(Decimal('0.1E-999')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3915 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3916 | >>> c.is_normal(Decimal('0.00')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3917 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3918 | >>> c.is_normal(Decimal('-Inf')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3919 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3920 | >>> c.is_normal(Decimal('NaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3921 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3922 | """ |
| 3923 | return a.is_normal(context=self) |
| 3924 | |
| 3925 | def is_qnan(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3926 | """Return True if the operand is a quiet NaN; otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3927 | |
| 3928 | >>> ExtendedContext.is_qnan(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3929 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3930 | >>> ExtendedContext.is_qnan(Decimal('NaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3931 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3932 | >>> ExtendedContext.is_qnan(Decimal('sNaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3933 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3934 | """ |
| 3935 | return a.is_qnan() |
| 3936 | |
| 3937 | def is_signed(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3938 | """Return True if the operand is negative; otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3939 | |
| 3940 | >>> ExtendedContext.is_signed(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3941 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3942 | >>> ExtendedContext.is_signed(Decimal('-12')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3943 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3944 | >>> ExtendedContext.is_signed(Decimal('-0')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3945 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3946 | """ |
| 3947 | return a.is_signed() |
| 3948 | |
| 3949 | def is_snan(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3950 | """Return True if the operand is a signaling NaN; |
| 3951 | otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3952 | |
| 3953 | >>> ExtendedContext.is_snan(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3954 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3955 | >>> ExtendedContext.is_snan(Decimal('NaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3956 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3957 | >>> ExtendedContext.is_snan(Decimal('sNaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3958 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3959 | """ |
| 3960 | return a.is_snan() |
| 3961 | |
| 3962 | def is_subnormal(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3963 | """Return True if the operand is subnormal; otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3964 | |
| 3965 | >>> c = ExtendedContext.copy() |
| 3966 | >>> c.Emin = -999 |
| 3967 | >>> c.Emax = 999 |
| 3968 | >>> c.is_subnormal(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3969 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3970 | >>> c.is_subnormal(Decimal('0.1E-999')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3971 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3972 | >>> c.is_subnormal(Decimal('0.00')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3973 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3974 | >>> c.is_subnormal(Decimal('-Inf')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3975 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3976 | >>> c.is_subnormal(Decimal('NaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3977 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3978 | """ |
| 3979 | return a.is_subnormal(context=self) |
| 3980 | |
| 3981 | def is_zero(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3982 | """Return True if the operand is a zero; otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3983 | |
| 3984 | >>> ExtendedContext.is_zero(Decimal('0')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3985 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3986 | >>> ExtendedContext.is_zero(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3987 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3988 | >>> ExtendedContext.is_zero(Decimal('-0E+2')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 3989 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3990 | """ |
| 3991 | return a.is_zero() |
| 3992 | |
| 3993 | def ln(self, a): |
| 3994 | """Returns the natural (base e) logarithm of the operand. |
| 3995 | |
| 3996 | >>> c = ExtendedContext.copy() |
| 3997 | >>> c.Emin = -999 |
| 3998 | >>> c.Emax = 999 |
| 3999 | >>> c.ln(Decimal('0')) |
| 4000 | Decimal("-Infinity") |
| 4001 | >>> c.ln(Decimal('1.000')) |
| 4002 | Decimal("0") |
| 4003 | >>> c.ln(Decimal('2.71828183')) |
| 4004 | Decimal("1.00000000") |
| 4005 | >>> c.ln(Decimal('10')) |
| 4006 | Decimal("2.30258509") |
| 4007 | >>> c.ln(Decimal('+Infinity')) |
| 4008 | Decimal("Infinity") |
| 4009 | """ |
| 4010 | return a.ln(context=self) |
| 4011 | |
| 4012 | def log10(self, a): |
| 4013 | """Returns the base 10 logarithm of the operand. |
| 4014 | |
| 4015 | >>> c = ExtendedContext.copy() |
| 4016 | >>> c.Emin = -999 |
| 4017 | >>> c.Emax = 999 |
| 4018 | >>> c.log10(Decimal('0')) |
| 4019 | Decimal("-Infinity") |
| 4020 | >>> c.log10(Decimal('0.001')) |
| 4021 | Decimal("-3") |
| 4022 | >>> c.log10(Decimal('1.000')) |
| 4023 | Decimal("0") |
| 4024 | >>> c.log10(Decimal('2')) |
| 4025 | Decimal("0.301029996") |
| 4026 | >>> c.log10(Decimal('10')) |
| 4027 | Decimal("1") |
| 4028 | >>> c.log10(Decimal('70')) |
| 4029 | Decimal("1.84509804") |
| 4030 | >>> c.log10(Decimal('+Infinity')) |
| 4031 | Decimal("Infinity") |
| 4032 | """ |
| 4033 | return a.log10(context=self) |
| 4034 | |
| 4035 | def logb(self, a): |
| 4036 | """ Returns the exponent of the magnitude of the operand's MSD. |
| 4037 | |
| 4038 | The result is the integer which is the exponent of the magnitude |
| 4039 | of the most significant digit of the operand (as though the |
| 4040 | operand were truncated to a single digit while maintaining the |
| 4041 | value of that digit and without limiting the resulting exponent). |
| 4042 | |
| 4043 | >>> ExtendedContext.logb(Decimal('250')) |
| 4044 | Decimal("2") |
| 4045 | >>> ExtendedContext.logb(Decimal('2.50')) |
| 4046 | Decimal("0") |
| 4047 | >>> ExtendedContext.logb(Decimal('0.03')) |
| 4048 | Decimal("-2") |
| 4049 | >>> ExtendedContext.logb(Decimal('0')) |
| 4050 | Decimal("-Infinity") |
| 4051 | """ |
| 4052 | return a.logb(context=self) |
| 4053 | |
| 4054 | def logical_and(self, a, b): |
| 4055 | """Applies the logical operation 'and' between each operand's digits. |
| 4056 | |
| 4057 | The operands must be both logical numbers. |
| 4058 | |
| 4059 | >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0')) |
| 4060 | Decimal("0") |
| 4061 | >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1')) |
| 4062 | Decimal("0") |
| 4063 | >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0')) |
| 4064 | Decimal("0") |
| 4065 | >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1')) |
| 4066 | Decimal("1") |
| 4067 | >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010')) |
| 4068 | Decimal("1000") |
| 4069 | >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10')) |
| 4070 | Decimal("10") |
| 4071 | """ |
| 4072 | return a.logical_and(b, context=self) |
| 4073 | |
| 4074 | def logical_invert(self, a): |
| 4075 | """Invert all the digits in the operand. |
| 4076 | |
| 4077 | The operand must be a logical number. |
| 4078 | |
| 4079 | >>> ExtendedContext.logical_invert(Decimal('0')) |
| 4080 | Decimal("111111111") |
| 4081 | >>> ExtendedContext.logical_invert(Decimal('1')) |
| 4082 | Decimal("111111110") |
| 4083 | >>> ExtendedContext.logical_invert(Decimal('111111111')) |
| 4084 | Decimal("0") |
| 4085 | >>> ExtendedContext.logical_invert(Decimal('101010101')) |
| 4086 | Decimal("10101010") |
| 4087 | """ |
| 4088 | return a.logical_invert(context=self) |
| 4089 | |
| 4090 | def logical_or(self, a, b): |
| 4091 | """Applies the logical operation 'or' between each operand's digits. |
| 4092 | |
| 4093 | The operands must be both logical numbers. |
| 4094 | |
| 4095 | >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0')) |
| 4096 | Decimal("0") |
| 4097 | >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1')) |
| 4098 | Decimal("1") |
| 4099 | >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0')) |
| 4100 | Decimal("1") |
| 4101 | >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1')) |
| 4102 | Decimal("1") |
| 4103 | >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010')) |
| 4104 | Decimal("1110") |
| 4105 | >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10')) |
| 4106 | Decimal("1110") |
| 4107 | """ |
| 4108 | return a.logical_or(b, context=self) |
| 4109 | |
| 4110 | def logical_xor(self, a, b): |
| 4111 | """Applies the logical operation 'xor' between each operand's digits. |
| 4112 | |
| 4113 | The operands must be both logical numbers. |
| 4114 | |
| 4115 | >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0')) |
| 4116 | Decimal("0") |
| 4117 | >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1')) |
| 4118 | Decimal("1") |
| 4119 | >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0')) |
| 4120 | Decimal("1") |
| 4121 | >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1')) |
| 4122 | Decimal("0") |
| 4123 | >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010')) |
| 4124 | Decimal("110") |
| 4125 | >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10')) |
| 4126 | Decimal("1101") |
| 4127 | """ |
| 4128 | return a.logical_xor(b, context=self) |
| 4129 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4130 | def max(self, a,b): |
| 4131 | """max compares two values numerically and returns the maximum. |
| 4132 | |
| 4133 | If either operand is a NaN then the general rules apply. |
| 4134 | Otherwise, the operands are compared as as though by the compare |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 4135 | operation. If they are numerically equal then the left-hand operand |
| 4136 | is chosen as the result. Otherwise the maximum (closer to positive |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4137 | infinity) of the two operands is chosen as the result. |
| 4138 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4139 | >>> ExtendedContext.max(Decimal('3'), Decimal('2')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4140 | Decimal("3") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4141 | >>> ExtendedContext.max(Decimal('-10'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4142 | Decimal("3") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4143 | >>> ExtendedContext.max(Decimal('1.0'), Decimal('1')) |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 4144 | Decimal("1") |
| 4145 | >>> ExtendedContext.max(Decimal('7'), Decimal('NaN')) |
| 4146 | Decimal("7") |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4147 | """ |
| 4148 | return a.max(b, context=self) |
| 4149 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4150 | def max_mag(self, a, b): |
| 4151 | """Compares the values numerically with their sign ignored.""" |
| 4152 | return a.max_mag(b, context=self) |
| 4153 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4154 | def min(self, a,b): |
| 4155 | """min compares two values numerically and returns the minimum. |
| 4156 | |
| 4157 | If either operand is a NaN then the general rules apply. |
| 4158 | Otherwise, the operands are compared as as though by the compare |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 4159 | operation. If they are numerically equal then the left-hand operand |
| 4160 | is chosen as the result. Otherwise the minimum (closer to negative |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4161 | infinity) of the two operands is chosen as the result. |
| 4162 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4163 | >>> ExtendedContext.min(Decimal('3'), Decimal('2')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4164 | Decimal("2") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4165 | >>> ExtendedContext.min(Decimal('-10'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4166 | Decimal("-10") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4167 | >>> ExtendedContext.min(Decimal('1.0'), Decimal('1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4168 | Decimal("1.0") |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 4169 | >>> ExtendedContext.min(Decimal('7'), Decimal('NaN')) |
| 4170 | Decimal("7") |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4171 | """ |
| 4172 | return a.min(b, context=self) |
| 4173 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4174 | def min_mag(self, a, b): |
| 4175 | """Compares the values numerically with their sign ignored.""" |
| 4176 | return a.min_mag(b, context=self) |
| 4177 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4178 | def minus(self, a): |
| 4179 | """Minus corresponds to unary prefix minus in Python. |
| 4180 | |
| 4181 | The operation is evaluated using the same rules as subtract; the |
| 4182 | operation minus(a) is calculated as subtract('0', a) where the '0' |
| 4183 | has the same exponent as the operand. |
| 4184 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4185 | >>> ExtendedContext.minus(Decimal('1.3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4186 | Decimal("-1.3") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4187 | >>> ExtendedContext.minus(Decimal('-1.3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4188 | Decimal("1.3") |
| 4189 | """ |
| 4190 | return a.__neg__(context=self) |
| 4191 | |
| 4192 | def multiply(self, a, b): |
| 4193 | """multiply multiplies two operands. |
| 4194 | |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 4195 | If either operand is a special value then the general rules apply. |
| 4196 | Otherwise, the operands are multiplied together ('long multiplication'), |
| 4197 | resulting in a number which may be as long as the sum of the lengths |
| 4198 | of the two operands. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4199 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4200 | >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4201 | Decimal("3.60") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4202 | >>> ExtendedContext.multiply(Decimal('7'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4203 | Decimal("21") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4204 | >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4205 | Decimal("0.72") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4206 | >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4207 | Decimal("-0.0") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4208 | >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4209 | Decimal("4.28135971E+11") |
| 4210 | """ |
| 4211 | return a.__mul__(b, context=self) |
| 4212 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4213 | def next_minus(self, a): |
| 4214 | """Returns the largest representable number smaller than a. |
| 4215 | |
| 4216 | >>> c = ExtendedContext.copy() |
| 4217 | >>> c.Emin = -999 |
| 4218 | >>> c.Emax = 999 |
| 4219 | >>> ExtendedContext.next_minus(Decimal('1')) |
| 4220 | Decimal("0.999999999") |
| 4221 | >>> c.next_minus(Decimal('1E-1007')) |
| 4222 | Decimal("0E-1007") |
| 4223 | >>> ExtendedContext.next_minus(Decimal('-1.00000003')) |
| 4224 | Decimal("-1.00000004") |
| 4225 | >>> c.next_minus(Decimal('Infinity')) |
| 4226 | Decimal("9.99999999E+999") |
| 4227 | """ |
| 4228 | return a.next_minus(context=self) |
| 4229 | |
| 4230 | def next_plus(self, a): |
| 4231 | """Returns the smallest representable number larger than a. |
| 4232 | |
| 4233 | >>> c = ExtendedContext.copy() |
| 4234 | >>> c.Emin = -999 |
| 4235 | >>> c.Emax = 999 |
| 4236 | >>> ExtendedContext.next_plus(Decimal('1')) |
| 4237 | Decimal("1.00000001") |
| 4238 | >>> c.next_plus(Decimal('-1E-1007')) |
| 4239 | Decimal("-0E-1007") |
| 4240 | >>> ExtendedContext.next_plus(Decimal('-1.00000003')) |
| 4241 | Decimal("-1.00000002") |
| 4242 | >>> c.next_plus(Decimal('-Infinity')) |
| 4243 | Decimal("-9.99999999E+999") |
| 4244 | """ |
| 4245 | return a.next_plus(context=self) |
| 4246 | |
| 4247 | def next_toward(self, a, b): |
| 4248 | """Returns the number closest to a, in direction towards b. |
| 4249 | |
| 4250 | The result is the closest representable number from the first |
| 4251 | operand (but not the first operand) that is in the direction |
| 4252 | towards the second operand, unless the operands have the same |
| 4253 | value. |
| 4254 | |
| 4255 | >>> c = ExtendedContext.copy() |
| 4256 | >>> c.Emin = -999 |
| 4257 | >>> c.Emax = 999 |
| 4258 | >>> c.next_toward(Decimal('1'), Decimal('2')) |
| 4259 | Decimal("1.00000001") |
| 4260 | >>> c.next_toward(Decimal('-1E-1007'), Decimal('1')) |
| 4261 | Decimal("-0E-1007") |
| 4262 | >>> c.next_toward(Decimal('-1.00000003'), Decimal('0')) |
| 4263 | Decimal("-1.00000002") |
| 4264 | >>> c.next_toward(Decimal('1'), Decimal('0')) |
| 4265 | Decimal("0.999999999") |
| 4266 | >>> c.next_toward(Decimal('1E-1007'), Decimal('-100')) |
| 4267 | Decimal("0E-1007") |
| 4268 | >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10')) |
| 4269 | Decimal("-1.00000004") |
| 4270 | >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000')) |
| 4271 | Decimal("-0.00") |
| 4272 | """ |
| 4273 | return a.next_toward(b, context=self) |
| 4274 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4275 | def normalize(self, a): |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 4276 | """normalize reduces an operand to its simplest form. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4277 | |
| 4278 | Essentially a plus operation with all trailing zeros removed from the |
| 4279 | result. |
| 4280 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4281 | >>> ExtendedContext.normalize(Decimal('2.1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4282 | Decimal("2.1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4283 | >>> ExtendedContext.normalize(Decimal('-2.0')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4284 | Decimal("-2") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4285 | >>> ExtendedContext.normalize(Decimal('1.200')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4286 | Decimal("1.2") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4287 | >>> ExtendedContext.normalize(Decimal('-120')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4288 | Decimal("-1.2E+2") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4289 | >>> ExtendedContext.normalize(Decimal('120.00')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4290 | Decimal("1.2E+2") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4291 | >>> ExtendedContext.normalize(Decimal('0.00')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4292 | Decimal("0") |
| 4293 | """ |
| 4294 | return a.normalize(context=self) |
| 4295 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4296 | def number_class(self, a): |
| 4297 | """Returns an indication of the class of the operand. |
| 4298 | |
| 4299 | The class is one of the following strings: |
| 4300 | -sNaN |
| 4301 | -NaN |
| 4302 | -Infinity |
| 4303 | -Normal |
| 4304 | -Subnormal |
| 4305 | -Zero |
| 4306 | +Zero |
| 4307 | +Subnormal |
| 4308 | +Normal |
| 4309 | +Infinity |
| 4310 | |
| 4311 | >>> c = Context(ExtendedContext) |
| 4312 | >>> c.Emin = -999 |
| 4313 | >>> c.Emax = 999 |
| 4314 | >>> c.number_class(Decimal('Infinity')) |
| 4315 | '+Infinity' |
| 4316 | >>> c.number_class(Decimal('1E-10')) |
| 4317 | '+Normal' |
| 4318 | >>> c.number_class(Decimal('2.50')) |
| 4319 | '+Normal' |
| 4320 | >>> c.number_class(Decimal('0.1E-999')) |
| 4321 | '+Subnormal' |
| 4322 | >>> c.number_class(Decimal('0')) |
| 4323 | '+Zero' |
| 4324 | >>> c.number_class(Decimal('-0')) |
| 4325 | '-Zero' |
| 4326 | >>> c.number_class(Decimal('-0.1E-999')) |
| 4327 | '-Subnormal' |
| 4328 | >>> c.number_class(Decimal('-1E-10')) |
| 4329 | '-Normal' |
| 4330 | >>> c.number_class(Decimal('-2.50')) |
| 4331 | '-Normal' |
| 4332 | >>> c.number_class(Decimal('-Infinity')) |
| 4333 | '-Infinity' |
| 4334 | >>> c.number_class(Decimal('NaN')) |
| 4335 | 'NaN' |
| 4336 | >>> c.number_class(Decimal('-NaN')) |
| 4337 | 'NaN' |
| 4338 | >>> c.number_class(Decimal('sNaN')) |
| 4339 | 'sNaN' |
| 4340 | """ |
| 4341 | return a.number_class(context=self) |
| 4342 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4343 | def plus(self, a): |
| 4344 | """Plus corresponds to unary prefix plus in Python. |
| 4345 | |
| 4346 | The operation is evaluated using the same rules as add; the |
| 4347 | operation plus(a) is calculated as add('0', a) where the '0' |
| 4348 | has the same exponent as the operand. |
| 4349 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4350 | >>> ExtendedContext.plus(Decimal('1.3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4351 | Decimal("1.3") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4352 | >>> ExtendedContext.plus(Decimal('-1.3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4353 | Decimal("-1.3") |
| 4354 | """ |
| 4355 | return a.__pos__(context=self) |
| 4356 | |
| 4357 | def power(self, a, b, modulo=None): |
| 4358 | """Raises a to the power of b, to modulo if given. |
| 4359 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4360 | With two arguments, compute a**b. If a is negative then b |
| 4361 | must be integral. The result will be inexact unless b is |
| 4362 | integral and the result is finite and can be expressed exactly |
| 4363 | in 'precision' digits. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4364 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4365 | With three arguments, compute (a**b) % modulo. For the |
| 4366 | three argument form, the following restrictions on the |
| 4367 | arguments hold: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4368 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4369 | - all three arguments must be integral |
| 4370 | - b must be nonnegative |
| 4371 | - at least one of a or b must be nonzero |
| 4372 | - modulo must be nonzero and have at most 'precision' digits |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4373 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4374 | The result of pow(a, b, modulo) is identical to the result |
| 4375 | that would be obtained by computing (a**b) % modulo with |
| 4376 | unbounded precision, but is computed more efficiently. It is |
| 4377 | always exact. |
| 4378 | |
| 4379 | >>> c = ExtendedContext.copy() |
| 4380 | >>> c.Emin = -999 |
| 4381 | >>> c.Emax = 999 |
| 4382 | >>> c.power(Decimal('2'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4383 | Decimal("8") |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4384 | >>> c.power(Decimal('-2'), Decimal('3')) |
| 4385 | Decimal("-8") |
| 4386 | >>> c.power(Decimal('2'), Decimal('-3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4387 | Decimal("0.125") |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4388 | >>> c.power(Decimal('1.7'), Decimal('8')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4389 | Decimal("69.7575744") |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4390 | >>> c.power(Decimal('10'), Decimal('0.301029996')) |
| 4391 | Decimal("2.00000000") |
| 4392 | >>> c.power(Decimal('Infinity'), Decimal('-1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4393 | Decimal("0") |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4394 | >>> c.power(Decimal('Infinity'), Decimal('0')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4395 | Decimal("1") |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4396 | >>> c.power(Decimal('Infinity'), Decimal('1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4397 | Decimal("Infinity") |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4398 | >>> c.power(Decimal('-Infinity'), Decimal('-1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4399 | Decimal("-0") |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4400 | >>> c.power(Decimal('-Infinity'), Decimal('0')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4401 | Decimal("1") |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4402 | >>> c.power(Decimal('-Infinity'), Decimal('1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4403 | Decimal("-Infinity") |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4404 | >>> c.power(Decimal('-Infinity'), Decimal('2')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4405 | Decimal("Infinity") |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4406 | >>> c.power(Decimal('0'), Decimal('0')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4407 | Decimal("NaN") |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4408 | |
| 4409 | >>> c.power(Decimal('3'), Decimal('7'), Decimal('16')) |
| 4410 | Decimal("11") |
| 4411 | >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16')) |
| 4412 | Decimal("-11") |
| 4413 | >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16')) |
| 4414 | Decimal("1") |
| 4415 | >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16')) |
| 4416 | Decimal("11") |
| 4417 | >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789')) |
| 4418 | Decimal("11729830") |
| 4419 | >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729')) |
| 4420 | Decimal("-0") |
| 4421 | >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537')) |
| 4422 | Decimal("1") |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4423 | """ |
| 4424 | return a.__pow__(b, modulo, context=self) |
| 4425 | |
| 4426 | def quantize(self, a, b): |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 4427 | """Returns a value equal to 'a' (rounded), having the exponent of 'b'. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4428 | |
| 4429 | The coefficient of the result is derived from that of the left-hand |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 4430 | operand. It may be rounded using the current rounding setting (if the |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4431 | exponent is being increased), multiplied by a positive power of ten (if |
| 4432 | the exponent is being decreased), or is unchanged (if the exponent is |
| 4433 | already equal to that of the right-hand operand). |
| 4434 | |
| 4435 | Unlike other operations, if the length of the coefficient after the |
| 4436 | quantize operation would be greater than precision then an Invalid |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 4437 | operation condition is raised. This guarantees that, unless there is |
| 4438 | 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] | 4439 | equal to that of the right-hand operand. |
| 4440 | |
| 4441 | Also unlike other operations, quantize will never raise Underflow, even |
| 4442 | if the result is subnormal and inexact. |
| 4443 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4444 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4445 | Decimal("2.170") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4446 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4447 | Decimal("2.17") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4448 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4449 | Decimal("2.2") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4450 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4451 | Decimal("2") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4452 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4453 | Decimal("0E+1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4454 | >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4455 | Decimal("-Infinity") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4456 | >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4457 | Decimal("NaN") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4458 | >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4459 | Decimal("-0") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4460 | >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4461 | Decimal("-0E+5") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4462 | >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4463 | Decimal("NaN") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4464 | >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4465 | Decimal("NaN") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4466 | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4467 | Decimal("217.0") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4468 | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4469 | Decimal("217") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4470 | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4471 | Decimal("2.2E+2") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4472 | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4473 | Decimal("2E+2") |
| 4474 | """ |
| 4475 | return a.quantize(b, context=self) |
| 4476 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4477 | def radix(self): |
| 4478 | """Just returns 10, as this is Decimal, :) |
| 4479 | |
| 4480 | >>> ExtendedContext.radix() |
| 4481 | Decimal("10") |
| 4482 | """ |
| 4483 | return Decimal(10) |
| 4484 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4485 | def remainder(self, a, b): |
| 4486 | """Returns the remainder from integer division. |
| 4487 | |
| 4488 | The result is the residue of the dividend after the operation of |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 4489 | calculating integer division as described for divide-integer, rounded |
Neal Norwitz | 0d4c06e | 2007-04-25 06:30:05 +0000 | [diff] [blame] | 4490 | to precision digits if necessary. The sign of the result, if |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 4491 | non-zero, is the same as that of the original dividend. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4492 | |
| 4493 | This operation will fail under the same conditions as integer division |
| 4494 | (that is, if integer division on the same two operands would fail, the |
| 4495 | remainder cannot be calculated). |
| 4496 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4497 | >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4498 | Decimal("2.1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4499 | >>> ExtendedContext.remainder(Decimal('10'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4500 | Decimal("1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4501 | >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4502 | Decimal("-1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4503 | >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4504 | Decimal("0.2") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4505 | >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4506 | Decimal("0.1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4507 | >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4508 | Decimal("1.0") |
| 4509 | """ |
| 4510 | return a.__mod__(b, context=self) |
| 4511 | |
| 4512 | def remainder_near(self, a, b): |
| 4513 | """Returns to be "a - b * n", where n is the integer nearest the exact |
| 4514 | value of "x / b" (if two integers are equally near then the even one |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 4515 | 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] | 4516 | sign of a. |
| 4517 | |
| 4518 | This operation will fail under the same conditions as integer division |
| 4519 | (that is, if integer division on the same two operands would fail, the |
| 4520 | remainder cannot be calculated). |
| 4521 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4522 | >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4523 | Decimal("-0.9") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4524 | >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4525 | Decimal("-2") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4526 | >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4527 | Decimal("1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4528 | >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4529 | Decimal("-1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4530 | >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4531 | Decimal("0.2") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4532 | >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4533 | Decimal("0.1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4534 | >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4535 | Decimal("-0.3") |
| 4536 | """ |
| 4537 | return a.remainder_near(b, context=self) |
| 4538 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4539 | def rotate(self, a, b): |
| 4540 | """Returns a rotated copy of a, b times. |
| 4541 | |
| 4542 | The coefficient of the result is a rotated copy of the digits in |
| 4543 | the coefficient of the first operand. The number of places of |
| 4544 | rotation is taken from the absolute value of the second operand, |
| 4545 | with the rotation being to the left if the second operand is |
| 4546 | positive or to the right otherwise. |
| 4547 | |
| 4548 | >>> ExtendedContext.rotate(Decimal('34'), Decimal('8')) |
| 4549 | Decimal("400000003") |
| 4550 | >>> ExtendedContext.rotate(Decimal('12'), Decimal('9')) |
| 4551 | Decimal("12") |
| 4552 | >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2')) |
| 4553 | Decimal("891234567") |
| 4554 | >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0')) |
| 4555 | Decimal("123456789") |
| 4556 | >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2')) |
| 4557 | Decimal("345678912") |
| 4558 | """ |
| 4559 | return a.rotate(b, context=self) |
| 4560 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4561 | def same_quantum(self, a, b): |
| 4562 | """Returns True if the two operands have the same exponent. |
| 4563 | |
| 4564 | The result is never affected by either the sign or the coefficient of |
| 4565 | either operand. |
| 4566 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4567 | >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4568 | False |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4569 | >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4570 | True |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4571 | >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4572 | False |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4573 | >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4574 | True |
| 4575 | """ |
| 4576 | return a.same_quantum(b) |
| 4577 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4578 | def scaleb (self, a, b): |
| 4579 | """Returns the first operand after adding the second value its exp. |
| 4580 | |
| 4581 | >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2')) |
| 4582 | Decimal("0.0750") |
| 4583 | >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0')) |
| 4584 | Decimal("7.50") |
| 4585 | >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3')) |
| 4586 | Decimal("7.50E+3") |
| 4587 | """ |
| 4588 | return a.scaleb (b, context=self) |
| 4589 | |
| 4590 | def shift(self, a, b): |
| 4591 | """Returns a shifted copy of a, b times. |
| 4592 | |
| 4593 | The coefficient of the result is a shifted copy of the digits |
| 4594 | in the coefficient of the first operand. The number of places |
| 4595 | to shift is taken from the absolute value of the second operand, |
| 4596 | with the shift being to the left if the second operand is |
| 4597 | positive or to the right otherwise. Digits shifted into the |
| 4598 | coefficient are zeros. |
| 4599 | |
| 4600 | >>> ExtendedContext.shift(Decimal('34'), Decimal('8')) |
| 4601 | Decimal("400000000") |
| 4602 | >>> ExtendedContext.shift(Decimal('12'), Decimal('9')) |
| 4603 | Decimal("0") |
| 4604 | >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2')) |
| 4605 | Decimal("1234567") |
| 4606 | >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0')) |
| 4607 | Decimal("123456789") |
| 4608 | >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2')) |
| 4609 | Decimal("345678900") |
| 4610 | """ |
| 4611 | return a.shift(b, context=self) |
| 4612 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4613 | def sqrt(self, a): |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 4614 | """Square root of a non-negative number to context precision. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4615 | |
| 4616 | If the result must be inexact, it is rounded using the round-half-even |
| 4617 | algorithm. |
| 4618 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4619 | >>> ExtendedContext.sqrt(Decimal('0')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4620 | Decimal("0") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4621 | >>> ExtendedContext.sqrt(Decimal('-0')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4622 | Decimal("-0") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4623 | >>> ExtendedContext.sqrt(Decimal('0.39')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4624 | Decimal("0.624499800") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4625 | >>> ExtendedContext.sqrt(Decimal('100')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4626 | Decimal("10") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4627 | >>> ExtendedContext.sqrt(Decimal('1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4628 | Decimal("1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4629 | >>> ExtendedContext.sqrt(Decimal('1.0')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4630 | Decimal("1.0") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4631 | >>> ExtendedContext.sqrt(Decimal('1.00')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4632 | Decimal("1.0") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4633 | >>> ExtendedContext.sqrt(Decimal('7')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4634 | Decimal("2.64575131") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4635 | >>> ExtendedContext.sqrt(Decimal('10')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4636 | Decimal("3.16227766") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4637 | >>> ExtendedContext.prec |
Raymond Hettinger | 6ea4845 | 2004-07-03 12:26:21 +0000 | [diff] [blame] | 4638 | 9 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4639 | """ |
| 4640 | return a.sqrt(context=self) |
| 4641 | |
| 4642 | def subtract(self, a, b): |
Georg Brandl | f33d01d | 2005-08-22 19:35:18 +0000 | [diff] [blame] | 4643 | """Return the difference between the two operands. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4644 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4645 | >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4646 | Decimal("0.23") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4647 | >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4648 | Decimal("0.00") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4649 | >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4650 | Decimal("-0.77") |
| 4651 | """ |
| 4652 | return a.__sub__(b, context=self) |
| 4653 | |
| 4654 | def to_eng_string(self, a): |
| 4655 | """Converts a number to a string, using scientific notation. |
| 4656 | |
| 4657 | The operation is not affected by the context. |
| 4658 | """ |
| 4659 | return a.to_eng_string(context=self) |
| 4660 | |
| 4661 | def to_sci_string(self, a): |
| 4662 | """Converts a number to a string, using scientific notation. |
| 4663 | |
| 4664 | The operation is not affected by the context. |
| 4665 | """ |
| 4666 | return a.__str__(context=self) |
| 4667 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4668 | def to_integral_exact(self, a): |
| 4669 | """Rounds to an integer. |
| 4670 | |
| 4671 | When the operand has a negative exponent, the result is the same |
| 4672 | as using the quantize() operation using the given operand as the |
| 4673 | left-hand-operand, 1E+0 as the right-hand-operand, and the precision |
| 4674 | of the operand as the precision setting; Inexact and Rounded flags |
| 4675 | are allowed in this operation. The rounding mode is taken from the |
| 4676 | context. |
| 4677 | |
| 4678 | >>> ExtendedContext.to_integral_exact(Decimal('2.1')) |
| 4679 | Decimal("2") |
| 4680 | >>> ExtendedContext.to_integral_exact(Decimal('100')) |
| 4681 | Decimal("100") |
| 4682 | >>> ExtendedContext.to_integral_exact(Decimal('100.0')) |
| 4683 | Decimal("100") |
| 4684 | >>> ExtendedContext.to_integral_exact(Decimal('101.5')) |
| 4685 | Decimal("102") |
| 4686 | >>> ExtendedContext.to_integral_exact(Decimal('-101.5')) |
| 4687 | Decimal("-102") |
| 4688 | >>> ExtendedContext.to_integral_exact(Decimal('10E+5')) |
| 4689 | Decimal("1.0E+6") |
| 4690 | >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77')) |
| 4691 | Decimal("7.89E+77") |
| 4692 | >>> ExtendedContext.to_integral_exact(Decimal('-Inf')) |
| 4693 | Decimal("-Infinity") |
| 4694 | """ |
| 4695 | return a.to_integral_exact(context=self) |
| 4696 | |
| 4697 | def to_integral_value(self, a): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4698 | """Rounds to an integer. |
| 4699 | |
| 4700 | When the operand has a negative exponent, the result is the same |
| 4701 | as using the quantize() operation using the given operand as the |
| 4702 | left-hand-operand, 1E+0 as the right-hand-operand, and the precision |
| 4703 | of the operand as the precision setting, except that no flags will |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 4704 | be set. The rounding mode is taken from the context. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4705 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4706 | >>> ExtendedContext.to_integral_value(Decimal('2.1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4707 | Decimal("2") |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4708 | >>> ExtendedContext.to_integral_value(Decimal('100')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4709 | Decimal("100") |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4710 | >>> ExtendedContext.to_integral_value(Decimal('100.0')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4711 | Decimal("100") |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4712 | >>> ExtendedContext.to_integral_value(Decimal('101.5')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4713 | Decimal("102") |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4714 | >>> ExtendedContext.to_integral_value(Decimal('-101.5')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4715 | Decimal("-102") |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4716 | >>> ExtendedContext.to_integral_value(Decimal('10E+5')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4717 | Decimal("1.0E+6") |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4718 | >>> ExtendedContext.to_integral_value(Decimal('7.89E+77')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4719 | Decimal("7.89E+77") |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4720 | >>> ExtendedContext.to_integral_value(Decimal('-Inf')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4721 | Decimal("-Infinity") |
| 4722 | """ |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4723 | return a.to_integral_value(context=self) |
| 4724 | |
| 4725 | # the method name changed, but we provide also the old one, for compatibility |
| 4726 | to_integral = to_integral_value |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4727 | |
| 4728 | class _WorkRep(object): |
| 4729 | __slots__ = ('sign','int','exp') |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 4730 | # sign: 0 or 1 |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 4731 | # int: int or long |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4732 | # exp: None, int, or string |
| 4733 | |
| 4734 | def __init__(self, value=None): |
| 4735 | if value is None: |
| 4736 | self.sign = None |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 4737 | self.int = 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4738 | self.exp = None |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 4739 | elif isinstance(value, Decimal): |
| 4740 | self.sign = value._sign |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 4741 | self.int = int(value._int) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4742 | self.exp = value._exp |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 4743 | else: |
| 4744 | # assert isinstance(value, tuple) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4745 | self.sign = value[0] |
| 4746 | self.int = value[1] |
| 4747 | self.exp = value[2] |
| 4748 | |
| 4749 | def __repr__(self): |
| 4750 | return "(%r, %r, %r)" % (self.sign, self.int, self.exp) |
| 4751 | |
| 4752 | __str__ = __repr__ |
| 4753 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4754 | |
| 4755 | |
| 4756 | def _normalize(op1, op2, shouldround = 0, prec = 0): |
| 4757 | """Normalizes op1, op2 to have the same exp and length of coefficient. |
| 4758 | |
| 4759 | Done during addition. |
| 4760 | """ |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4761 | if op1.exp < op2.exp: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4762 | tmp = op2 |
| 4763 | other = op1 |
| 4764 | else: |
| 4765 | tmp = op1 |
| 4766 | other = op2 |
| 4767 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4768 | # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1). |
| 4769 | # Then adding 10**exp to tmp has the same effect (after rounding) |
| 4770 | # as adding any positive quantity smaller than 10**exp; similarly |
| 4771 | # for subtraction. So if other is smaller than 10**exp we replace |
| 4772 | # it with 10**exp. This avoids tmp.exp - other.exp getting too large. |
| 4773 | if shouldround: |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 4774 | tmp_len = len(str(tmp.int)) |
| 4775 | other_len = len(str(other.int)) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4776 | exp = tmp.exp + min(-1, tmp_len - prec - 2) |
| 4777 | if other_len + other.exp - 1 < exp: |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 4778 | other.int = 1 |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4779 | other.exp = exp |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 4780 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4781 | tmp.int *= 10 ** (tmp.exp - other.exp) |
| 4782 | tmp.exp = other.exp |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4783 | return op1, op2 |
| 4784 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4785 | ##### Integer arithmetic functions used by ln, log10, exp and __pow__ ##### |
| 4786 | |
| 4787 | # This function from Tim Peters was taken from here: |
| 4788 | # http://mail.python.org/pipermail/python-list/1999-July/007758.html |
| 4789 | # The correction being in the function definition is for speed, and |
| 4790 | # the whole function is not resolved with math.log because of avoiding |
| 4791 | # the use of floats. |
| 4792 | def _nbits(n, correction = { |
| 4793 | '0': 4, '1': 3, '2': 2, '3': 2, |
| 4794 | '4': 1, '5': 1, '6': 1, '7': 1, |
| 4795 | '8': 0, '9': 0, 'a': 0, 'b': 0, |
| 4796 | 'c': 0, 'd': 0, 'e': 0, 'f': 0}): |
| 4797 | """Number of bits in binary representation of the positive integer n, |
| 4798 | or 0 if n == 0. |
| 4799 | """ |
| 4800 | if n < 0: |
| 4801 | raise ValueError("The argument to _nbits should be nonnegative.") |
| 4802 | hex_n = "%x" % n |
| 4803 | return 4*len(hex_n) - correction[hex_n[0]] |
| 4804 | |
| 4805 | def _sqrt_nearest(n, a): |
| 4806 | """Closest integer to the square root of the positive integer n. a is |
| 4807 | an initial approximation to the square root. Any positive integer |
| 4808 | will do for a, but the closer a is to the square root of n the |
| 4809 | faster convergence will be. |
| 4810 | |
| 4811 | """ |
| 4812 | if n <= 0 or a <= 0: |
| 4813 | raise ValueError("Both arguments to _sqrt_nearest should be positive.") |
| 4814 | |
| 4815 | b=0 |
| 4816 | while a != b: |
| 4817 | b, a = a, a--n//a>>1 |
| 4818 | return a |
| 4819 | |
| 4820 | def _rshift_nearest(x, shift): |
| 4821 | """Given an integer x and a nonnegative integer shift, return closest |
| 4822 | integer to x / 2**shift; use round-to-even in case of a tie. |
| 4823 | |
| 4824 | """ |
| 4825 | b, q = 1L << shift, x >> shift |
| 4826 | return q + (2*(x & (b-1)) + (q&1) > b) |
| 4827 | |
| 4828 | def _div_nearest(a, b): |
| 4829 | """Closest integer to a/b, a and b positive integers; rounds to even |
| 4830 | in the case of a tie. |
| 4831 | |
| 4832 | """ |
| 4833 | q, r = divmod(a, b) |
| 4834 | return q + (2*r + (q&1) > b) |
| 4835 | |
| 4836 | def _ilog(x, M, L = 8): |
| 4837 | """Integer approximation to M*log(x/M), with absolute error boundable |
| 4838 | in terms only of x/M. |
| 4839 | |
| 4840 | Given positive integers x and M, return an integer approximation to |
| 4841 | M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference |
| 4842 | between the approximation and the exact result is at most 22. For |
| 4843 | L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In |
| 4844 | both cases these are upper bounds on the error; it will usually be |
| 4845 | much smaller.""" |
| 4846 | |
| 4847 | # The basic algorithm is the following: let log1p be the function |
| 4848 | # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use |
| 4849 | # the reduction |
| 4850 | # |
| 4851 | # log1p(y) = 2*log1p(y/(1+sqrt(1+y))) |
| 4852 | # |
| 4853 | # repeatedly until the argument to log1p is small (< 2**-L in |
| 4854 | # absolute value). For small y we can use the Taylor series |
| 4855 | # expansion |
| 4856 | # |
| 4857 | # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T |
| 4858 | # |
| 4859 | # truncating at T such that y**T is small enough. The whole |
| 4860 | # computation is carried out in a form of fixed-point arithmetic, |
| 4861 | # with a real number z being represented by an integer |
| 4862 | # approximation to z*M. To avoid loss of precision, the y below |
| 4863 | # is actually an integer approximation to 2**R*y*M, where R is the |
| 4864 | # number of reductions performed so far. |
| 4865 | |
| 4866 | y = x-M |
| 4867 | # argument reduction; R = number of reductions performed |
| 4868 | R = 0 |
| 4869 | while (R <= L and long(abs(y)) << L-R >= M or |
| 4870 | R > L and abs(y) >> R-L >= M): |
| 4871 | y = _div_nearest(long(M*y) << 1, |
| 4872 | M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M)) |
| 4873 | R += 1 |
| 4874 | |
| 4875 | # Taylor series with T terms |
| 4876 | T = -int(-10*len(str(M))//(3*L)) |
| 4877 | yshift = _rshift_nearest(y, R) |
| 4878 | w = _div_nearest(M, T) |
| 4879 | for k in xrange(T-1, 0, -1): |
| 4880 | w = _div_nearest(M, k) - _div_nearest(yshift*w, M) |
| 4881 | |
| 4882 | return _div_nearest(w*y, M) |
| 4883 | |
| 4884 | def _dlog10(c, e, p): |
| 4885 | """Given integers c, e and p with c > 0, p >= 0, compute an integer |
| 4886 | approximation to 10**p * log10(c*10**e), with an absolute error of |
| 4887 | at most 1. Assumes that c*10**e is not exactly 1.""" |
| 4888 | |
| 4889 | # increase precision by 2; compensate for this by dividing |
| 4890 | # final result by 100 |
| 4891 | p += 2 |
| 4892 | |
| 4893 | # write c*10**e as d*10**f with either: |
| 4894 | # f >= 0 and 1 <= d <= 10, or |
| 4895 | # f <= 0 and 0.1 <= d <= 1. |
| 4896 | # Thus for c*10**e close to 1, f = 0 |
| 4897 | l = len(str(c)) |
| 4898 | f = e+l - (e+l >= 1) |
| 4899 | |
| 4900 | if p > 0: |
| 4901 | M = 10**p |
| 4902 | k = e+p-f |
| 4903 | if k >= 0: |
| 4904 | c *= 10**k |
| 4905 | else: |
| 4906 | c = _div_nearest(c, 10**-k) |
| 4907 | |
| 4908 | log_d = _ilog(c, M) # error < 5 + 22 = 27 |
Facundo Batista | be6c7ba | 2007-10-02 18:21:18 +0000 | [diff] [blame] | 4909 | log_10 = _log10_digits(p) # error < 1 |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4910 | log_d = _div_nearest(log_d*M, log_10) |
| 4911 | log_tenpower = f*M # exact |
| 4912 | else: |
| 4913 | log_d = 0 # error < 2.31 |
| 4914 | log_tenpower = div_nearest(f, 10**-p) # error < 0.5 |
| 4915 | |
| 4916 | return _div_nearest(log_tenpower+log_d, 100) |
| 4917 | |
| 4918 | def _dlog(c, e, p): |
| 4919 | """Given integers c, e and p with c > 0, compute an integer |
| 4920 | approximation to 10**p * log(c*10**e), with an absolute error of |
| 4921 | at most 1. Assumes that c*10**e is not exactly 1.""" |
| 4922 | |
| 4923 | # Increase precision by 2. The precision increase is compensated |
| 4924 | # for at the end with a division by 100. |
| 4925 | p += 2 |
| 4926 | |
| 4927 | # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10, |
| 4928 | # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e) |
| 4929 | # as 10**p * log(d) + 10**p*f * log(10). |
| 4930 | l = len(str(c)) |
| 4931 | f = e+l - (e+l >= 1) |
| 4932 | |
| 4933 | # compute approximation to 10**p*log(d), with error < 27 |
| 4934 | if p > 0: |
| 4935 | k = e+p-f |
| 4936 | if k >= 0: |
| 4937 | c *= 10**k |
| 4938 | else: |
| 4939 | c = _div_nearest(c, 10**-k) # error of <= 0.5 in c |
| 4940 | |
| 4941 | # _ilog magnifies existing error in c by a factor of at most 10 |
| 4942 | log_d = _ilog(c, 10**p) # error < 5 + 22 = 27 |
| 4943 | else: |
| 4944 | # p <= 0: just approximate the whole thing by 0; error < 2.31 |
| 4945 | log_d = 0 |
| 4946 | |
Facundo Batista | be6c7ba | 2007-10-02 18:21:18 +0000 | [diff] [blame] | 4947 | # compute approximation to f*10**p*log(10), with error < 11. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4948 | if f: |
Facundo Batista | be6c7ba | 2007-10-02 18:21:18 +0000 | [diff] [blame] | 4949 | extra = len(str(abs(f)))-1 |
| 4950 | if p + extra >= 0: |
| 4951 | # error in f * _log10_digits(p+extra) < |f| * 1 = |f| |
| 4952 | # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11 |
| 4953 | f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4954 | else: |
| 4955 | f_log_ten = 0 |
| 4956 | else: |
| 4957 | f_log_ten = 0 |
| 4958 | |
Facundo Batista | be6c7ba | 2007-10-02 18:21:18 +0000 | [diff] [blame] | 4959 | # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1 |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4960 | return _div_nearest(f_log_ten + log_d, 100) |
| 4961 | |
Facundo Batista | be6c7ba | 2007-10-02 18:21:18 +0000 | [diff] [blame] | 4962 | class _Log10Memoize(object): |
| 4963 | """Class to compute, store, and allow retrieval of, digits of the |
| 4964 | constant log(10) = 2.302585.... This constant is needed by |
| 4965 | Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__.""" |
| 4966 | def __init__(self): |
| 4967 | self.digits = "23025850929940456840179914546843642076011014886" |
| 4968 | |
| 4969 | def getdigits(self, p): |
| 4970 | """Given an integer p >= 0, return floor(10**p)*log(10). |
| 4971 | |
| 4972 | For example, self.getdigits(3) returns 2302. |
| 4973 | """ |
| 4974 | # digits are stored as a string, for quick conversion to |
| 4975 | # integer in the case that we've already computed enough |
| 4976 | # digits; the stored digits should always be correct |
| 4977 | # (truncated, not rounded to nearest). |
| 4978 | if p < 0: |
| 4979 | raise ValueError("p should be nonnegative") |
| 4980 | |
| 4981 | if p >= len(self.digits): |
| 4982 | # compute p+3, p+6, p+9, ... digits; continue until at |
| 4983 | # least one of the extra digits is nonzero |
| 4984 | extra = 3 |
| 4985 | while True: |
| 4986 | # compute p+extra digits, correct to within 1ulp |
| 4987 | M = 10**(p+extra+2) |
| 4988 | digits = str(_div_nearest(_ilog(10*M, M), 100)) |
| 4989 | if digits[-extra:] != '0'*extra: |
| 4990 | break |
| 4991 | extra += 3 |
| 4992 | # keep all reliable digits so far; remove trailing zeros |
| 4993 | # and next nonzero digit |
| 4994 | self.digits = digits.rstrip('0')[:-1] |
| 4995 | return int(self.digits[:p+1]) |
| 4996 | |
| 4997 | _log10_digits = _Log10Memoize().getdigits |
| 4998 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4999 | def _iexp(x, M, L=8): |
| 5000 | """Given integers x and M, M > 0, such that x/M is small in absolute |
| 5001 | value, compute an integer approximation to M*exp(x/M). For 0 <= |
| 5002 | x/M <= 2.4, the absolute error in the result is bounded by 60 (and |
| 5003 | is usually much smaller).""" |
| 5004 | |
| 5005 | # Algorithm: to compute exp(z) for a real number z, first divide z |
| 5006 | # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then |
| 5007 | # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor |
| 5008 | # series |
| 5009 | # |
| 5010 | # expm1(x) = x + x**2/2! + x**3/3! + ... |
| 5011 | # |
| 5012 | # Now use the identity |
| 5013 | # |
| 5014 | # expm1(2x) = expm1(x)*(expm1(x)+2) |
| 5015 | # |
| 5016 | # R times to compute the sequence expm1(z/2**R), |
| 5017 | # expm1(z/2**(R-1)), ... , exp(z/2), exp(z). |
| 5018 | |
| 5019 | # Find R such that x/2**R/M <= 2**-L |
| 5020 | R = _nbits((long(x)<<L)//M) |
| 5021 | |
| 5022 | # Taylor series. (2**L)**T > M |
| 5023 | T = -int(-10*len(str(M))//(3*L)) |
| 5024 | y = _div_nearest(x, T) |
| 5025 | Mshift = long(M)<<R |
| 5026 | for i in xrange(T-1, 0, -1): |
| 5027 | y = _div_nearest(x*(Mshift + y), Mshift * i) |
| 5028 | |
| 5029 | # Expansion |
| 5030 | for k in xrange(R-1, -1, -1): |
| 5031 | Mshift = long(M)<<(k+2) |
| 5032 | y = _div_nearest(y*(y+Mshift), Mshift) |
| 5033 | |
| 5034 | return M+y |
| 5035 | |
| 5036 | def _dexp(c, e, p): |
| 5037 | """Compute an approximation to exp(c*10**e), with p decimal places of |
| 5038 | precision. |
| 5039 | |
Facundo Batista | be6c7ba | 2007-10-02 18:21:18 +0000 | [diff] [blame] | 5040 | Returns integers d, f such that: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5041 | |
| 5042 | 10**(p-1) <= d <= 10**p, and |
| 5043 | (d-1)*10**f < exp(c*10**e) < (d+1)*10**f |
| 5044 | |
| 5045 | In other words, d*10**f is an approximation to exp(c*10**e) with p |
| 5046 | digits of precision, and with an error in d of at most 1. This is |
| 5047 | almost, but not quite, the same as the error being < 1ulp: when d |
| 5048 | = 10**(p-1) the error could be up to 10 ulp.""" |
| 5049 | |
| 5050 | # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision |
| 5051 | p += 2 |
| 5052 | |
Facundo Batista | be6c7ba | 2007-10-02 18:21:18 +0000 | [diff] [blame] | 5053 | # compute log(10) with extra precision = adjusted exponent of c*10**e |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5054 | extra = max(0, e + len(str(c)) - 1) |
| 5055 | q = p + extra |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5056 | |
Facundo Batista | be6c7ba | 2007-10-02 18:21:18 +0000 | [diff] [blame] | 5057 | # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q), |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5058 | # rounding down |
| 5059 | shift = e+q |
| 5060 | if shift >= 0: |
| 5061 | cshift = c*10**shift |
| 5062 | else: |
| 5063 | cshift = c//10**-shift |
Facundo Batista | be6c7ba | 2007-10-02 18:21:18 +0000 | [diff] [blame] | 5064 | quot, rem = divmod(cshift, _log10_digits(q)) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5065 | |
| 5066 | # reduce remainder back to original precision |
| 5067 | rem = _div_nearest(rem, 10**extra) |
| 5068 | |
| 5069 | # error in result of _iexp < 120; error after division < 0.62 |
| 5070 | return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3 |
| 5071 | |
| 5072 | def _dpower(xc, xe, yc, ye, p): |
| 5073 | """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and |
| 5074 | y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that: |
| 5075 | |
| 5076 | 10**(p-1) <= c <= 10**p, and |
| 5077 | (c-1)*10**e < x**y < (c+1)*10**e |
| 5078 | |
| 5079 | in other words, c*10**e is an approximation to x**y with p digits |
| 5080 | of precision, and with an error in c of at most 1. (This is |
| 5081 | almost, but not quite, the same as the error being < 1ulp: when c |
| 5082 | == 10**(p-1) we can only guarantee error < 10ulp.) |
| 5083 | |
| 5084 | We assume that: x is positive and not equal to 1, and y is nonzero. |
| 5085 | """ |
| 5086 | |
| 5087 | # Find b such that 10**(b-1) <= |y| <= 10**b |
| 5088 | b = len(str(abs(yc))) + ye |
| 5089 | |
| 5090 | # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point |
| 5091 | lxc = _dlog(xc, xe, p+b+1) |
| 5092 | |
| 5093 | # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1) |
| 5094 | shift = ye-b |
| 5095 | if shift >= 0: |
| 5096 | pc = lxc*yc*10**shift |
| 5097 | else: |
| 5098 | pc = _div_nearest(lxc*yc, 10**-shift) |
| 5099 | |
| 5100 | if pc == 0: |
| 5101 | # we prefer a result that isn't exactly 1; this makes it |
| 5102 | # easier to compute a correctly rounded result in __pow__ |
| 5103 | if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1: |
| 5104 | coeff, exp = 10**(p-1)+1, 1-p |
| 5105 | else: |
| 5106 | coeff, exp = 10**p-1, -p |
| 5107 | else: |
| 5108 | coeff, exp = _dexp(pc, -(p+1), p+1) |
| 5109 | coeff = _div_nearest(coeff, 10) |
| 5110 | exp += 1 |
| 5111 | |
| 5112 | return coeff, exp |
| 5113 | |
| 5114 | def _log10_lb(c, correction = { |
| 5115 | '1': 100, '2': 70, '3': 53, '4': 40, '5': 31, |
| 5116 | '6': 23, '7': 16, '8': 10, '9': 5}): |
| 5117 | """Compute a lower bound for 100*log10(c) for a positive integer c.""" |
| 5118 | if c <= 0: |
| 5119 | raise ValueError("The argument to _log10_lb should be nonnegative.") |
| 5120 | str_c = str(c) |
| 5121 | return 100*len(str_c) - correction[str_c[0]] |
| 5122 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 5123 | ##### Helper Functions #################################################### |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5124 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5125 | def _convert_other(other, raiseit=False): |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5126 | """Convert other to Decimal. |
| 5127 | |
| 5128 | Verifies that it's ok to use in an implicit construction. |
| 5129 | """ |
| 5130 | if isinstance(other, Decimal): |
| 5131 | return other |
| 5132 | if isinstance(other, (int, long)): |
| 5133 | return Decimal(other) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5134 | if raiseit: |
| 5135 | raise TypeError("Unable to convert %s to Decimal" % other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 5136 | return NotImplemented |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5137 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 5138 | ##### Setup Specific Contexts ############################################ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5139 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5140 | # The default context prototype used by Context() |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 5141 | # Is mutable, so that new contexts can have different default values |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5142 | |
| 5143 | DefaultContext = Context( |
Raymond Hettinger | 6ea4845 | 2004-07-03 12:26:21 +0000 | [diff] [blame] | 5144 | prec=28, rounding=ROUND_HALF_EVEN, |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 5145 | traps=[DivisionByZero, Overflow, InvalidOperation], |
| 5146 | flags=[], |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5147 | _rounding_decision=ALWAYS_ROUND, |
Raymond Hettinger | 99148e7 | 2004-07-14 19:56:56 +0000 | [diff] [blame] | 5148 | Emax=999999999, |
| 5149 | Emin=-999999999, |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 5150 | capitals=1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5151 | ) |
| 5152 | |
| 5153 | # Pre-made alternate contexts offered by the specification |
| 5154 | # Don't change these; the user should be able to select these |
| 5155 | # contexts and be able to reproduce results from other implementations |
| 5156 | # of the spec. |
| 5157 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5158 | BasicContext = Context( |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5159 | prec=9, rounding=ROUND_HALF_UP, |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 5160 | traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow], |
| 5161 | flags=[], |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5162 | ) |
| 5163 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5164 | ExtendedContext = Context( |
Raymond Hettinger | 6ea4845 | 2004-07-03 12:26:21 +0000 | [diff] [blame] | 5165 | prec=9, rounding=ROUND_HALF_EVEN, |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 5166 | traps=[], |
| 5167 | flags=[], |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5168 | ) |
| 5169 | |
| 5170 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 5171 | ##### crud for parsing strings ############################################# |
| 5172 | import re |
| 5173 | |
| 5174 | # Regular expression used for parsing numeric strings. Additional |
| 5175 | # comments: |
| 5176 | # |
| 5177 | # 1. Uncomment the two '\s*' lines to allow leading and/or trailing |
| 5178 | # whitespace. But note that the specification disallows whitespace in |
| 5179 | # a numeric string. |
| 5180 | # |
| 5181 | # 2. For finite numbers (not infinities and NaNs) the body of the |
| 5182 | # number between the optional sign and the optional exponent must have |
| 5183 | # at least one decimal digit, possibly after the decimal point. The |
| 5184 | # lookahead expression '(?=\d|\.\d)' checks this. |
| 5185 | # |
| 5186 | # As the flag UNICODE is not enabled here, we're explicitly avoiding any |
| 5187 | # other meaning for \d than the numbers [0-9]. |
| 5188 | |
| 5189 | import re |
| 5190 | _parser = re.compile(r""" # A numeric string consists of: |
| 5191 | # \s* |
| 5192 | (?P<sign>[-+])? # an optional sign, followed by either... |
| 5193 | ( |
| 5194 | (?=\d|\.\d) # ...a number (with at least one digit) |
| 5195 | (?P<int>\d*) # consisting of a (possibly empty) integer part |
| 5196 | (\.(?P<frac>\d*))? # followed by an optional fractional part |
| 5197 | (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or... |
| 5198 | | |
| 5199 | Inf(inity)? # ...an infinity, or... |
| 5200 | | |
| 5201 | (?P<signal>s)? # ...an (optionally signaling) |
| 5202 | NaN # NaN |
| 5203 | (?P<diag>\d*) # with (possibly empty) diagnostic information. |
| 5204 | ) |
| 5205 | # \s* |
| 5206 | $ |
| 5207 | """, re.VERBOSE | re.IGNORECASE).match |
| 5208 | |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 5209 | _all_zeros = re.compile('0*$').match |
| 5210 | _exact_half = re.compile('50*$').match |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 5211 | del re |
| 5212 | |
| 5213 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 5214 | ##### Useful Constants (internal use only) ################################ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5215 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 5216 | # Reusable defaults |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5217 | Inf = Decimal('Inf') |
| 5218 | negInf = Decimal('-Inf') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5219 | NaN = Decimal('NaN') |
| 5220 | Dec_0 = Decimal(0) |
| 5221 | Dec_p1 = Decimal(1) |
| 5222 | Dec_n1 = Decimal(-1) |
| 5223 | Dec_p2 = Decimal(2) |
| 5224 | Dec_n2 = Decimal(-2) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5225 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 5226 | # Infsign[sign] is infinity w/ that sign |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5227 | Infsign = (Inf, negInf) |
| 5228 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5229 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5230 | |
| 5231 | if __name__ == '__main__': |
| 5232 | import doctest, sys |
| 5233 | doctest.testmod(sys.modules[__name__]) |