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 | |
| 32 | The purpose of the module is to support arithmetic using familiar |
| 33 | "schoolhouse" rules and to avoid the some of tricky representation |
| 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 | ... |
Guido van Rossum | 6a2a2a0 | 2006-08-26 20:37:44 +0000 | [diff] [blame] | 88 | decimal.DivisionByZero: x / 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 89 | >>> c = Context() |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 90 | >>> c.traps[InvalidOperation] = 0 |
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 | ... |
Guido van Rossum | 6a2a2a0 | 2006-08-26 20:37:44 +0000 | [diff] [blame] | 106 | decimal.InvalidOperation: 0 / 0 |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 107 | >>> print c.flags[InvalidOperation] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 108 | 1 |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 109 | >>> c.flags[InvalidOperation] = 0 |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 110 | >>> c.traps[InvalidOperation] = 0 |
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', |
| 131 | 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 132 | |
| 133 | # Functions for manipulating contexts |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 134 | 'setcontext', 'getcontext', 'localcontext' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 135 | ] |
| 136 | |
Raymond Hettinger | eb26084 | 2005-06-07 18:52:34 +0000 | [diff] [blame] | 137 | import copy as _copy |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 138 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +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' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 147 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 148 | #Rounding decision (not part of the public API) |
Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 149 | NEVER_ROUND = 'NEVER_ROUND' # Round in division (non-divmod), sqrt ONLY |
| 150 | ALWAYS_ROUND = 'ALWAYS_ROUND' # Every operation rounds at end. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 151 | |
| 152 | #Errors |
| 153 | |
| 154 | class DecimalException(ArithmeticError): |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 155 | """Base exception class. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 156 | |
| 157 | Used exceptions derive from this. |
| 158 | If an exception derives from another exception besides this (such as |
| 159 | Underflow (Inexact, Rounded, Subnormal) that indicates that it is only |
| 160 | called if the others are present. This isn't actually used for |
| 161 | anything, though. |
| 162 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 163 | handle -- Called when context._raise_error is called and the |
| 164 | trap_enabler is set. First argument is self, second is the |
| 165 | context. More arguments can be given, those being after |
| 166 | the explanation in _raise_error (For example, |
| 167 | context._raise_error(NewError, '(-x)!', self._sign) would |
| 168 | call NewError().handle(context, self._sign).) |
| 169 | |
| 170 | To define a new exception, it should be sufficient to have it derive |
| 171 | from DecimalException. |
| 172 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 173 | def handle(self, context, *args): |
| 174 | pass |
| 175 | |
| 176 | |
| 177 | class Clamped(DecimalException): |
| 178 | """Exponent of a 0 changed to fit bounds. |
| 179 | |
| 180 | This occurs and signals clamped if the exponent of a result has been |
| 181 | altered in order to fit the constraints of a specific concrete |
| 182 | representation. This may occur when the exponent of a zero result would |
| 183 | be outside the bounds of a representation, or when a large normal |
| 184 | number would have an encoded exponent that cannot be represented. In |
| 185 | this latter case, the exponent is reduced to fit and the corresponding |
| 186 | number of zero digits are appended to the coefficient ("fold-down"). |
| 187 | """ |
| 188 | |
| 189 | |
| 190 | class InvalidOperation(DecimalException): |
| 191 | """An invalid operation was performed. |
| 192 | |
| 193 | Various bad things cause this: |
| 194 | |
| 195 | Something creates a signaling NaN |
| 196 | -INF + INF |
| 197 | 0 * (+-)INF |
| 198 | (+-)INF / (+-)INF |
| 199 | x % 0 |
| 200 | (+-)INF % x |
| 201 | x._rescale( non-integer ) |
| 202 | sqrt(-x) , x > 0 |
| 203 | 0 ** 0 |
| 204 | x ** (non-integer) |
| 205 | x ** (+-)INF |
| 206 | An operand is invalid |
| 207 | """ |
| 208 | def handle(self, context, *args): |
| 209 | if args: |
| 210 | if args[0] == 1: #sNaN, must drop 's' but keep diagnostics |
| 211 | return Decimal( (args[1]._sign, args[1]._int, 'n') ) |
| 212 | return NaN |
| 213 | |
| 214 | class ConversionSyntax(InvalidOperation): |
| 215 | """Trying to convert badly formed string. |
| 216 | |
| 217 | This occurs and signals invalid-operation if an string is being |
| 218 | converted to a number and it does not conform to the numeric string |
| 219 | syntax. The result is [0,qNaN]. |
| 220 | """ |
| 221 | |
| 222 | def handle(self, context, *args): |
| 223 | return (0, (0,), 'n') #Passed to something which uses a tuple. |
| 224 | |
| 225 | class DivisionByZero(DecimalException, ZeroDivisionError): |
| 226 | """Division by 0. |
| 227 | |
| 228 | This occurs and signals division-by-zero if division of a finite number |
| 229 | by zero was attempted (during a divide-integer or divide operation, or a |
| 230 | power operation with negative right-hand operand), and the dividend was |
| 231 | not zero. |
| 232 | |
| 233 | The result of the operation is [sign,inf], where sign is the exclusive |
| 234 | or of the signs of the operands for divide, or is 1 for an odd power of |
| 235 | -0, for power. |
| 236 | """ |
| 237 | |
| 238 | def handle(self, context, sign, double = None, *args): |
| 239 | if double is not None: |
| 240 | return (Infsign[sign],)*2 |
| 241 | return Infsign[sign] |
| 242 | |
| 243 | class DivisionImpossible(InvalidOperation): |
| 244 | """Cannot perform the division adequately. |
| 245 | |
| 246 | This occurs and signals invalid-operation if the integer result of a |
| 247 | divide-integer or remainder operation had too many digits (would be |
| 248 | longer than precision). The result is [0,qNaN]. |
| 249 | """ |
| 250 | |
| 251 | def handle(self, context, *args): |
| 252 | return (NaN, NaN) |
| 253 | |
| 254 | class DivisionUndefined(InvalidOperation, ZeroDivisionError): |
| 255 | """Undefined result of division. |
| 256 | |
| 257 | This occurs and signals invalid-operation if division by zero was |
| 258 | attempted (during a divide-integer, divide, or remainder operation), and |
| 259 | the dividend is also zero. The result is [0,qNaN]. |
| 260 | """ |
| 261 | |
| 262 | def handle(self, context, tup=None, *args): |
| 263 | if tup is not None: |
| 264 | return (NaN, NaN) #for 0 %0, 0 // 0 |
| 265 | return NaN |
| 266 | |
| 267 | class Inexact(DecimalException): |
| 268 | """Had to round, losing information. |
| 269 | |
| 270 | This occurs and signals inexact whenever the result of an operation is |
| 271 | not exact (that is, it needed to be rounded and any discarded digits |
| 272 | were non-zero), or if an overflow or underflow condition occurs. The |
| 273 | result in all cases is unchanged. |
| 274 | |
| 275 | The inexact signal may be tested (or trapped) to determine if a given |
| 276 | operation (or sequence of operations) was inexact. |
| 277 | """ |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 278 | pass |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 279 | |
| 280 | class InvalidContext(InvalidOperation): |
| 281 | """Invalid context. Unknown rounding, for example. |
| 282 | |
| 283 | This occurs and signals invalid-operation if an invalid context was |
| 284 | detected during an operation. This can occur if contexts are not checked |
| 285 | on creation and either the precision exceeds the capability of the |
| 286 | underlying concrete representation or an unknown or unsupported rounding |
| 287 | was specified. These aspects of the context need only be checked when |
| 288 | the values are required to be used. The result is [0,qNaN]. |
| 289 | """ |
| 290 | |
| 291 | def handle(self, context, *args): |
| 292 | return NaN |
| 293 | |
| 294 | class Rounded(DecimalException): |
| 295 | """Number got rounded (not necessarily changed during rounding). |
| 296 | |
| 297 | This occurs and signals rounded whenever the result of an operation is |
| 298 | rounded (that is, some zero or non-zero digits were discarded from the |
| 299 | coefficient), or if an overflow or underflow condition occurs. The |
| 300 | result in all cases is unchanged. |
| 301 | |
| 302 | The rounded signal may be tested (or trapped) to determine if a given |
| 303 | operation (or sequence of operations) caused a loss of precision. |
| 304 | """ |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 305 | pass |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 306 | |
| 307 | class Subnormal(DecimalException): |
| 308 | """Exponent < Emin before rounding. |
| 309 | |
| 310 | This occurs and signals subnormal whenever the result of a conversion or |
| 311 | operation is subnormal (that is, its adjusted exponent is less than |
| 312 | Emin, before any rounding). The result in all cases is unchanged. |
| 313 | |
| 314 | The subnormal signal may be tested (or trapped) to determine if a given |
| 315 | or operation (or sequence of operations) yielded a subnormal result. |
| 316 | """ |
| 317 | pass |
| 318 | |
| 319 | class Overflow(Inexact, Rounded): |
| 320 | """Numerical overflow. |
| 321 | |
| 322 | This occurs and signals overflow if the adjusted exponent of a result |
| 323 | (from a conversion or from an operation that is not an attempt to divide |
| 324 | by zero), after rounding, would be greater than the largest value that |
| 325 | can be handled by the implementation (the value Emax). |
| 326 | |
| 327 | The result depends on the rounding mode: |
| 328 | |
| 329 | For round-half-up and round-half-even (and for round-half-down and |
| 330 | round-up, if implemented), the result of the operation is [sign,inf], |
| 331 | where sign is the sign of the intermediate result. For round-down, the |
| 332 | result is the largest finite number that can be represented in the |
| 333 | current precision, with the sign of the intermediate result. For |
| 334 | round-ceiling, the result is the same as for round-down if the sign of |
| 335 | the intermediate result is 1, or is [0,inf] otherwise. For round-floor, |
| 336 | the result is the same as for round-down if the sign of the intermediate |
| 337 | result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded |
| 338 | will also be raised. |
| 339 | """ |
| 340 | |
| 341 | def handle(self, context, sign, *args): |
| 342 | if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN, |
| 343 | ROUND_HALF_DOWN, ROUND_UP): |
| 344 | return Infsign[sign] |
| 345 | if sign == 0: |
| 346 | if context.rounding == ROUND_CEILING: |
| 347 | return Infsign[sign] |
| 348 | return Decimal((sign, (9,)*context.prec, |
| 349 | context.Emax-context.prec+1)) |
| 350 | if sign == 1: |
| 351 | if context.rounding == ROUND_FLOOR: |
| 352 | return Infsign[sign] |
| 353 | return Decimal( (sign, (9,)*context.prec, |
| 354 | context.Emax-context.prec+1)) |
| 355 | |
| 356 | |
| 357 | class Underflow(Inexact, Rounded, Subnormal): |
| 358 | """Numerical underflow with result rounded to 0. |
| 359 | |
| 360 | This occurs and signals underflow if a result is inexact and the |
| 361 | adjusted exponent of the result would be smaller (more negative) than |
| 362 | the smallest value that can be handled by the implementation (the value |
| 363 | Emin). That is, the result is both inexact and subnormal. |
| 364 | |
| 365 | The result after an underflow will be a subnormal number rounded, if |
| 366 | necessary, so that its exponent is not less than Etiny. This may result |
| 367 | in 0 with the sign of the intermediate result and an exponent of Etiny. |
| 368 | |
| 369 | In all cases, Inexact, Rounded, and Subnormal will also be raised. |
| 370 | """ |
| 371 | |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 372 | # List of public traps and flags |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 373 | _signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded, |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 374 | Underflow, InvalidOperation, Subnormal] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 375 | |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 376 | # Map conditions (per the spec) to signals |
| 377 | _condition_map = {ConversionSyntax:InvalidOperation, |
| 378 | DivisionImpossible:InvalidOperation, |
| 379 | DivisionUndefined:InvalidOperation, |
| 380 | InvalidContext:InvalidOperation} |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 381 | |
| 382 | ##### Context Functions ####################################### |
| 383 | |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 384 | # The getcontext() and setcontext() function manage access to a thread-local |
| 385 | # current context. Py2.4 offers direct support for thread locals. If that |
| 386 | # is not available, use threading.currentThread() which is slower but will |
Raymond Hettinger | 7e71fa5 | 2004-12-18 19:07:19 +0000 | [diff] [blame] | 387 | # work for older Pythons. If threads are not part of the build, create a |
| 388 | # mock threading object with threading.local() returning the module namespace. |
| 389 | |
| 390 | try: |
| 391 | import threading |
| 392 | except ImportError: |
| 393 | # Python was compiled without threads; create a mock object instead |
| 394 | import sys |
| 395 | class MockThreading: |
| 396 | def local(self, sys=sys): |
| 397 | return sys.modules[__name__] |
| 398 | threading = MockThreading() |
| 399 | del sys, MockThreading |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 400 | |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 401 | try: |
| 402 | threading.local |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 403 | |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 404 | except AttributeError: |
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 | #To fix reloading, force it to create a new context |
| 407 | #Old contexts have different exceptions in their dicts, making problems. |
| 408 | if hasattr(threading.currentThread(), '__decimal_context__'): |
| 409 | del threading.currentThread().__decimal_context__ |
| 410 | |
| 411 | def setcontext(context): |
| 412 | """Set this thread's context to context.""" |
| 413 | if context in (DefaultContext, BasicContext, ExtendedContext): |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 414 | context = context.copy() |
Raymond Hettinger | 61992ef | 2004-08-06 23:42:16 +0000 | [diff] [blame] | 415 | context.clear_flags() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 416 | threading.currentThread().__decimal_context__ = context |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 417 | |
| 418 | def getcontext(): |
| 419 | """Returns this thread's context. |
| 420 | |
| 421 | If this thread does not yet have a context, returns |
| 422 | a new context and sets this thread's context. |
| 423 | New contexts are copies of DefaultContext. |
| 424 | """ |
| 425 | try: |
| 426 | return threading.currentThread().__decimal_context__ |
| 427 | except AttributeError: |
| 428 | context = Context() |
| 429 | threading.currentThread().__decimal_context__ = context |
| 430 | return context |
| 431 | |
| 432 | else: |
| 433 | |
| 434 | local = threading.local() |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 435 | if hasattr(local, '__decimal_context__'): |
| 436 | del local.__decimal_context__ |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 437 | |
| 438 | def getcontext(_local=local): |
| 439 | """Returns this thread's context. |
| 440 | |
| 441 | If this thread does not yet have a context, returns |
| 442 | a new context and sets this thread's context. |
| 443 | New contexts are copies of DefaultContext. |
| 444 | """ |
| 445 | try: |
| 446 | return _local.__decimal_context__ |
| 447 | except AttributeError: |
| 448 | context = Context() |
| 449 | _local.__decimal_context__ = context |
| 450 | return context |
| 451 | |
| 452 | def setcontext(context, _local=local): |
| 453 | """Set this thread's context to context.""" |
| 454 | if context in (DefaultContext, BasicContext, ExtendedContext): |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 455 | context = context.copy() |
Raymond Hettinger | 61992ef | 2004-08-06 23:42:16 +0000 | [diff] [blame] | 456 | context.clear_flags() |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 457 | _local.__decimal_context__ = context |
| 458 | |
| 459 | del threading, local # Don't contaminate the namespace |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 460 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 461 | def localcontext(ctx=None): |
| 462 | """Return a context manager for a copy of the supplied context |
| 463 | |
| 464 | Uses a copy of the current context if no context is specified |
| 465 | The returned context manager creates a local decimal context |
| 466 | in a with statement: |
| 467 | def sin(x): |
| 468 | with localcontext() as ctx: |
| 469 | ctx.prec += 2 |
| 470 | # Rest of sin calculation algorithm |
| 471 | # uses a precision 2 greater than normal |
| 472 | return +s # Convert result to normal precision |
| 473 | |
| 474 | def sin(x): |
| 475 | with localcontext(ExtendedContext): |
| 476 | # Rest of sin calculation algorithm |
| 477 | # uses the Extended Context from the |
| 478 | # General Decimal Arithmetic Specification |
| 479 | return +s # Convert result to normal context |
| 480 | |
| 481 | """ |
| 482 | # The string below can't be included in the docstring until Python 2.6 |
| 483 | # as the doctest module doesn't understand __future__ statements |
| 484 | """ |
| 485 | >>> from __future__ import with_statement |
| 486 | >>> print getcontext().prec |
| 487 | 28 |
| 488 | >>> with localcontext(): |
| 489 | ... ctx = getcontext() |
| 490 | ... ctx.prec() += 2 |
| 491 | ... print ctx.prec |
| 492 | ... |
| 493 | 30 |
| 494 | >>> with localcontext(ExtendedContext): |
| 495 | ... print getcontext().prec |
| 496 | ... |
| 497 | 9 |
| 498 | >>> print getcontext().prec |
| 499 | 28 |
| 500 | """ |
| 501 | if ctx is None: ctx = getcontext() |
| 502 | return _ContextManager(ctx) |
| 503 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 504 | |
| 505 | ##### Decimal class ########################################### |
| 506 | |
| 507 | class Decimal(object): |
| 508 | """Floating point class for decimal arithmetic.""" |
| 509 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 510 | __slots__ = ('_exp','_int','_sign', '_is_special') |
| 511 | # Generally, the value of the Decimal instance is given by |
| 512 | # (-1)**_sign * _int * 10**_exp |
| 513 | # Special values are signified by _is_special == True |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 514 | |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 515 | # We're immutable, so use __new__ not __init__ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 516 | def __new__(cls, value="0", context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 517 | """Create a decimal point instance. |
| 518 | |
| 519 | >>> Decimal('3.14') # string input |
| 520 | Decimal("3.14") |
| 521 | >>> Decimal((0, (3, 1, 4), -2)) # tuple input (sign, digit_tuple, exponent) |
| 522 | Decimal("3.14") |
| 523 | >>> Decimal(314) # int or long |
| 524 | Decimal("314") |
| 525 | >>> Decimal(Decimal(314)) # another decimal instance |
| 526 | Decimal("314") |
| 527 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 528 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 529 | self = object.__new__(cls) |
| 530 | self._is_special = False |
| 531 | |
| 532 | # From an internal working value |
| 533 | if isinstance(value, _WorkRep): |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 534 | self._sign = value.sign |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 535 | self._int = tuple(map(int, str(value.int))) |
| 536 | self._exp = int(value.exp) |
| 537 | return self |
| 538 | |
| 539 | # From another decimal |
| 540 | if isinstance(value, Decimal): |
| 541 | self._exp = value._exp |
| 542 | self._sign = value._sign |
| 543 | self._int = value._int |
| 544 | self._is_special = value._is_special |
| 545 | return self |
| 546 | |
| 547 | # From an integer |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame^] | 548 | if isinstance(value, (int,int)): |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 549 | if value >= 0: |
| 550 | self._sign = 0 |
| 551 | else: |
| 552 | self._sign = 1 |
| 553 | self._exp = 0 |
| 554 | self._int = tuple(map(int, str(abs(value)))) |
| 555 | return self |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 556 | |
| 557 | # tuple/list conversion (possibly from as_tuple()) |
| 558 | if isinstance(value, (list,tuple)): |
| 559 | if len(value) != 3: |
| 560 | raise ValueError, 'Invalid arguments' |
Raymond Hettinger | dbecd93 | 2005-02-06 06:57:08 +0000 | [diff] [blame] | 561 | if value[0] not in (0,1): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 562 | raise ValueError, 'Invalid sign' |
| 563 | for digit in value[1]: |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame^] | 564 | if not isinstance(digit, (int,int)) or digit < 0: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 565 | raise ValueError, "The second value in the tuple must be composed of non negative integer elements." |
| 566 | |
| 567 | self._sign = value[0] |
| 568 | self._int = tuple(value[1]) |
| 569 | if value[2] in ('F','n','N'): |
| 570 | self._exp = value[2] |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 571 | self._is_special = True |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 572 | else: |
| 573 | self._exp = int(value[2]) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 574 | return self |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 575 | |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 576 | if isinstance(value, float): |
| 577 | raise TypeError("Cannot convert float to Decimal. " + |
| 578 | "First convert the float to a string") |
| 579 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 580 | # Other argument types may require the context during interpretation |
| 581 | if context is None: |
| 582 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 583 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 584 | # From a string |
| 585 | # REs insist on real strings, so we can too. |
| 586 | if isinstance(value, basestring): |
| 587 | if _isinfinity(value): |
| 588 | self._exp = 'F' |
| 589 | self._int = (0,) |
| 590 | self._is_special = True |
| 591 | if _isinfinity(value) == 1: |
| 592 | self._sign = 0 |
| 593 | else: |
| 594 | self._sign = 1 |
| 595 | return self |
| 596 | if _isnan(value): |
| 597 | sig, sign, diag = _isnan(value) |
| 598 | self._is_special = True |
| 599 | if len(diag) > context.prec: #Diagnostic info too long |
| 600 | self._sign, self._int, self._exp = \ |
| 601 | context._raise_error(ConversionSyntax) |
| 602 | return self |
| 603 | if sig == 1: |
| 604 | self._exp = 'n' #qNaN |
| 605 | else: #sig == 2 |
| 606 | self._exp = 'N' #sNaN |
| 607 | self._sign = sign |
| 608 | self._int = tuple(map(int, diag)) #Diagnostic info |
| 609 | return self |
| 610 | try: |
| 611 | self._sign, self._int, self._exp = _string2exact(value) |
| 612 | except ValueError: |
| 613 | self._is_special = True |
| 614 | self._sign, self._int, self._exp = context._raise_error(ConversionSyntax) |
| 615 | return self |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 616 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 617 | raise TypeError("Cannot convert %r to Decimal" % value) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 618 | |
| 619 | def _isnan(self): |
| 620 | """Returns whether the number is not actually one. |
| 621 | |
| 622 | 0 if a number |
| 623 | 1 if NaN |
| 624 | 2 if sNaN |
| 625 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 626 | if self._is_special: |
| 627 | exp = self._exp |
| 628 | if exp == 'n': |
| 629 | return 1 |
| 630 | elif exp == 'N': |
| 631 | return 2 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 632 | return 0 |
| 633 | |
| 634 | def _isinfinity(self): |
| 635 | """Returns whether the number is infinite |
| 636 | |
| 637 | 0 if finite or not a number |
| 638 | 1 if +INF |
| 639 | -1 if -INF |
| 640 | """ |
| 641 | if self._exp == 'F': |
| 642 | if self._sign: |
| 643 | return -1 |
| 644 | return 1 |
| 645 | return 0 |
| 646 | |
| 647 | def _check_nans(self, other = None, context=None): |
| 648 | """Returns whether the number is not actually one. |
| 649 | |
| 650 | if self, other are sNaN, signal |
| 651 | if self, other are NaN return nan |
| 652 | return 0 |
| 653 | |
| 654 | Done before operations. |
| 655 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 656 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 657 | self_is_nan = self._isnan() |
| 658 | if other is None: |
| 659 | other_is_nan = False |
| 660 | else: |
| 661 | other_is_nan = other._isnan() |
| 662 | |
| 663 | if self_is_nan or other_is_nan: |
| 664 | if context is None: |
| 665 | context = getcontext() |
| 666 | |
| 667 | if self_is_nan == 2: |
| 668 | return context._raise_error(InvalidOperation, 'sNaN', |
| 669 | 1, self) |
| 670 | if other_is_nan == 2: |
| 671 | return context._raise_error(InvalidOperation, 'sNaN', |
| 672 | 1, other) |
| 673 | if self_is_nan: |
| 674 | return self |
| 675 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 676 | return other |
| 677 | return 0 |
| 678 | |
Jack Diederich | 4dafcc4 | 2006-11-28 19:15:13 +0000 | [diff] [blame] | 679 | def __bool__(self): |
Jack Diederich | 030debb | 2006-11-28 22:22:22 +0000 | [diff] [blame] | 680 | """return True if the number is non-zero. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 681 | |
Jack Diederich | 030debb | 2006-11-28 22:22:22 +0000 | [diff] [blame] | 682 | False if self == 0 |
| 683 | True if self != 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 684 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 685 | if self._is_special: |
Jack Diederich | 4dafcc4 | 2006-11-28 19:15:13 +0000 | [diff] [blame] | 686 | return True |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 687 | return sum(self._int) != 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 688 | |
| 689 | def __cmp__(self, other, context=None): |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 690 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 691 | if other is NotImplemented: |
| 692 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 693 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 694 | if self._is_special or other._is_special: |
| 695 | ans = self._check_nans(other, context) |
| 696 | if ans: |
| 697 | return 1 # Comparison involving NaN's always reports self > other |
| 698 | |
| 699 | # INF = INF |
| 700 | return cmp(self._isinfinity(), other._isinfinity()) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 701 | |
| 702 | if not self and not other: |
| 703 | return 0 #If both 0, sign comparison isn't certain. |
| 704 | |
| 705 | #If different signs, neg one is less |
| 706 | if other._sign < self._sign: |
| 707 | return -1 |
| 708 | if self._sign < other._sign: |
| 709 | return 1 |
| 710 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 711 | self_adjusted = self.adjusted() |
| 712 | other_adjusted = other.adjusted() |
| 713 | if self_adjusted == other_adjusted and \ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 714 | self._int + (0,)*(self._exp - other._exp) == \ |
| 715 | other._int + (0,)*(other._exp - self._exp): |
| 716 | return 0 #equal, except in precision. ([0]*(-x) = []) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 717 | elif self_adjusted > other_adjusted and self._int[0] != 0: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 718 | return (-1)**self._sign |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 719 | elif self_adjusted < other_adjusted and other._int[0] != 0: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 720 | return -((-1)**self._sign) |
| 721 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 722 | # Need to round, so make sure we have a valid context |
| 723 | if context is None: |
| 724 | context = getcontext() |
| 725 | |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 726 | context = context._shallow_copy() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 727 | rounding = context._set_rounding(ROUND_UP) #round away from 0 |
| 728 | |
| 729 | flags = context._ignore_all_flags() |
| 730 | res = self.__sub__(other, context=context) |
| 731 | |
| 732 | context._regard_flags(*flags) |
| 733 | |
| 734 | context.rounding = rounding |
| 735 | |
| 736 | if not res: |
| 737 | return 0 |
| 738 | elif res._sign: |
| 739 | return -1 |
| 740 | return 1 |
| 741 | |
Raymond Hettinger | 0aeac10 | 2004-07-05 22:53:03 +0000 | [diff] [blame] | 742 | def __eq__(self, other): |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame^] | 743 | if not isinstance(other, (Decimal, int, int)): |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 744 | return NotImplemented |
Raymond Hettinger | 0aeac10 | 2004-07-05 22:53:03 +0000 | [diff] [blame] | 745 | return self.__cmp__(other) == 0 |
| 746 | |
| 747 | def __ne__(self, other): |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame^] | 748 | if not isinstance(other, (Decimal, int, int)): |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 749 | return NotImplemented |
Raymond Hettinger | 0aeac10 | 2004-07-05 22:53:03 +0000 | [diff] [blame] | 750 | return self.__cmp__(other) != 0 |
| 751 | |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 752 | def __lt__(self, other): |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame^] | 753 | if not isinstance(other, (Decimal, int, int)): |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 754 | return NotImplemented |
| 755 | return self.__cmp__(other) < 0 |
| 756 | |
| 757 | def __le__(self, other): |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame^] | 758 | if not isinstance(other, (Decimal, int, int)): |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 759 | return NotImplemented |
| 760 | return self.__cmp__(other) <= 0 |
| 761 | |
| 762 | def __gt__(self, other): |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame^] | 763 | if not isinstance(other, (Decimal, int, int)): |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 764 | return NotImplemented |
| 765 | return self.__cmp__(other) > 0 |
| 766 | |
| 767 | def __ge__(self, other): |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame^] | 768 | if not isinstance(other, (Decimal, int, int)): |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 769 | return NotImplemented |
| 770 | return self.__cmp__(other) >= 0 |
| 771 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 772 | def compare(self, other, context=None): |
| 773 | """Compares one to another. |
| 774 | |
| 775 | -1 => a < b |
| 776 | 0 => a = b |
| 777 | 1 => a > b |
| 778 | NaN => one is NaN |
| 779 | Like __cmp__, but returns Decimal instances. |
| 780 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 781 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 782 | if other is NotImplemented: |
| 783 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 784 | |
| 785 | #compare(NaN, NaN) = NaN |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 786 | if (self._is_special or other and other._is_special): |
| 787 | ans = self._check_nans(other, context) |
| 788 | if ans: |
| 789 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 790 | |
| 791 | return Decimal(self.__cmp__(other, context)) |
| 792 | |
| 793 | def __hash__(self): |
| 794 | """x.__hash__() <==> hash(x)""" |
| 795 | # Decimal integers must hash the same as the ints |
| 796 | # Non-integer decimals are normalized and hashed as strings |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 797 | # Normalization assures that hash(100E-1) == hash(10) |
Raymond Hettinger | bea3f6f | 2005-03-15 04:59:17 +0000 | [diff] [blame] | 798 | if self._is_special: |
| 799 | if self._isnan(): |
| 800 | raise TypeError('Cannot hash a NaN value.') |
| 801 | return hash(str(self)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 802 | i = int(self) |
| 803 | if self == Decimal(i): |
| 804 | return hash(i) |
Jack Diederich | 4dafcc4 | 2006-11-28 19:15:13 +0000 | [diff] [blame] | 805 | assert self.__bool__() # '-0' handled by integer case |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 806 | return hash(str(self.normalize())) |
| 807 | |
| 808 | def as_tuple(self): |
| 809 | """Represents the number as a triple tuple. |
| 810 | |
| 811 | To show the internals exactly as they are. |
| 812 | """ |
| 813 | return (self._sign, self._int, self._exp) |
| 814 | |
| 815 | def __repr__(self): |
| 816 | """Represents the number as an instance of Decimal.""" |
| 817 | # Invariant: eval(repr(d)) == d |
| 818 | return 'Decimal("%s")' % str(self) |
| 819 | |
| 820 | def __str__(self, eng = 0, context=None): |
| 821 | """Return string representation of the number in scientific notation. |
| 822 | |
| 823 | Captures all of the information in the underlying representation. |
| 824 | """ |
| 825 | |
Raymond Hettinger | e5a0a96 | 2005-06-20 09:49:42 +0000 | [diff] [blame] | 826 | if self._is_special: |
| 827 | if self._isnan(): |
| 828 | minus = '-'*self._sign |
| 829 | if self._int == (0,): |
| 830 | info = '' |
| 831 | else: |
| 832 | info = ''.join(map(str, self._int)) |
| 833 | if self._isnan() == 2: |
| 834 | return minus + 'sNaN' + info |
| 835 | return minus + 'NaN' + info |
| 836 | if self._isinfinity(): |
| 837 | minus = '-'*self._sign |
| 838 | return minus + 'Infinity' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 839 | |
| 840 | if context is None: |
| 841 | context = getcontext() |
| 842 | |
| 843 | tmp = map(str, self._int) |
| 844 | numdigits = len(self._int) |
| 845 | leftdigits = self._exp + numdigits |
| 846 | if eng and not self: #self = 0eX wants 0[.0[0]]eY, not [[0]0]0eY |
| 847 | if self._exp < 0 and self._exp >= -6: #short, no need for e/E |
| 848 | s = '-'*self._sign + '0.' + '0'*(abs(self._exp)) |
| 849 | return s |
| 850 | #exp is closest mult. of 3 >= self._exp |
| 851 | exp = ((self._exp - 1)// 3 + 1) * 3 |
| 852 | if exp != self._exp: |
| 853 | s = '0.'+'0'*(exp - self._exp) |
| 854 | else: |
| 855 | s = '0' |
| 856 | if exp != 0: |
| 857 | if context.capitals: |
| 858 | s += 'E' |
| 859 | else: |
| 860 | s += 'e' |
| 861 | if exp > 0: |
| 862 | s += '+' #0.0e+3, not 0.0e3 |
| 863 | s += str(exp) |
| 864 | s = '-'*self._sign + s |
| 865 | return s |
| 866 | if eng: |
| 867 | dotplace = (leftdigits-1)%3+1 |
| 868 | adjexp = leftdigits -1 - (leftdigits-1)%3 |
| 869 | else: |
| 870 | adjexp = leftdigits-1 |
| 871 | dotplace = 1 |
| 872 | if self._exp == 0: |
| 873 | pass |
| 874 | elif self._exp < 0 and adjexp >= 0: |
| 875 | tmp.insert(leftdigits, '.') |
| 876 | elif self._exp < 0 and adjexp >= -6: |
| 877 | tmp[0:0] = ['0'] * int(-leftdigits) |
| 878 | tmp.insert(0, '0.') |
| 879 | else: |
| 880 | if numdigits > dotplace: |
| 881 | tmp.insert(dotplace, '.') |
| 882 | elif numdigits < dotplace: |
| 883 | tmp.extend(['0']*(dotplace-numdigits)) |
| 884 | if adjexp: |
| 885 | if not context.capitals: |
| 886 | tmp.append('e') |
| 887 | else: |
| 888 | tmp.append('E') |
| 889 | if adjexp > 0: |
| 890 | tmp.append('+') |
| 891 | tmp.append(str(adjexp)) |
| 892 | if eng: |
| 893 | while tmp[0:1] == ['0']: |
| 894 | tmp[0:1] = [] |
| 895 | if len(tmp) == 0 or tmp[0] == '.' or tmp[0].lower() == 'e': |
| 896 | tmp[0:0] = ['0'] |
| 897 | if self._sign: |
| 898 | tmp.insert(0, '-') |
| 899 | |
| 900 | return ''.join(tmp) |
| 901 | |
| 902 | def to_eng_string(self, context=None): |
| 903 | """Convert to engineering-type string. |
| 904 | |
| 905 | Engineering notation has an exponent which is a multiple of 3, so there |
| 906 | are up to 3 digits left of the decimal place. |
| 907 | |
| 908 | Same rules for when in exponential and when as a value as in __str__. |
| 909 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 910 | return self.__str__(eng=1, context=context) |
| 911 | |
| 912 | def __neg__(self, context=None): |
| 913 | """Returns a copy with the sign switched. |
| 914 | |
| 915 | Rounds, if it has reason. |
| 916 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 917 | if self._is_special: |
| 918 | ans = self._check_nans(context=context) |
| 919 | if ans: |
| 920 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 921 | |
| 922 | if not self: |
| 923 | # -Decimal('0') is Decimal('0'), not Decimal('-0') |
| 924 | sign = 0 |
| 925 | elif self._sign: |
| 926 | sign = 0 |
| 927 | else: |
| 928 | sign = 1 |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 929 | |
| 930 | if context is None: |
| 931 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 932 | if context._rounding_decision == ALWAYS_ROUND: |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 933 | return Decimal((sign, self._int, self._exp))._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 934 | return Decimal( (sign, self._int, self._exp)) |
| 935 | |
| 936 | def __pos__(self, context=None): |
| 937 | """Returns a copy, unless it is a sNaN. |
| 938 | |
| 939 | Rounds the number (if more then precision digits) |
| 940 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 941 | if self._is_special: |
| 942 | ans = self._check_nans(context=context) |
| 943 | if ans: |
| 944 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 945 | |
| 946 | sign = self._sign |
| 947 | if not self: |
| 948 | # + (-0) = 0 |
| 949 | sign = 0 |
| 950 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 951 | if context is None: |
| 952 | context = getcontext() |
| 953 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 954 | if context._rounding_decision == ALWAYS_ROUND: |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 955 | ans = self._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 956 | else: |
| 957 | ans = Decimal(self) |
| 958 | ans._sign = sign |
| 959 | return ans |
| 960 | |
| 961 | def __abs__(self, round=1, context=None): |
| 962 | """Returns the absolute value of self. |
| 963 | |
| 964 | If the second argument is 0, do not round. |
| 965 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 966 | if self._is_special: |
| 967 | ans = self._check_nans(context=context) |
| 968 | if ans: |
| 969 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 970 | |
| 971 | if not round: |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 972 | if context is None: |
| 973 | context = getcontext() |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 974 | context = context._shallow_copy() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 975 | context._set_rounding_decision(NEVER_ROUND) |
| 976 | |
| 977 | if self._sign: |
| 978 | ans = self.__neg__(context=context) |
| 979 | else: |
| 980 | ans = self.__pos__(context=context) |
| 981 | |
| 982 | return ans |
| 983 | |
| 984 | def __add__(self, other, context=None): |
| 985 | """Returns self + other. |
| 986 | |
| 987 | -INF + INF (or the reverse) cause InvalidOperation errors. |
| 988 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 989 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 990 | if other is NotImplemented: |
| 991 | return other |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 992 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 993 | if context is None: |
| 994 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 995 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 996 | if self._is_special or other._is_special: |
| 997 | ans = self._check_nans(other, context) |
| 998 | if ans: |
| 999 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1000 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1001 | if self._isinfinity(): |
| 1002 | #If both INF, same sign => same as both, opposite => error. |
| 1003 | if self._sign != other._sign and other._isinfinity(): |
| 1004 | return context._raise_error(InvalidOperation, '-INF + INF') |
| 1005 | return Decimal(self) |
| 1006 | if other._isinfinity(): |
| 1007 | return Decimal(other) #Can't both be infinity here |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1008 | |
| 1009 | shouldround = context._rounding_decision == ALWAYS_ROUND |
| 1010 | |
| 1011 | exp = min(self._exp, other._exp) |
| 1012 | negativezero = 0 |
| 1013 | if context.rounding == ROUND_FLOOR and self._sign != other._sign: |
| 1014 | #If the answer is 0, the sign should be negative, in this case. |
| 1015 | negativezero = 1 |
| 1016 | |
| 1017 | if not self and not other: |
| 1018 | sign = min(self._sign, other._sign) |
| 1019 | if negativezero: |
| 1020 | sign = 1 |
| 1021 | return Decimal( (sign, (0,), exp)) |
| 1022 | if not self: |
Facundo Batista | 99b5548 | 2004-10-26 23:38:46 +0000 | [diff] [blame] | 1023 | exp = max(exp, other._exp - context.prec-1) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1024 | ans = other._rescale(exp, watchexp=0, context=context) |
| 1025 | if shouldround: |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1026 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1027 | return ans |
| 1028 | if not other: |
Facundo Batista | 99b5548 | 2004-10-26 23:38:46 +0000 | [diff] [blame] | 1029 | exp = max(exp, self._exp - context.prec-1) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1030 | ans = self._rescale(exp, watchexp=0, context=context) |
| 1031 | if shouldround: |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1032 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1033 | return ans |
| 1034 | |
| 1035 | op1 = _WorkRep(self) |
| 1036 | op2 = _WorkRep(other) |
| 1037 | op1, op2 = _normalize(op1, op2, shouldround, context.prec) |
| 1038 | |
| 1039 | result = _WorkRep() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1040 | if op1.sign != op2.sign: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1041 | # Equal and opposite |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1042 | if op1.int == op2.int: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1043 | if exp < context.Etiny(): |
| 1044 | exp = context.Etiny() |
| 1045 | context._raise_error(Clamped) |
| 1046 | return Decimal((negativezero, (0,), exp)) |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1047 | if op1.int < op2.int: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1048 | op1, op2 = op2, op1 |
| 1049 | #OK, now abs(op1) > abs(op2) |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1050 | if op1.sign == 1: |
| 1051 | result.sign = 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1052 | op1.sign, op2.sign = op2.sign, op1.sign |
| 1053 | else: |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1054 | result.sign = 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1055 | #So we know the sign, and op1 > 0. |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1056 | elif op1.sign == 1: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1057 | result.sign = 1 |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1058 | op1.sign, op2.sign = (0, 0) |
| 1059 | else: |
| 1060 | result.sign = 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1061 | #Now, op1 > abs(op2) > 0 |
| 1062 | |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1063 | if op2.sign == 0: |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1064 | result.int = op1.int + op2.int |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1065 | else: |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1066 | result.int = op1.int - op2.int |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1067 | |
| 1068 | result.exp = op1.exp |
| 1069 | ans = Decimal(result) |
| 1070 | if shouldround: |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1071 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1072 | return ans |
| 1073 | |
| 1074 | __radd__ = __add__ |
| 1075 | |
| 1076 | def __sub__(self, other, context=None): |
| 1077 | """Return self + (-other)""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1078 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1079 | if other is NotImplemented: |
| 1080 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1081 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1082 | if self._is_special or other._is_special: |
| 1083 | ans = self._check_nans(other, context=context) |
| 1084 | if ans: |
| 1085 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1086 | |
| 1087 | # -Decimal(0) = Decimal(0), which we don't want since |
| 1088 | # (-0 - 0 = -0 + (-0) = -0, but -0 + 0 = 0.) |
| 1089 | # so we change the sign directly to a copy |
| 1090 | tmp = Decimal(other) |
| 1091 | tmp._sign = 1-tmp._sign |
| 1092 | |
| 1093 | return self.__add__(tmp, context=context) |
| 1094 | |
| 1095 | def __rsub__(self, other, context=None): |
| 1096 | """Return other + (-self)""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1097 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1098 | if other is NotImplemented: |
| 1099 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1100 | |
| 1101 | tmp = Decimal(self) |
| 1102 | tmp._sign = 1 - tmp._sign |
| 1103 | return other.__add__(tmp, context=context) |
| 1104 | |
| 1105 | def _increment(self, round=1, context=None): |
| 1106 | """Special case of add, adding 1eExponent |
| 1107 | |
| 1108 | Since it is common, (rounding, for example) this adds |
| 1109 | (sign)*one E self._exp to the number more efficiently than add. |
| 1110 | |
| 1111 | For example: |
| 1112 | Decimal('5.624e10')._increment() == Decimal('5.625e10') |
| 1113 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1114 | if self._is_special: |
| 1115 | ans = self._check_nans(context=context) |
| 1116 | if ans: |
| 1117 | return ans |
| 1118 | |
| 1119 | return Decimal(self) # Must be infinite, and incrementing makes no difference |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1120 | |
| 1121 | L = list(self._int) |
| 1122 | L[-1] += 1 |
| 1123 | spot = len(L)-1 |
| 1124 | while L[spot] == 10: |
| 1125 | L[spot] = 0 |
| 1126 | if spot == 0: |
| 1127 | L[0:0] = [1] |
| 1128 | break |
| 1129 | L[spot-1] += 1 |
| 1130 | spot -= 1 |
| 1131 | ans = Decimal((self._sign, L, self._exp)) |
| 1132 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1133 | if context is None: |
| 1134 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1135 | if round and context._rounding_decision == ALWAYS_ROUND: |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1136 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1137 | return ans |
| 1138 | |
| 1139 | def __mul__(self, other, context=None): |
| 1140 | """Return self * other. |
| 1141 | |
| 1142 | (+-) INF * 0 (or its reverse) raise InvalidOperation. |
| 1143 | """ |
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: |
| 1146 | return other |
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 | resultsign = self._sign ^ other._sign |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1152 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1153 | if self._is_special or other._is_special: |
| 1154 | ans = self._check_nans(other, context) |
| 1155 | if ans: |
| 1156 | return ans |
| 1157 | |
| 1158 | if self._isinfinity(): |
| 1159 | if not other: |
| 1160 | return context._raise_error(InvalidOperation, '(+-)INF * 0') |
| 1161 | return Infsign[resultsign] |
| 1162 | |
| 1163 | if other._isinfinity(): |
| 1164 | if not self: |
| 1165 | return context._raise_error(InvalidOperation, '0 * (+-)INF') |
| 1166 | return Infsign[resultsign] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1167 | |
| 1168 | resultexp = self._exp + other._exp |
| 1169 | shouldround = context._rounding_decision == ALWAYS_ROUND |
| 1170 | |
| 1171 | # Special case for multiplying by zero |
| 1172 | if not self or not other: |
| 1173 | ans = Decimal((resultsign, (0,), resultexp)) |
| 1174 | if shouldround: |
| 1175 | #Fixing in case the exponent is out of bounds |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1176 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1177 | return ans |
| 1178 | |
| 1179 | # Special case for multiplying by power of 10 |
| 1180 | if self._int == (1,): |
| 1181 | ans = Decimal((resultsign, other._int, resultexp)) |
| 1182 | if shouldround: |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1183 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1184 | return ans |
| 1185 | if other._int == (1,): |
| 1186 | ans = Decimal((resultsign, self._int, resultexp)) |
| 1187 | if shouldround: |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1188 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1189 | return ans |
| 1190 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1191 | op1 = _WorkRep(self) |
| 1192 | op2 = _WorkRep(other) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1193 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1194 | ans = Decimal( (resultsign, map(int, str(op1.int * op2.int)), resultexp)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1195 | if shouldround: |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1196 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1197 | |
| 1198 | return ans |
| 1199 | __rmul__ = __mul__ |
| 1200 | |
Neal Norwitz | bcc0db8 | 2006-03-24 08:14:36 +0000 | [diff] [blame] | 1201 | def __truediv__(self, other, context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1202 | """Return self / other.""" |
| 1203 | return self._divide(other, context=context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1204 | |
| 1205 | def _divide(self, other, divmod = 0, context=None): |
| 1206 | """Return a / b, to context.prec precision. |
| 1207 | |
| 1208 | divmod: |
| 1209 | 0 => true division |
| 1210 | 1 => (a //b, a%b) |
| 1211 | 2 => a //b |
| 1212 | 3 => a%b |
| 1213 | |
| 1214 | Actually, if divmod is 2 or 3 a tuple is returned, but errors for |
| 1215 | computing the other value are not raised. |
| 1216 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1217 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1218 | if other is NotImplemented: |
| 1219 | if divmod in (0, 1): |
| 1220 | return NotImplemented |
| 1221 | return (NotImplemented, NotImplemented) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1222 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1223 | if context is None: |
| 1224 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1225 | |
Raymond Hettinger | d87ac8f | 2004-07-09 10:52:54 +0000 | [diff] [blame] | 1226 | sign = self._sign ^ other._sign |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1227 | |
| 1228 | if self._is_special or other._is_special: |
| 1229 | ans = self._check_nans(other, context) |
| 1230 | if ans: |
| 1231 | if divmod: |
| 1232 | return (ans, ans) |
| 1233 | return ans |
| 1234 | |
| 1235 | if self._isinfinity() and other._isinfinity(): |
| 1236 | if divmod: |
| 1237 | return (context._raise_error(InvalidOperation, |
| 1238 | '(+-)INF // (+-)INF'), |
| 1239 | context._raise_error(InvalidOperation, |
| 1240 | '(+-)INF % (+-)INF')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1241 | return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1242 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1243 | if self._isinfinity(): |
| 1244 | if divmod == 1: |
| 1245 | return (Infsign[sign], |
| 1246 | context._raise_error(InvalidOperation, 'INF % x')) |
| 1247 | elif divmod == 2: |
| 1248 | return (Infsign[sign], NaN) |
| 1249 | elif divmod == 3: |
| 1250 | return (Infsign[sign], |
| 1251 | context._raise_error(InvalidOperation, 'INF % x')) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1252 | return Infsign[sign] |
| 1253 | |
| 1254 | if other._isinfinity(): |
| 1255 | if divmod: |
| 1256 | return (Decimal((sign, (0,), 0)), Decimal(self)) |
| 1257 | context._raise_error(Clamped, 'Division by infinity') |
| 1258 | return Decimal((sign, (0,), context.Etiny())) |
| 1259 | |
| 1260 | # Special cases for zeroes |
| 1261 | if not self and not other: |
| 1262 | if divmod: |
| 1263 | return context._raise_error(DivisionUndefined, '0 / 0', 1) |
| 1264 | return context._raise_error(DivisionUndefined, '0 / 0') |
| 1265 | |
| 1266 | if not self: |
| 1267 | if divmod: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1268 | otherside = Decimal(self) |
| 1269 | otherside._exp = min(self._exp, other._exp) |
| 1270 | return (Decimal((sign, (0,), 0)), otherside) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1271 | exp = self._exp - other._exp |
| 1272 | if exp < context.Etiny(): |
| 1273 | exp = context.Etiny() |
| 1274 | context._raise_error(Clamped, '0e-x / y') |
| 1275 | if exp > context.Emax: |
| 1276 | exp = context.Emax |
| 1277 | context._raise_error(Clamped, '0e+x / y') |
| 1278 | return Decimal( (sign, (0,), exp) ) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1279 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1280 | if not other: |
| 1281 | if divmod: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1282 | return context._raise_error(DivisionByZero, 'divmod(x,0)', |
| 1283 | sign, 1) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1284 | return context._raise_error(DivisionByZero, 'x / 0', sign) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1285 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1286 | #OK, so neither = 0, INF or NaN |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1287 | |
| 1288 | shouldround = context._rounding_decision == ALWAYS_ROUND |
| 1289 | |
| 1290 | #If we're dividing into ints, and self < other, stop. |
| 1291 | #self.__abs__(0) does not round. |
| 1292 | if divmod and (self.__abs__(0, context) < other.__abs__(0, context)): |
| 1293 | |
| 1294 | if divmod == 1 or divmod == 3: |
| 1295 | exp = min(self._exp, other._exp) |
| 1296 | ans2 = self._rescale(exp, context=context, watchexp=0) |
| 1297 | if shouldround: |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1298 | ans2 = ans2._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1299 | return (Decimal( (sign, (0,), 0) ), |
| 1300 | ans2) |
| 1301 | |
| 1302 | elif divmod == 2: |
| 1303 | #Don't round the mod part, if we don't need it. |
| 1304 | return (Decimal( (sign, (0,), 0) ), Decimal(self)) |
| 1305 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1306 | op1 = _WorkRep(self) |
| 1307 | op2 = _WorkRep(other) |
| 1308 | op1, op2, adjust = _adjust_coefficients(op1, op2) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1309 | res = _WorkRep( (sign, 0, (op1.exp - op2.exp)) ) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1310 | if divmod and res.exp > context.prec + 1: |
| 1311 | return context._raise_error(DivisionImpossible) |
| 1312 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1313 | prec_limit = 10 ** context.prec |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1314 | while 1: |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1315 | while op2.int <= op1.int: |
| 1316 | res.int += 1 |
| 1317 | op1.int -= op2.int |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1318 | if res.exp == 0 and divmod: |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1319 | if res.int >= prec_limit and shouldround: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1320 | return context._raise_error(DivisionImpossible) |
| 1321 | otherside = Decimal(op1) |
| 1322 | frozen = context._ignore_all_flags() |
| 1323 | |
| 1324 | exp = min(self._exp, other._exp) |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1325 | otherside = otherside._rescale(exp, context=context, watchexp=0) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1326 | context._regard_flags(*frozen) |
| 1327 | if shouldround: |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1328 | otherside = otherside._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1329 | return (Decimal(res), otherside) |
| 1330 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1331 | if op1.int == 0 and adjust >= 0 and not divmod: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1332 | break |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1333 | if res.int >= prec_limit and shouldround: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1334 | if divmod: |
| 1335 | return context._raise_error(DivisionImpossible) |
| 1336 | shouldround=1 |
| 1337 | # Really, the answer is a bit higher, so adding a one to |
| 1338 | # the end will make sure the rounding is right. |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1339 | if op1.int != 0: |
| 1340 | res.int *= 10 |
| 1341 | res.int += 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1342 | res.exp -= 1 |
| 1343 | |
| 1344 | break |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1345 | res.int *= 10 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1346 | res.exp -= 1 |
| 1347 | adjust += 1 |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1348 | op1.int *= 10 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1349 | op1.exp -= 1 |
| 1350 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1351 | if res.exp == 0 and divmod and op2.int > op1.int: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1352 | #Solves an error in precision. Same as a previous block. |
| 1353 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1354 | if res.int >= prec_limit and shouldround: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1355 | return context._raise_error(DivisionImpossible) |
| 1356 | otherside = Decimal(op1) |
| 1357 | frozen = context._ignore_all_flags() |
| 1358 | |
| 1359 | exp = min(self._exp, other._exp) |
| 1360 | otherside = otherside._rescale(exp, context=context) |
| 1361 | |
| 1362 | context._regard_flags(*frozen) |
| 1363 | |
| 1364 | return (Decimal(res), otherside) |
| 1365 | |
| 1366 | ans = Decimal(res) |
| 1367 | if shouldround: |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1368 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1369 | return ans |
| 1370 | |
Neal Norwitz | bcc0db8 | 2006-03-24 08:14:36 +0000 | [diff] [blame] | 1371 | def __rtruediv__(self, other, context=None): |
| 1372 | """Swaps self/other and returns __truediv__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1373 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1374 | if other is NotImplemented: |
| 1375 | return other |
Neal Norwitz | bcc0db8 | 2006-03-24 08:14:36 +0000 | [diff] [blame] | 1376 | return other.__truediv__(self, context=context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1377 | |
| 1378 | def __divmod__(self, other, context=None): |
| 1379 | """ |
| 1380 | (self // other, self % other) |
| 1381 | """ |
| 1382 | return self._divide(other, 1, context) |
| 1383 | |
| 1384 | def __rdivmod__(self, other, context=None): |
| 1385 | """Swaps self/other and returns __divmod__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1386 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1387 | if other is NotImplemented: |
| 1388 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1389 | return other.__divmod__(self, context=context) |
| 1390 | |
| 1391 | def __mod__(self, other, context=None): |
| 1392 | """ |
| 1393 | self % other |
| 1394 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1395 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1396 | if other is NotImplemented: |
| 1397 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1398 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1399 | if self._is_special or other._is_special: |
| 1400 | ans = self._check_nans(other, context) |
| 1401 | if ans: |
| 1402 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1403 | |
| 1404 | if self and not other: |
| 1405 | return context._raise_error(InvalidOperation, 'x % 0') |
| 1406 | |
| 1407 | return self._divide(other, 3, context)[1] |
| 1408 | |
| 1409 | def __rmod__(self, other, context=None): |
| 1410 | """Swaps self/other and returns __mod__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1411 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1412 | if other is NotImplemented: |
| 1413 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1414 | return other.__mod__(self, context=context) |
| 1415 | |
| 1416 | def remainder_near(self, other, context=None): |
| 1417 | """ |
| 1418 | Remainder nearest to 0- abs(remainder-near) <= other/2 |
| 1419 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1420 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1421 | if other is NotImplemented: |
| 1422 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1423 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1424 | if self._is_special or other._is_special: |
| 1425 | ans = self._check_nans(other, context) |
| 1426 | if ans: |
| 1427 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1428 | if self and not other: |
| 1429 | return context._raise_error(InvalidOperation, 'x % 0') |
| 1430 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1431 | if context is None: |
| 1432 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1433 | # If DivisionImpossible causes an error, do not leave Rounded/Inexact |
| 1434 | # ignored in the calling function. |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 1435 | context = context._shallow_copy() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1436 | flags = context._ignore_flags(Rounded, Inexact) |
| 1437 | #keep DivisionImpossible flags |
| 1438 | (side, r) = self.__divmod__(other, context=context) |
| 1439 | |
| 1440 | if r._isnan(): |
| 1441 | context._regard_flags(*flags) |
| 1442 | return r |
| 1443 | |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 1444 | context = context._shallow_copy() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1445 | rounding = context._set_rounding_decision(NEVER_ROUND) |
| 1446 | |
| 1447 | if other._sign: |
Neal Norwitz | bcc0db8 | 2006-03-24 08:14:36 +0000 | [diff] [blame] | 1448 | comparison = other.__truediv__(Decimal(-2), context=context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1449 | else: |
Neal Norwitz | bcc0db8 | 2006-03-24 08:14:36 +0000 | [diff] [blame] | 1450 | comparison = other.__truediv__(Decimal(2), context=context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1451 | |
| 1452 | context._set_rounding_decision(rounding) |
| 1453 | context._regard_flags(*flags) |
| 1454 | |
| 1455 | s1, s2 = r._sign, comparison._sign |
| 1456 | r._sign, comparison._sign = 0, 0 |
| 1457 | |
| 1458 | if r < comparison: |
| 1459 | r._sign, comparison._sign = s1, s2 |
| 1460 | #Get flags now |
| 1461 | self.__divmod__(other, context=context) |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1462 | return r._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1463 | r._sign, comparison._sign = s1, s2 |
| 1464 | |
| 1465 | rounding = context._set_rounding_decision(NEVER_ROUND) |
| 1466 | |
| 1467 | (side, r) = self.__divmod__(other, context=context) |
| 1468 | context._set_rounding_decision(rounding) |
| 1469 | if r._isnan(): |
| 1470 | return r |
| 1471 | |
| 1472 | decrease = not side._iseven() |
| 1473 | rounding = context._set_rounding_decision(NEVER_ROUND) |
| 1474 | side = side.__abs__(context=context) |
| 1475 | context._set_rounding_decision(rounding) |
| 1476 | |
| 1477 | s1, s2 = r._sign, comparison._sign |
| 1478 | r._sign, comparison._sign = 0, 0 |
| 1479 | if r > comparison or decrease and r == comparison: |
| 1480 | r._sign, comparison._sign = s1, s2 |
| 1481 | context.prec += 1 |
| 1482 | if len(side.__add__(Decimal(1), context=context)._int) >= context.prec: |
| 1483 | context.prec -= 1 |
| 1484 | return context._raise_error(DivisionImpossible)[1] |
| 1485 | context.prec -= 1 |
| 1486 | if self._sign == other._sign: |
| 1487 | r = r.__sub__(other, context=context) |
| 1488 | else: |
| 1489 | r = r.__add__(other, context=context) |
| 1490 | else: |
| 1491 | r._sign, comparison._sign = s1, s2 |
| 1492 | |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1493 | return r._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1494 | |
| 1495 | def __floordiv__(self, other, context=None): |
| 1496 | """self // other""" |
| 1497 | return self._divide(other, 2, context)[0] |
| 1498 | |
| 1499 | def __rfloordiv__(self, other, context=None): |
| 1500 | """Swaps self/other and returns __floordiv__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1501 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1502 | if other is NotImplemented: |
| 1503 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1504 | return other.__floordiv__(self, context=context) |
| 1505 | |
| 1506 | def __float__(self): |
| 1507 | """Float representation.""" |
| 1508 | return float(str(self)) |
| 1509 | |
| 1510 | def __int__(self): |
Brett Cannon | 46b0802 | 2005-03-01 03:12:26 +0000 | [diff] [blame] | 1511 | """Converts self to an int, truncating if necessary.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1512 | if self._is_special: |
| 1513 | if self._isnan(): |
| 1514 | context = getcontext() |
| 1515 | return context._raise_error(InvalidContext) |
| 1516 | elif self._isinfinity(): |
| 1517 | raise OverflowError, "Cannot convert infinity to long" |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1518 | if self._exp >= 0: |
Raymond Hettinger | 605ed02 | 2004-11-24 07:28:48 +0000 | [diff] [blame] | 1519 | s = ''.join(map(str, self._int)) + '0'*self._exp |
| 1520 | else: |
| 1521 | s = ''.join(map(str, self._int))[:self._exp] |
| 1522 | if s == '': |
| 1523 | s = '0' |
| 1524 | sign = '-'*self._sign |
| 1525 | return int(sign + s) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1526 | |
| 1527 | def __long__(self): |
| 1528 | """Converts to a long. |
| 1529 | |
| 1530 | Equivalent to long(int(self)) |
| 1531 | """ |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame^] | 1532 | return int(self.__int__()) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1533 | |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1534 | def _fix(self, context): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1535 | """Round if it is necessary to keep self within prec precision. |
| 1536 | |
| 1537 | Rounds and fixes the exponent. Does not raise on a sNaN. |
| 1538 | |
| 1539 | Arguments: |
| 1540 | self - Decimal instance |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1541 | context - context used. |
| 1542 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1543 | if self._is_special: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1544 | return self |
| 1545 | if context is None: |
| 1546 | context = getcontext() |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1547 | prec = context.prec |
Facundo Batista | 99b5548 | 2004-10-26 23:38:46 +0000 | [diff] [blame] | 1548 | ans = self._fixexponents(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1549 | if len(ans._int) > prec: |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1550 | ans = ans._round(prec, context=context) |
Facundo Batista | 99b5548 | 2004-10-26 23:38:46 +0000 | [diff] [blame] | 1551 | ans = ans._fixexponents(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1552 | return ans |
| 1553 | |
Facundo Batista | 99b5548 | 2004-10-26 23:38:46 +0000 | [diff] [blame] | 1554 | def _fixexponents(self, context): |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1555 | """Fix the exponents and return a copy with the exponent in bounds. |
| 1556 | Only call if known to not be a special value. |
| 1557 | """ |
| 1558 | folddown = context._clamp |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1559 | Emin = context.Emin |
Facundo Batista | 99b5548 | 2004-10-26 23:38:46 +0000 | [diff] [blame] | 1560 | ans = self |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1561 | ans_adjusted = ans.adjusted() |
| 1562 | if ans_adjusted < Emin: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1563 | Etiny = context.Etiny() |
| 1564 | if ans._exp < Etiny: |
| 1565 | if not ans: |
Facundo Batista | 99b5548 | 2004-10-26 23:38:46 +0000 | [diff] [blame] | 1566 | ans = Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1567 | ans._exp = Etiny |
| 1568 | context._raise_error(Clamped) |
| 1569 | return ans |
| 1570 | ans = ans._rescale(Etiny, context=context) |
| 1571 | #It isn't zero, and exp < Emin => subnormal |
| 1572 | context._raise_error(Subnormal) |
| 1573 | if context.flags[Inexact]: |
| 1574 | context._raise_error(Underflow) |
| 1575 | else: |
| 1576 | if ans: |
| 1577 | #Only raise subnormal if non-zero. |
| 1578 | context._raise_error(Subnormal) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1579 | else: |
| 1580 | Etop = context.Etop() |
| 1581 | if folddown and ans._exp > Etop: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1582 | context._raise_error(Clamped) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1583 | ans = ans._rescale(Etop, context=context) |
| 1584 | else: |
| 1585 | Emax = context.Emax |
| 1586 | if ans_adjusted > Emax: |
| 1587 | if not ans: |
Facundo Batista | 99b5548 | 2004-10-26 23:38:46 +0000 | [diff] [blame] | 1588 | ans = Decimal(self) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1589 | ans._exp = Emax |
| 1590 | context._raise_error(Clamped) |
| 1591 | return ans |
| 1592 | context._raise_error(Inexact) |
| 1593 | context._raise_error(Rounded) |
| 1594 | return context._raise_error(Overflow, 'above Emax', ans._sign) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1595 | return ans |
| 1596 | |
| 1597 | def _round(self, prec=None, rounding=None, context=None): |
| 1598 | """Returns a rounded version of self. |
| 1599 | |
| 1600 | You can specify the precision or rounding method. Otherwise, the |
| 1601 | context determines it. |
| 1602 | """ |
| 1603 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1604 | if self._is_special: |
| 1605 | ans = self._check_nans(context=context) |
| 1606 | if ans: |
| 1607 | return ans |
| 1608 | |
| 1609 | if self._isinfinity(): |
| 1610 | return Decimal(self) |
| 1611 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1612 | if context is None: |
| 1613 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1614 | |
| 1615 | if rounding is None: |
| 1616 | rounding = context.rounding |
| 1617 | if prec is None: |
| 1618 | prec = context.prec |
| 1619 | |
| 1620 | if not self: |
| 1621 | if prec <= 0: |
| 1622 | dig = (0,) |
| 1623 | exp = len(self._int) - prec + self._exp |
| 1624 | else: |
| 1625 | dig = (0,) * prec |
| 1626 | exp = len(self._int) + self._exp - prec |
| 1627 | ans = Decimal((self._sign, dig, exp)) |
| 1628 | context._raise_error(Rounded) |
| 1629 | return ans |
| 1630 | |
| 1631 | if prec == 0: |
| 1632 | temp = Decimal(self) |
| 1633 | temp._int = (0,)+temp._int |
| 1634 | prec = 1 |
| 1635 | elif prec < 0: |
| 1636 | exp = self._exp + len(self._int) - prec - 1 |
| 1637 | temp = Decimal( (self._sign, (0, 1), exp)) |
| 1638 | prec = 1 |
| 1639 | else: |
| 1640 | temp = Decimal(self) |
| 1641 | |
| 1642 | numdigits = len(temp._int) |
| 1643 | if prec == numdigits: |
| 1644 | return temp |
| 1645 | |
| 1646 | # See if we need to extend precision |
| 1647 | expdiff = prec - numdigits |
| 1648 | if expdiff > 0: |
| 1649 | tmp = list(temp._int) |
| 1650 | tmp.extend([0] * expdiff) |
| 1651 | ans = Decimal( (temp._sign, tmp, temp._exp - expdiff)) |
| 1652 | return ans |
| 1653 | |
| 1654 | #OK, but maybe all the lost digits are 0. |
| 1655 | lostdigits = self._int[expdiff:] |
| 1656 | if lostdigits == (0,) * len(lostdigits): |
| 1657 | ans = Decimal( (temp._sign, temp._int[:prec], temp._exp - expdiff)) |
| 1658 | #Rounded, but not Inexact |
| 1659 | context._raise_error(Rounded) |
| 1660 | return ans |
| 1661 | |
| 1662 | # Okay, let's round and lose data |
| 1663 | |
| 1664 | this_function = getattr(temp, self._pick_rounding_function[rounding]) |
| 1665 | #Now we've got the rounding function |
| 1666 | |
| 1667 | if prec != context.prec: |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 1668 | context = context._shallow_copy() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1669 | context.prec = prec |
| 1670 | ans = this_function(prec, expdiff, context) |
| 1671 | context._raise_error(Rounded) |
| 1672 | context._raise_error(Inexact, 'Changed in rounding') |
| 1673 | |
| 1674 | return ans |
| 1675 | |
| 1676 | _pick_rounding_function = {} |
| 1677 | |
| 1678 | def _round_down(self, prec, expdiff, context): |
| 1679 | """Also known as round-towards-0, truncate.""" |
| 1680 | return Decimal( (self._sign, self._int[:prec], self._exp - expdiff) ) |
| 1681 | |
| 1682 | def _round_half_up(self, prec, expdiff, context, tmp = None): |
| 1683 | """Rounds 5 up (away from 0)""" |
| 1684 | |
| 1685 | if tmp is None: |
| 1686 | tmp = Decimal( (self._sign,self._int[:prec], self._exp - expdiff)) |
| 1687 | if self._int[prec] >= 5: |
| 1688 | tmp = tmp._increment(round=0, context=context) |
| 1689 | if len(tmp._int) > prec: |
| 1690 | return Decimal( (tmp._sign, tmp._int[:-1], tmp._exp + 1)) |
| 1691 | return tmp |
| 1692 | |
| 1693 | def _round_half_even(self, prec, expdiff, context): |
| 1694 | """Round 5 to even, rest to nearest.""" |
| 1695 | |
| 1696 | tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff)) |
| 1697 | half = (self._int[prec] == 5) |
| 1698 | if half: |
| 1699 | for digit in self._int[prec+1:]: |
| 1700 | if digit != 0: |
| 1701 | half = 0 |
| 1702 | break |
| 1703 | if half: |
Raymond Hettinger | 61992ef | 2004-08-06 23:42:16 +0000 | [diff] [blame] | 1704 | if self._int[prec-1] & 1 == 0: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1705 | return tmp |
| 1706 | return self._round_half_up(prec, expdiff, context, tmp) |
| 1707 | |
| 1708 | def _round_half_down(self, prec, expdiff, context): |
| 1709 | """Round 5 down""" |
| 1710 | |
| 1711 | tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff)) |
| 1712 | half = (self._int[prec] == 5) |
| 1713 | if half: |
| 1714 | for digit in self._int[prec+1:]: |
| 1715 | if digit != 0: |
| 1716 | half = 0 |
| 1717 | break |
| 1718 | if half: |
| 1719 | return tmp |
| 1720 | return self._round_half_up(prec, expdiff, context, tmp) |
| 1721 | |
| 1722 | def _round_up(self, prec, expdiff, context): |
| 1723 | """Rounds away from 0.""" |
| 1724 | tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff) ) |
| 1725 | for digit in self._int[prec:]: |
| 1726 | if digit != 0: |
| 1727 | tmp = tmp._increment(round=1, context=context) |
| 1728 | if len(tmp._int) > prec: |
| 1729 | return Decimal( (tmp._sign, tmp._int[:-1], tmp._exp + 1)) |
| 1730 | else: |
| 1731 | return tmp |
| 1732 | return tmp |
| 1733 | |
| 1734 | def _round_ceiling(self, prec, expdiff, context): |
| 1735 | """Rounds up (not away from 0 if negative.)""" |
| 1736 | if self._sign: |
| 1737 | return self._round_down(prec, expdiff, context) |
| 1738 | else: |
| 1739 | return self._round_up(prec, expdiff, context) |
| 1740 | |
| 1741 | def _round_floor(self, prec, expdiff, context): |
| 1742 | """Rounds down (not towards 0 if negative)""" |
| 1743 | if not self._sign: |
| 1744 | return self._round_down(prec, expdiff, context) |
| 1745 | else: |
| 1746 | return self._round_up(prec, expdiff, context) |
| 1747 | |
| 1748 | def __pow__(self, n, modulo = None, context=None): |
| 1749 | """Return self ** n (mod modulo) |
| 1750 | |
| 1751 | If modulo is None (default), don't take it mod modulo. |
| 1752 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1753 | n = _convert_other(n) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1754 | if n is NotImplemented: |
| 1755 | return n |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1756 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1757 | if context is None: |
| 1758 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1759 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1760 | if self._is_special or n._is_special or n.adjusted() > 8: |
| 1761 | #Because the spot << doesn't work with really big exponents |
| 1762 | if n._isinfinity() or n.adjusted() > 8: |
| 1763 | return context._raise_error(InvalidOperation, 'x ** INF') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1764 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1765 | ans = self._check_nans(n, context) |
| 1766 | if ans: |
| 1767 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1768 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1769 | if not n._isinteger(): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1770 | return context._raise_error(InvalidOperation, 'x ** (non-integer)') |
| 1771 | |
| 1772 | if not self and not n: |
| 1773 | return context._raise_error(InvalidOperation, '0 ** 0') |
| 1774 | |
| 1775 | if not n: |
| 1776 | return Decimal(1) |
| 1777 | |
| 1778 | if self == Decimal(1): |
| 1779 | return Decimal(1) |
| 1780 | |
| 1781 | sign = self._sign and not n._iseven() |
| 1782 | n = int(n) |
| 1783 | |
| 1784 | if self._isinfinity(): |
| 1785 | if modulo: |
| 1786 | return context._raise_error(InvalidOperation, 'INF % x') |
| 1787 | if n > 0: |
| 1788 | return Infsign[sign] |
| 1789 | return Decimal( (sign, (0,), 0) ) |
| 1790 | |
| 1791 | #with ludicrously large exponent, just raise an overflow and return inf. |
| 1792 | if not modulo and n > 0 and (self._exp + len(self._int) - 1) * n > context.Emax \ |
| 1793 | and self: |
| 1794 | |
| 1795 | tmp = Decimal('inf') |
| 1796 | tmp._sign = sign |
| 1797 | context._raise_error(Rounded) |
| 1798 | context._raise_error(Inexact) |
| 1799 | context._raise_error(Overflow, 'Big power', sign) |
| 1800 | return tmp |
| 1801 | |
| 1802 | elength = len(str(abs(n))) |
| 1803 | firstprec = context.prec |
| 1804 | |
Raymond Hettinger | 99148e7 | 2004-07-14 19:56:56 +0000 | [diff] [blame] | 1805 | if not modulo and firstprec + elength + 1 > DefaultContext.Emax: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1806 | return context._raise_error(Overflow, 'Too much precision.', sign) |
| 1807 | |
| 1808 | mul = Decimal(self) |
| 1809 | val = Decimal(1) |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 1810 | context = context._shallow_copy() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1811 | context.prec = firstprec + elength + 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1812 | if n < 0: |
| 1813 | #n is a long now, not Decimal instance |
| 1814 | n = -n |
Neal Norwitz | bcc0db8 | 2006-03-24 08:14:36 +0000 | [diff] [blame] | 1815 | mul = Decimal(1).__truediv__(mul, context=context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1816 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1817 | spot = 1 |
| 1818 | while spot <= n: |
| 1819 | spot <<= 1 |
| 1820 | |
| 1821 | spot >>= 1 |
| 1822 | #Spot is the highest power of 2 less than n |
| 1823 | while spot: |
| 1824 | val = val.__mul__(val, context=context) |
| 1825 | if val._isinfinity(): |
| 1826 | val = Infsign[sign] |
| 1827 | break |
| 1828 | if spot & n: |
| 1829 | val = val.__mul__(mul, context=context) |
| 1830 | if modulo is not None: |
| 1831 | val = val.__mod__(modulo, context=context) |
| 1832 | spot >>= 1 |
| 1833 | context.prec = firstprec |
| 1834 | |
Raymond Hettinger | 76e60d6 | 2004-10-20 06:58:28 +0000 | [diff] [blame] | 1835 | if context._rounding_decision == ALWAYS_ROUND: |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1836 | return val._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1837 | return val |
| 1838 | |
| 1839 | def __rpow__(self, other, context=None): |
| 1840 | """Swaps self/other and returns __pow__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1841 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1842 | if other is NotImplemented: |
| 1843 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1844 | return other.__pow__(self, context=context) |
| 1845 | |
| 1846 | def normalize(self, context=None): |
| 1847 | """Normalize- strip trailing 0s, change anything equal to 0 to 0e0""" |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1848 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1849 | if self._is_special: |
| 1850 | ans = self._check_nans(context=context) |
| 1851 | if ans: |
| 1852 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1853 | |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1854 | dup = self._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1855 | if dup._isinfinity(): |
| 1856 | return dup |
| 1857 | |
| 1858 | if not dup: |
| 1859 | return Decimal( (dup._sign, (0,), 0) ) |
| 1860 | end = len(dup._int) |
| 1861 | exp = dup._exp |
| 1862 | while dup._int[end-1] == 0: |
| 1863 | exp += 1 |
| 1864 | end -= 1 |
| 1865 | return Decimal( (dup._sign, dup._int[:end], exp) ) |
| 1866 | |
| 1867 | |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1868 | def quantize(self, exp, rounding=None, context=None, watchexp=1): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1869 | """Quantize self so its exponent is the same as that of exp. |
| 1870 | |
| 1871 | Similar to self._rescale(exp._exp) but with error checking. |
| 1872 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1873 | if self._is_special or exp._is_special: |
| 1874 | ans = self._check_nans(exp, context) |
| 1875 | if ans: |
| 1876 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1877 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1878 | if exp._isinfinity() or self._isinfinity(): |
| 1879 | if exp._isinfinity() and self._isinfinity(): |
| 1880 | return self #if both are inf, it is OK |
| 1881 | if context is None: |
| 1882 | context = getcontext() |
| 1883 | return context._raise_error(InvalidOperation, |
| 1884 | 'quantize with one INF') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1885 | return self._rescale(exp._exp, rounding, context, watchexp) |
| 1886 | |
| 1887 | def same_quantum(self, other): |
| 1888 | """Test whether self and other have the same exponent. |
| 1889 | |
| 1890 | same as self._exp == other._exp, except NaN == sNaN |
| 1891 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1892 | if self._is_special or other._is_special: |
| 1893 | if self._isnan() or other._isnan(): |
| 1894 | return self._isnan() and other._isnan() and True |
| 1895 | if self._isinfinity() or other._isinfinity(): |
| 1896 | return self._isinfinity() and other._isinfinity() and True |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1897 | return self._exp == other._exp |
| 1898 | |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1899 | def _rescale(self, exp, rounding=None, context=None, watchexp=1): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1900 | """Rescales so that the exponent is exp. |
| 1901 | |
| 1902 | exp = exp to scale to (an integer) |
| 1903 | rounding = rounding version |
| 1904 | watchexp: if set (default) an error is returned if exp is greater |
| 1905 | than Emax or less than Etiny. |
| 1906 | """ |
| 1907 | if context is None: |
| 1908 | context = getcontext() |
| 1909 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1910 | if self._is_special: |
| 1911 | if self._isinfinity(): |
| 1912 | return context._raise_error(InvalidOperation, 'rescale with an INF') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1913 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1914 | ans = self._check_nans(context=context) |
| 1915 | if ans: |
| 1916 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1917 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1918 | if watchexp and (context.Emax < exp or context.Etiny() > exp): |
| 1919 | return context._raise_error(InvalidOperation, 'rescale(a, INF)') |
| 1920 | |
| 1921 | if not self: |
| 1922 | ans = Decimal(self) |
| 1923 | ans._int = (0,) |
| 1924 | ans._exp = exp |
| 1925 | return ans |
| 1926 | |
| 1927 | diff = self._exp - exp |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1928 | digits = len(self._int) + diff |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1929 | |
| 1930 | if watchexp and digits > context.prec: |
| 1931 | return context._raise_error(InvalidOperation, 'Rescale > prec') |
| 1932 | |
| 1933 | tmp = Decimal(self) |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1934 | tmp._int = (0,) + tmp._int |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1935 | digits += 1 |
| 1936 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1937 | if digits < 0: |
| 1938 | tmp._exp = -digits + tmp._exp |
| 1939 | tmp._int = (0,1) |
| 1940 | digits = 1 |
| 1941 | tmp = tmp._round(digits, rounding, context=context) |
| 1942 | |
| 1943 | if tmp._int[0] == 0 and len(tmp._int) > 1: |
| 1944 | tmp._int = tmp._int[1:] |
| 1945 | tmp._exp = exp |
| 1946 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1947 | tmp_adjusted = tmp.adjusted() |
| 1948 | if tmp and tmp_adjusted < context.Emin: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1949 | context._raise_error(Subnormal) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1950 | elif tmp and tmp_adjusted > context.Emax: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1951 | return context._raise_error(InvalidOperation, 'rescale(a, INF)') |
| 1952 | return tmp |
| 1953 | |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1954 | def to_integral(self, rounding=None, context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1955 | """Rounds to the nearest integer, without raising inexact, rounded.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1956 | if self._is_special: |
| 1957 | ans = self._check_nans(context=context) |
| 1958 | if ans: |
| 1959 | return ans |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 1960 | return self |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1961 | if self._exp >= 0: |
| 1962 | return self |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1963 | if context is None: |
| 1964 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1965 | flags = context._ignore_flags(Rounded, Inexact) |
| 1966 | ans = self._rescale(0, rounding, context=context) |
| 1967 | context._regard_flags(flags) |
| 1968 | return ans |
| 1969 | |
| 1970 | def sqrt(self, context=None): |
| 1971 | """Return the square root of self. |
| 1972 | |
| 1973 | Uses a converging algorithm (Xn+1 = 0.5*(Xn + self / Xn)) |
| 1974 | Should quadratically approach the right answer. |
| 1975 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1976 | if self._is_special: |
| 1977 | ans = self._check_nans(context=context) |
| 1978 | if ans: |
| 1979 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1980 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1981 | if self._isinfinity() and self._sign == 0: |
| 1982 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1983 | |
| 1984 | if not self: |
| 1985 | #exponent = self._exp / 2, using round_down. |
| 1986 | #if self._exp < 0: |
| 1987 | # exp = (self._exp+1) // 2 |
| 1988 | #else: |
| 1989 | exp = (self._exp) // 2 |
| 1990 | if self._sign == 1: |
| 1991 | #sqrt(-0) = -0 |
| 1992 | return Decimal( (1, (0,), exp)) |
| 1993 | else: |
| 1994 | return Decimal( (0, (0,), exp)) |
| 1995 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1996 | if context is None: |
| 1997 | context = getcontext() |
| 1998 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1999 | if self._sign == 1: |
| 2000 | return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0') |
| 2001 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2002 | tmp = Decimal(self) |
| 2003 | |
Raymond Hettinger | 4837a22 | 2004-09-27 14:23:40 +0000 | [diff] [blame] | 2004 | expadd = tmp._exp // 2 |
Raymond Hettinger | 61992ef | 2004-08-06 23:42:16 +0000 | [diff] [blame] | 2005 | if tmp._exp & 1: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2006 | tmp._int += (0,) |
| 2007 | tmp._exp = 0 |
| 2008 | else: |
| 2009 | tmp._exp = 0 |
| 2010 | |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 2011 | context = context._shallow_copy() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2012 | flags = context._ignore_all_flags() |
| 2013 | firstprec = context.prec |
| 2014 | context.prec = 3 |
Raymond Hettinger | 61992ef | 2004-08-06 23:42:16 +0000 | [diff] [blame] | 2015 | if tmp.adjusted() & 1 == 0: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2016 | ans = Decimal( (0, (8,1,9), tmp.adjusted() - 2) ) |
| 2017 | ans = ans.__add__(tmp.__mul__(Decimal((0, (2,5,9), -2)), |
| 2018 | context=context), context=context) |
Raymond Hettinger | 4837a22 | 2004-09-27 14:23:40 +0000 | [diff] [blame] | 2019 | ans._exp -= 1 + tmp.adjusted() // 2 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2020 | else: |
| 2021 | ans = Decimal( (0, (2,5,9), tmp._exp + len(tmp._int)- 3) ) |
| 2022 | ans = ans.__add__(tmp.__mul__(Decimal((0, (8,1,9), -3)), |
| 2023 | context=context), context=context) |
Raymond Hettinger | 4837a22 | 2004-09-27 14:23:40 +0000 | [diff] [blame] | 2024 | ans._exp -= 1 + tmp.adjusted() // 2 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2025 | |
| 2026 | #ans is now a linear approximation. |
| 2027 | |
| 2028 | Emax, Emin = context.Emax, context.Emin |
Raymond Hettinger | 99148e7 | 2004-07-14 19:56:56 +0000 | [diff] [blame] | 2029 | context.Emax, context.Emin = DefaultContext.Emax, DefaultContext.Emin |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2030 | |
| 2031 | half = Decimal('0.5') |
| 2032 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2033 | maxp = firstprec + 2 |
| 2034 | rounding = context._set_rounding(ROUND_HALF_EVEN) |
| 2035 | while 1: |
| 2036 | context.prec = min(2*context.prec - 2, maxp) |
Neal Norwitz | bcc0db8 | 2006-03-24 08:14:36 +0000 | [diff] [blame] | 2037 | ans = half.__mul__(ans.__add__(tmp.__truediv__(ans, context=context), |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2038 | context=context), context=context) |
| 2039 | if context.prec == maxp: |
| 2040 | break |
| 2041 | |
| 2042 | #round to the answer's precision-- the only error can be 1 ulp. |
| 2043 | context.prec = firstprec |
| 2044 | prevexp = ans.adjusted() |
| 2045 | ans = ans._round(context=context) |
| 2046 | |
| 2047 | #Now, check if the other last digits are better. |
| 2048 | context.prec = firstprec + 1 |
| 2049 | # In case we rounded up another digit and we should actually go lower. |
| 2050 | if prevexp != ans.adjusted(): |
| 2051 | ans._int += (0,) |
| 2052 | ans._exp -= 1 |
| 2053 | |
| 2054 | |
| 2055 | lower = ans.__sub__(Decimal((0, (5,), ans._exp-1)), context=context) |
| 2056 | context._set_rounding(ROUND_UP) |
| 2057 | if lower.__mul__(lower, context=context) > (tmp): |
| 2058 | ans = ans.__sub__(Decimal((0, (1,), ans._exp)), context=context) |
| 2059 | |
| 2060 | else: |
| 2061 | upper = ans.__add__(Decimal((0, (5,), ans._exp-1)),context=context) |
| 2062 | context._set_rounding(ROUND_DOWN) |
| 2063 | if upper.__mul__(upper, context=context) < tmp: |
| 2064 | ans = ans.__add__(Decimal((0, (1,), ans._exp)),context=context) |
| 2065 | |
| 2066 | ans._exp += expadd |
| 2067 | |
| 2068 | context.prec = firstprec |
| 2069 | context.rounding = rounding |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 2070 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2071 | |
| 2072 | rounding = context._set_rounding_decision(NEVER_ROUND) |
| 2073 | if not ans.__mul__(ans, context=context) == self: |
| 2074 | # Only rounded/inexact if here. |
| 2075 | context._regard_flags(flags) |
| 2076 | context._raise_error(Rounded) |
| 2077 | context._raise_error(Inexact) |
| 2078 | else: |
| 2079 | #Exact answer, so let's set the exponent right. |
| 2080 | #if self._exp < 0: |
| 2081 | # exp = (self._exp +1)// 2 |
| 2082 | #else: |
| 2083 | exp = self._exp // 2 |
| 2084 | context.prec += ans._exp - exp |
| 2085 | ans = ans._rescale(exp, context=context) |
| 2086 | context.prec = firstprec |
| 2087 | context._regard_flags(flags) |
| 2088 | context.Emax, context.Emin = Emax, Emin |
| 2089 | |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 2090 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2091 | |
| 2092 | def max(self, other, context=None): |
| 2093 | """Returns the larger value. |
| 2094 | |
| 2095 | like max(self, other) except if one is not a number, returns |
| 2096 | NaN (and signals if one is sNaN). Also rounds. |
| 2097 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2098 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 2099 | if other is NotImplemented: |
| 2100 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2101 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2102 | if self._is_special or other._is_special: |
| 2103 | # if one operand is a quiet NaN and the other is number, then the |
| 2104 | # number is always returned |
| 2105 | sn = self._isnan() |
| 2106 | on = other._isnan() |
| 2107 | if sn or on: |
| 2108 | if on == 1 and sn != 2: |
| 2109 | return self |
| 2110 | if sn == 1 and on != 2: |
| 2111 | return other |
| 2112 | return self._check_nans(other, context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2113 | |
| 2114 | ans = self |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2115 | c = self.__cmp__(other) |
| 2116 | if c == 0: |
| 2117 | # if both operands are finite and equal in numerical value |
| 2118 | # then an ordering is applied: |
| 2119 | # |
| 2120 | # if the signs differ then max returns the operand with the |
| 2121 | # positive sign and min returns the operand with the negative sign |
| 2122 | # |
| 2123 | # if the signs are the same then the exponent is used to select |
| 2124 | # the result. |
| 2125 | if self._sign != other._sign: |
| 2126 | if self._sign: |
| 2127 | ans = other |
| 2128 | elif self._exp < other._exp and not self._sign: |
| 2129 | ans = other |
| 2130 | elif self._exp > other._exp and self._sign: |
| 2131 | ans = other |
| 2132 | elif c == -1: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2133 | ans = other |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2134 | |
| 2135 | if context is None: |
| 2136 | context = getcontext() |
Raymond Hettinger | 76e60d6 | 2004-10-20 06:58:28 +0000 | [diff] [blame] | 2137 | if context._rounding_decision == ALWAYS_ROUND: |
| 2138 | return ans._fix(context) |
| 2139 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2140 | |
| 2141 | def min(self, other, context=None): |
| 2142 | """Returns the smaller value. |
| 2143 | |
| 2144 | like min(self, other) except if one is not a number, returns |
| 2145 | NaN (and signals if one is sNaN). Also rounds. |
| 2146 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2147 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 2148 | if other is NotImplemented: |
| 2149 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2150 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2151 | if self._is_special or other._is_special: |
| 2152 | # if one operand is a quiet NaN and the other is number, then the |
| 2153 | # number is always returned |
| 2154 | sn = self._isnan() |
| 2155 | on = other._isnan() |
| 2156 | if sn or on: |
| 2157 | if on == 1 and sn != 2: |
| 2158 | return self |
| 2159 | if sn == 1 and on != 2: |
| 2160 | return other |
| 2161 | return self._check_nans(other, context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2162 | |
| 2163 | ans = self |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2164 | c = self.__cmp__(other) |
| 2165 | if c == 0: |
| 2166 | # if both operands are finite and equal in numerical value |
| 2167 | # then an ordering is applied: |
| 2168 | # |
| 2169 | # if the signs differ then max returns the operand with the |
| 2170 | # positive sign and min returns the operand with the negative sign |
| 2171 | # |
| 2172 | # if the signs are the same then the exponent is used to select |
| 2173 | # the result. |
| 2174 | if self._sign != other._sign: |
| 2175 | if other._sign: |
| 2176 | ans = other |
| 2177 | elif self._exp > other._exp and not self._sign: |
| 2178 | ans = other |
| 2179 | elif self._exp < other._exp and self._sign: |
| 2180 | ans = other |
| 2181 | elif c == 1: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2182 | ans = other |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2183 | |
| 2184 | if context is None: |
| 2185 | context = getcontext() |
Raymond Hettinger | 76e60d6 | 2004-10-20 06:58:28 +0000 | [diff] [blame] | 2186 | if context._rounding_decision == ALWAYS_ROUND: |
| 2187 | return ans._fix(context) |
| 2188 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2189 | |
| 2190 | def _isinteger(self): |
| 2191 | """Returns whether self is an integer""" |
| 2192 | if self._exp >= 0: |
| 2193 | return True |
| 2194 | rest = self._int[self._exp:] |
| 2195 | return rest == (0,)*len(rest) |
| 2196 | |
| 2197 | def _iseven(self): |
| 2198 | """Returns 1 if self is even. Assumes self is an integer.""" |
| 2199 | if self._exp > 0: |
| 2200 | return 1 |
Raymond Hettinger | 61992ef | 2004-08-06 23:42:16 +0000 | [diff] [blame] | 2201 | return self._int[-1+self._exp] & 1 == 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2202 | |
| 2203 | def adjusted(self): |
| 2204 | """Return the adjusted exponent of self""" |
| 2205 | try: |
| 2206 | return self._exp + len(self._int) - 1 |
| 2207 | #If NaN or Infinity, self._exp is string |
| 2208 | except TypeError: |
| 2209 | return 0 |
| 2210 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2211 | # support for pickling, copy, and deepcopy |
| 2212 | def __reduce__(self): |
| 2213 | return (self.__class__, (str(self),)) |
| 2214 | |
| 2215 | def __copy__(self): |
| 2216 | if type(self) == Decimal: |
| 2217 | return self # I'm immutable; therefore I am my own clone |
| 2218 | return self.__class__(str(self)) |
| 2219 | |
| 2220 | def __deepcopy__(self, memo): |
| 2221 | if type(self) == Decimal: |
| 2222 | return self # My components are also immutable |
| 2223 | return self.__class__(str(self)) |
| 2224 | |
Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 2225 | ##### Context class ########################################### |
| 2226 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2227 | |
| 2228 | # get rounding method function: |
| 2229 | rounding_functions = [name for name in Decimal.__dict__.keys() if name.startswith('_round_')] |
| 2230 | for name in rounding_functions: |
| 2231 | #name is like _round_half_even, goes to the global ROUND_HALF_EVEN value. |
| 2232 | globalname = name[1:].upper() |
| 2233 | val = globals()[globalname] |
| 2234 | Decimal._pick_rounding_function[val] = name |
| 2235 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2236 | del name, val, globalname, rounding_functions |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2237 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 2238 | class _ContextManager(object): |
| 2239 | """Context manager class to support localcontext(). |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 2240 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 2241 | Sets a copy of the supplied context in __enter__() and restores |
| 2242 | the previous decimal context in __exit__() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 2243 | """ |
| 2244 | def __init__(self, new_context): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 2245 | self.new_context = new_context.copy() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 2246 | def __enter__(self): |
| 2247 | self.saved_context = getcontext() |
| 2248 | setcontext(self.new_context) |
| 2249 | return self.new_context |
| 2250 | def __exit__(self, t, v, tb): |
| 2251 | setcontext(self.saved_context) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 2252 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2253 | class Context(object): |
| 2254 | """Contains the context for a Decimal instance. |
| 2255 | |
| 2256 | Contains: |
| 2257 | prec - precision (for use in rounding, division, square roots..) |
| 2258 | rounding - rounding type. (how you round) |
| 2259 | _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round? |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 2260 | traps - If traps[exception] = 1, then the exception is |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2261 | raised when it is caused. Otherwise, a value is |
| 2262 | substituted in. |
| 2263 | flags - When an exception is caused, flags[exception] is incremented. |
| 2264 | (Whether or not the trap_enabler is set) |
| 2265 | Should be reset by user of Decimal instance. |
Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 2266 | Emin - Minimum exponent |
| 2267 | Emax - Maximum exponent |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2268 | capitals - If 1, 1*10^1 is printed as 1E+1. |
| 2269 | If 0, printed as 1e1 |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 2270 | _clamp - If 1, change exponents if too high (Default 0) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2271 | """ |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2272 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2273 | def __init__(self, prec=None, rounding=None, |
Raymond Hettinger | abf8a56 | 2004-10-12 09:12:16 +0000 | [diff] [blame] | 2274 | traps=None, flags=None, |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2275 | _rounding_decision=None, |
Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 2276 | Emin=None, Emax=None, |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 2277 | capitals=None, _clamp=0, |
Raymond Hettinger | abf8a56 | 2004-10-12 09:12:16 +0000 | [diff] [blame] | 2278 | _ignored_flags=None): |
| 2279 | if flags is None: |
| 2280 | flags = [] |
| 2281 | if _ignored_flags is None: |
| 2282 | _ignored_flags = [] |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 2283 | if not isinstance(flags, dict): |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 2284 | flags = dict([(s,s in flags) for s in _signals]) |
Raymond Hettinger | b91af52 | 2004-07-14 16:35:30 +0000 | [diff] [blame] | 2285 | del s |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 2286 | if traps is not None and not isinstance(traps, dict): |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 2287 | traps = dict([(s,s in traps) for s in _signals]) |
Raymond Hettinger | b91af52 | 2004-07-14 16:35:30 +0000 | [diff] [blame] | 2288 | del s |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2289 | for name, val in locals().items(): |
| 2290 | if val is None: |
Raymond Hettinger | eb26084 | 2005-06-07 18:52:34 +0000 | [diff] [blame] | 2291 | setattr(self, name, _copy.copy(getattr(DefaultContext, name))) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2292 | else: |
| 2293 | setattr(self, name, val) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2294 | del self.self |
| 2295 | |
Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 2296 | def __repr__(self): |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 2297 | """Show the current context.""" |
Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 2298 | s = [] |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 2299 | s.append('Context(prec=%(prec)d, rounding=%(rounding)s, Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d' % vars(self)) |
| 2300 | s.append('flags=[' + ', '.join([f.__name__ for f, v in self.flags.items() if v]) + ']') |
| 2301 | s.append('traps=[' + ', '.join([t.__name__ for t, v in self.traps.items() if v]) + ']') |
Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 2302 | return ', '.join(s) + ')' |
| 2303 | |
Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 2304 | def clear_flags(self): |
| 2305 | """Reset all flags to zero""" |
| 2306 | for flag in self.flags: |
Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 2307 | self.flags[flag] = 0 |
Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 2308 | |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 2309 | def _shallow_copy(self): |
| 2310 | """Returns a shallow copy from self.""" |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 2311 | nc = Context(self.prec, self.rounding, self.traps, self.flags, |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2312 | self._rounding_decision, self.Emin, self.Emax, |
| 2313 | self.capitals, self._clamp, self._ignored_flags) |
| 2314 | return nc |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 2315 | |
| 2316 | def copy(self): |
| 2317 | """Returns a deep copy from self.""" |
| 2318 | nc = Context(self.prec, self.rounding, self.traps.copy(), self.flags.copy(), |
| 2319 | self._rounding_decision, self.Emin, self.Emax, |
| 2320 | self.capitals, self._clamp, self._ignored_flags) |
| 2321 | return nc |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2322 | __copy__ = copy |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2323 | |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 2324 | def _raise_error(self, condition, explanation = None, *args): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2325 | """Handles an error |
| 2326 | |
| 2327 | If the flag is in _ignored_flags, returns the default response. |
| 2328 | Otherwise, it increments the flag, then, if the corresponding |
| 2329 | trap_enabler is set, it reaises the exception. Otherwise, it returns |
| 2330 | the default value after incrementing the flag. |
| 2331 | """ |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 2332 | error = _condition_map.get(condition, condition) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2333 | if error in self._ignored_flags: |
| 2334 | #Don't touch the flag |
| 2335 | return error().handle(self, *args) |
| 2336 | |
| 2337 | self.flags[error] += 1 |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 2338 | if not self.traps[error]: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2339 | #The errors define how to handle themselves. |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 2340 | return condition().handle(self, *args) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2341 | |
| 2342 | # Errors should only be risked on copies of the context |
| 2343 | #self._ignored_flags = [] |
| 2344 | raise error, explanation |
| 2345 | |
| 2346 | def _ignore_all_flags(self): |
| 2347 | """Ignore all flags, if they are raised""" |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 2348 | return self._ignore_flags(*_signals) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2349 | |
| 2350 | def _ignore_flags(self, *flags): |
| 2351 | """Ignore the flags, if they are raised""" |
| 2352 | # Do not mutate-- This way, copies of a context leave the original |
| 2353 | # alone. |
| 2354 | self._ignored_flags = (self._ignored_flags + list(flags)) |
| 2355 | return list(flags) |
| 2356 | |
| 2357 | def _regard_flags(self, *flags): |
| 2358 | """Stop ignoring the flags, if they are raised""" |
| 2359 | if flags and isinstance(flags[0], (tuple,list)): |
| 2360 | flags = flags[0] |
| 2361 | for flag in flags: |
| 2362 | self._ignored_flags.remove(flag) |
| 2363 | |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 2364 | def __hash__(self): |
| 2365 | """A Context cannot be hashed.""" |
| 2366 | # We inherit object.__hash__, so we must deny this explicitly |
| 2367 | raise TypeError, "Cannot hash a Context." |
| 2368 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2369 | def Etiny(self): |
| 2370 | """Returns Etiny (= Emin - prec + 1)""" |
| 2371 | return int(self.Emin - self.prec + 1) |
| 2372 | |
| 2373 | def Etop(self): |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 2374 | """Returns maximum exponent (= Emax - prec + 1)""" |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2375 | return int(self.Emax - self.prec + 1) |
| 2376 | |
| 2377 | def _set_rounding_decision(self, type): |
| 2378 | """Sets the rounding decision. |
| 2379 | |
| 2380 | Sets the rounding decision, and returns the current (previous) |
| 2381 | rounding decision. Often used like: |
| 2382 | |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 2383 | context = context._shallow_copy() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2384 | # That so you don't change the calling context |
| 2385 | # if an error occurs in the middle (say DivisionImpossible is raised). |
| 2386 | |
| 2387 | rounding = context._set_rounding_decision(NEVER_ROUND) |
| 2388 | instance = instance / Decimal(2) |
| 2389 | context._set_rounding_decision(rounding) |
| 2390 | |
| 2391 | This will make it not round for that operation. |
| 2392 | """ |
| 2393 | |
| 2394 | rounding = self._rounding_decision |
| 2395 | self._rounding_decision = type |
| 2396 | return rounding |
| 2397 | |
| 2398 | def _set_rounding(self, type): |
| 2399 | """Sets the rounding type. |
| 2400 | |
| 2401 | Sets the rounding type, and returns the current (previous) |
| 2402 | rounding type. Often used like: |
| 2403 | |
| 2404 | context = context.copy() |
| 2405 | # so you don't change the calling context |
| 2406 | # if an error occurs in the middle. |
| 2407 | rounding = context._set_rounding(ROUND_UP) |
| 2408 | val = self.__sub__(other, context=context) |
| 2409 | context._set_rounding(rounding) |
| 2410 | |
| 2411 | This will make it round up for that operation. |
| 2412 | """ |
| 2413 | rounding = self.rounding |
| 2414 | self.rounding= type |
| 2415 | return rounding |
| 2416 | |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 2417 | def create_decimal(self, num='0'): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2418 | """Creates a new Decimal instance but using self as context.""" |
| 2419 | d = Decimal(num, context=self) |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 2420 | return d._fix(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2421 | |
| 2422 | #Methods |
| 2423 | def abs(self, a): |
| 2424 | """Returns the absolute value of the operand. |
| 2425 | |
| 2426 | If the operand is negative, the result is the same as using the minus |
| 2427 | operation on the operand. Otherwise, the result is the same as using |
| 2428 | the plus operation on the operand. |
| 2429 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2430 | >>> ExtendedContext.abs(Decimal('2.1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2431 | Decimal("2.1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2432 | >>> ExtendedContext.abs(Decimal('-100')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2433 | Decimal("100") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2434 | >>> ExtendedContext.abs(Decimal('101.5')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2435 | Decimal("101.5") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2436 | >>> ExtendedContext.abs(Decimal('-101.5')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2437 | Decimal("101.5") |
| 2438 | """ |
| 2439 | return a.__abs__(context=self) |
| 2440 | |
| 2441 | def add(self, a, b): |
| 2442 | """Return the sum of the two operands. |
| 2443 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2444 | >>> ExtendedContext.add(Decimal('12'), Decimal('7.00')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2445 | Decimal("19.00") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2446 | >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2447 | Decimal("1.02E+4") |
| 2448 | """ |
| 2449 | return a.__add__(b, context=self) |
| 2450 | |
| 2451 | def _apply(self, a): |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 2452 | return str(a._fix(self)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2453 | |
| 2454 | def compare(self, a, b): |
| 2455 | """Compares values numerically. |
| 2456 | |
| 2457 | If the signs of the operands differ, a value representing each operand |
| 2458 | ('-1' if the operand is less than zero, '0' if the operand is zero or |
| 2459 | negative zero, or '1' if the operand is greater than zero) is used in |
| 2460 | place of that operand for the comparison instead of the actual |
| 2461 | operand. |
| 2462 | |
| 2463 | The comparison is then effected by subtracting the second operand from |
| 2464 | the first and then returning a value according to the result of the |
| 2465 | subtraction: '-1' if the result is less than zero, '0' if the result is |
| 2466 | zero or negative zero, or '1' if the result is greater than zero. |
| 2467 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2468 | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2469 | Decimal("-1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2470 | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2471 | Decimal("0") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2472 | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2473 | Decimal("0") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2474 | >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2475 | Decimal("1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2476 | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2477 | Decimal("1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2478 | >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2479 | Decimal("-1") |
| 2480 | """ |
| 2481 | return a.compare(b, context=self) |
| 2482 | |
| 2483 | def divide(self, a, b): |
| 2484 | """Decimal division in a specified context. |
| 2485 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2486 | >>> ExtendedContext.divide(Decimal('1'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2487 | Decimal("0.333333333") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2488 | >>> ExtendedContext.divide(Decimal('2'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2489 | Decimal("0.666666667") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2490 | >>> ExtendedContext.divide(Decimal('5'), Decimal('2')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2491 | Decimal("2.5") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2492 | >>> ExtendedContext.divide(Decimal('1'), Decimal('10')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2493 | Decimal("0.1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2494 | >>> ExtendedContext.divide(Decimal('12'), Decimal('12')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2495 | Decimal("1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2496 | >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2497 | Decimal("4.00") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2498 | >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2499 | Decimal("1.20") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2500 | >>> ExtendedContext.divide(Decimal('1000'), Decimal('100')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2501 | Decimal("10") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2502 | >>> ExtendedContext.divide(Decimal('1000'), Decimal('1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2503 | Decimal("1000") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2504 | >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2505 | Decimal("1.20E+6") |
| 2506 | """ |
Neal Norwitz | bcc0db8 | 2006-03-24 08:14:36 +0000 | [diff] [blame] | 2507 | return a.__truediv__(b, context=self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2508 | |
| 2509 | def divide_int(self, a, b): |
| 2510 | """Divides two numbers and returns the integer part of the result. |
| 2511 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2512 | >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2513 | Decimal("0") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2514 | >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2515 | Decimal("3") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2516 | >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2517 | Decimal("3") |
| 2518 | """ |
| 2519 | return a.__floordiv__(b, context=self) |
| 2520 | |
| 2521 | def divmod(self, a, b): |
| 2522 | return a.__divmod__(b, context=self) |
| 2523 | |
| 2524 | def max(self, a,b): |
| 2525 | """max compares two values numerically and returns the maximum. |
| 2526 | |
| 2527 | If either operand is a NaN then the general rules apply. |
| 2528 | Otherwise, the operands are compared as as though by the compare |
| 2529 | operation. If they are numerically equal then the left-hand operand |
| 2530 | is chosen as the result. Otherwise the maximum (closer to positive |
| 2531 | infinity) of the two operands is chosen as the result. |
| 2532 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2533 | >>> ExtendedContext.max(Decimal('3'), Decimal('2')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2534 | Decimal("3") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2535 | >>> ExtendedContext.max(Decimal('-10'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2536 | Decimal("3") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2537 | >>> ExtendedContext.max(Decimal('1.0'), Decimal('1')) |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2538 | Decimal("1") |
| 2539 | >>> ExtendedContext.max(Decimal('7'), Decimal('NaN')) |
| 2540 | Decimal("7") |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2541 | """ |
| 2542 | return a.max(b, context=self) |
| 2543 | |
| 2544 | def min(self, a,b): |
| 2545 | """min compares two values numerically and returns the minimum. |
| 2546 | |
| 2547 | If either operand is a NaN then the general rules apply. |
| 2548 | Otherwise, the operands are compared as as though by the compare |
| 2549 | operation. If they are numerically equal then the left-hand operand |
| 2550 | is chosen as the result. Otherwise the minimum (closer to negative |
| 2551 | infinity) of the two operands is chosen as the result. |
| 2552 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2553 | >>> ExtendedContext.min(Decimal('3'), Decimal('2')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2554 | Decimal("2") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2555 | >>> ExtendedContext.min(Decimal('-10'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2556 | Decimal("-10") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2557 | >>> ExtendedContext.min(Decimal('1.0'), Decimal('1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2558 | Decimal("1.0") |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2559 | >>> ExtendedContext.min(Decimal('7'), Decimal('NaN')) |
| 2560 | Decimal("7") |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2561 | """ |
| 2562 | return a.min(b, context=self) |
| 2563 | |
| 2564 | def minus(self, a): |
| 2565 | """Minus corresponds to unary prefix minus in Python. |
| 2566 | |
| 2567 | The operation is evaluated using the same rules as subtract; the |
| 2568 | operation minus(a) is calculated as subtract('0', a) where the '0' |
| 2569 | has the same exponent as the operand. |
| 2570 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2571 | >>> ExtendedContext.minus(Decimal('1.3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2572 | Decimal("-1.3") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2573 | >>> ExtendedContext.minus(Decimal('-1.3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2574 | Decimal("1.3") |
| 2575 | """ |
| 2576 | return a.__neg__(context=self) |
| 2577 | |
| 2578 | def multiply(self, a, b): |
| 2579 | """multiply multiplies two operands. |
| 2580 | |
| 2581 | If either operand is a special value then the general rules apply. |
| 2582 | Otherwise, the operands are multiplied together ('long multiplication'), |
| 2583 | resulting in a number which may be as long as the sum of the lengths |
| 2584 | of the two operands. |
| 2585 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2586 | >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2587 | Decimal("3.60") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2588 | >>> ExtendedContext.multiply(Decimal('7'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2589 | Decimal("21") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2590 | >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2591 | Decimal("0.72") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2592 | >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2593 | Decimal("-0.0") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2594 | >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2595 | Decimal("4.28135971E+11") |
| 2596 | """ |
| 2597 | return a.__mul__(b, context=self) |
| 2598 | |
| 2599 | def normalize(self, a): |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 2600 | """normalize reduces an operand to its simplest form. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2601 | |
| 2602 | Essentially a plus operation with all trailing zeros removed from the |
| 2603 | result. |
| 2604 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2605 | >>> ExtendedContext.normalize(Decimal('2.1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2606 | Decimal("2.1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2607 | >>> ExtendedContext.normalize(Decimal('-2.0')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2608 | Decimal("-2") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2609 | >>> ExtendedContext.normalize(Decimal('1.200')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2610 | Decimal("1.2") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2611 | >>> ExtendedContext.normalize(Decimal('-120')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2612 | Decimal("-1.2E+2") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2613 | >>> ExtendedContext.normalize(Decimal('120.00')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2614 | Decimal("1.2E+2") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2615 | >>> ExtendedContext.normalize(Decimal('0.00')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2616 | Decimal("0") |
| 2617 | """ |
| 2618 | return a.normalize(context=self) |
| 2619 | |
| 2620 | def plus(self, a): |
| 2621 | """Plus corresponds to unary prefix plus in Python. |
| 2622 | |
| 2623 | The operation is evaluated using the same rules as add; the |
| 2624 | operation plus(a) is calculated as add('0', a) where the '0' |
| 2625 | has the same exponent as the operand. |
| 2626 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2627 | >>> ExtendedContext.plus(Decimal('1.3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2628 | Decimal("1.3") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2629 | >>> ExtendedContext.plus(Decimal('-1.3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2630 | Decimal("-1.3") |
| 2631 | """ |
| 2632 | return a.__pos__(context=self) |
| 2633 | |
| 2634 | def power(self, a, b, modulo=None): |
| 2635 | """Raises a to the power of b, to modulo if given. |
| 2636 | |
| 2637 | The right-hand operand must be a whole number whose integer part (after |
| 2638 | any exponent has been applied) has no more than 9 digits and whose |
| 2639 | fractional part (if any) is all zeros before any rounding. The operand |
| 2640 | may be positive, negative, or zero; if negative, the absolute value of |
| 2641 | the power is used, and the left-hand operand is inverted (divided into |
| 2642 | 1) before use. |
| 2643 | |
| 2644 | If the increased precision needed for the intermediate calculations |
| 2645 | exceeds the capabilities of the implementation then an Invalid operation |
| 2646 | condition is raised. |
| 2647 | |
| 2648 | If, when raising to a negative power, an underflow occurs during the |
| 2649 | division into 1, the operation is not halted at that point but |
| 2650 | continues. |
| 2651 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2652 | >>> ExtendedContext.power(Decimal('2'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2653 | Decimal("8") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2654 | >>> ExtendedContext.power(Decimal('2'), Decimal('-3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2655 | Decimal("0.125") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2656 | >>> ExtendedContext.power(Decimal('1.7'), Decimal('8')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2657 | Decimal("69.7575744") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2658 | >>> ExtendedContext.power(Decimal('Infinity'), Decimal('-2')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2659 | Decimal("0") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2660 | >>> ExtendedContext.power(Decimal('Infinity'), Decimal('-1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2661 | Decimal("0") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2662 | >>> ExtendedContext.power(Decimal('Infinity'), Decimal('0')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2663 | Decimal("1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2664 | >>> ExtendedContext.power(Decimal('Infinity'), Decimal('1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2665 | Decimal("Infinity") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2666 | >>> ExtendedContext.power(Decimal('Infinity'), Decimal('2')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2667 | Decimal("Infinity") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2668 | >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('-2')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2669 | Decimal("0") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2670 | >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('-1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2671 | Decimal("-0") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2672 | >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('0')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2673 | Decimal("1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2674 | >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2675 | Decimal("-Infinity") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2676 | >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('2')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2677 | Decimal("Infinity") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2678 | >>> ExtendedContext.power(Decimal('0'), Decimal('0')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2679 | Decimal("NaN") |
| 2680 | """ |
| 2681 | return a.__pow__(b, modulo, context=self) |
| 2682 | |
| 2683 | def quantize(self, a, b): |
| 2684 | """Returns a value equal to 'a' (rounded) and having the exponent of 'b'. |
| 2685 | |
| 2686 | The coefficient of the result is derived from that of the left-hand |
| 2687 | operand. It may be rounded using the current rounding setting (if the |
| 2688 | exponent is being increased), multiplied by a positive power of ten (if |
| 2689 | the exponent is being decreased), or is unchanged (if the exponent is |
| 2690 | already equal to that of the right-hand operand). |
| 2691 | |
| 2692 | Unlike other operations, if the length of the coefficient after the |
| 2693 | quantize operation would be greater than precision then an Invalid |
| 2694 | operation condition is raised. This guarantees that, unless there is an |
| 2695 | error condition, the exponent of the result of a quantize is always |
| 2696 | equal to that of the right-hand operand. |
| 2697 | |
| 2698 | Also unlike other operations, quantize will never raise Underflow, even |
| 2699 | if the result is subnormal and inexact. |
| 2700 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2701 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2702 | Decimal("2.170") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2703 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2704 | Decimal("2.17") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2705 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2706 | Decimal("2.2") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2707 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2708 | Decimal("2") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2709 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2710 | Decimal("0E+1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2711 | >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2712 | Decimal("-Infinity") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2713 | >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2714 | Decimal("NaN") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2715 | >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2716 | Decimal("-0") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2717 | >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2718 | Decimal("-0E+5") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2719 | >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2720 | Decimal("NaN") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2721 | >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2722 | Decimal("NaN") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2723 | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2724 | Decimal("217.0") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2725 | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2726 | Decimal("217") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2727 | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2728 | Decimal("2.2E+2") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2729 | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2730 | Decimal("2E+2") |
| 2731 | """ |
| 2732 | return a.quantize(b, context=self) |
| 2733 | |
| 2734 | def remainder(self, a, b): |
| 2735 | """Returns the remainder from integer division. |
| 2736 | |
| 2737 | The result is the residue of the dividend after the operation of |
| 2738 | calculating integer division as described for divide-integer, rounded to |
| 2739 | precision digits if necessary. The sign of the result, if non-zero, is |
| 2740 | the same as that of the original dividend. |
| 2741 | |
| 2742 | This operation will fail under the same conditions as integer division |
| 2743 | (that is, if integer division on the same two operands would fail, the |
| 2744 | remainder cannot be calculated). |
| 2745 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2746 | >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2747 | Decimal("2.1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2748 | >>> ExtendedContext.remainder(Decimal('10'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2749 | Decimal("1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2750 | >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2751 | Decimal("-1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2752 | >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2753 | Decimal("0.2") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2754 | >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2755 | Decimal("0.1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2756 | >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2757 | Decimal("1.0") |
| 2758 | """ |
| 2759 | return a.__mod__(b, context=self) |
| 2760 | |
| 2761 | def remainder_near(self, a, b): |
| 2762 | """Returns to be "a - b * n", where n is the integer nearest the exact |
| 2763 | value of "x / b" (if two integers are equally near then the even one |
| 2764 | is chosen). If the result is equal to 0 then its sign will be the |
| 2765 | sign of a. |
| 2766 | |
| 2767 | This operation will fail under the same conditions as integer division |
| 2768 | (that is, if integer division on the same two operands would fail, the |
| 2769 | remainder cannot be calculated). |
| 2770 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2771 | >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2772 | Decimal("-0.9") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2773 | >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2774 | Decimal("-2") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2775 | >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2776 | Decimal("1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2777 | >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2778 | Decimal("-1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2779 | >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2780 | Decimal("0.2") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2781 | >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2782 | Decimal("0.1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2783 | >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2784 | Decimal("-0.3") |
| 2785 | """ |
| 2786 | return a.remainder_near(b, context=self) |
| 2787 | |
| 2788 | def same_quantum(self, a, b): |
| 2789 | """Returns True if the two operands have the same exponent. |
| 2790 | |
| 2791 | The result is never affected by either the sign or the coefficient of |
| 2792 | either operand. |
| 2793 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2794 | >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2795 | False |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2796 | >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2797 | True |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2798 | >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2799 | False |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2800 | >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2801 | True |
| 2802 | """ |
| 2803 | return a.same_quantum(b) |
| 2804 | |
| 2805 | def sqrt(self, a): |
| 2806 | """Returns the square root of a non-negative number to context precision. |
| 2807 | |
| 2808 | If the result must be inexact, it is rounded using the round-half-even |
| 2809 | algorithm. |
| 2810 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2811 | >>> ExtendedContext.sqrt(Decimal('0')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2812 | Decimal("0") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2813 | >>> ExtendedContext.sqrt(Decimal('-0')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2814 | Decimal("-0") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2815 | >>> ExtendedContext.sqrt(Decimal('0.39')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2816 | Decimal("0.624499800") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2817 | >>> ExtendedContext.sqrt(Decimal('100')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2818 | Decimal("10") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2819 | >>> ExtendedContext.sqrt(Decimal('1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2820 | Decimal("1") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2821 | >>> ExtendedContext.sqrt(Decimal('1.0')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2822 | Decimal("1.0") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2823 | >>> ExtendedContext.sqrt(Decimal('1.00')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2824 | Decimal("1.0") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2825 | >>> ExtendedContext.sqrt(Decimal('7')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2826 | Decimal("2.64575131") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2827 | >>> ExtendedContext.sqrt(Decimal('10')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2828 | Decimal("3.16227766") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2829 | >>> ExtendedContext.prec |
Raymond Hettinger | 6ea4845 | 2004-07-03 12:26:21 +0000 | [diff] [blame] | 2830 | 9 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2831 | """ |
| 2832 | return a.sqrt(context=self) |
| 2833 | |
| 2834 | def subtract(self, a, b): |
Georg Brandl | f33d01d | 2005-08-22 19:35:18 +0000 | [diff] [blame] | 2835 | """Return the difference between the two operands. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2836 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2837 | >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2838 | Decimal("0.23") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2839 | >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2840 | Decimal("0.00") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2841 | >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2842 | Decimal("-0.77") |
| 2843 | """ |
| 2844 | return a.__sub__(b, context=self) |
| 2845 | |
| 2846 | def to_eng_string(self, a): |
| 2847 | """Converts a number to a string, using scientific notation. |
| 2848 | |
| 2849 | The operation is not affected by the context. |
| 2850 | """ |
| 2851 | return a.to_eng_string(context=self) |
| 2852 | |
| 2853 | def to_sci_string(self, a): |
| 2854 | """Converts a number to a string, using scientific notation. |
| 2855 | |
| 2856 | The operation is not affected by the context. |
| 2857 | """ |
| 2858 | return a.__str__(context=self) |
| 2859 | |
| 2860 | def to_integral(self, a): |
| 2861 | """Rounds to an integer. |
| 2862 | |
| 2863 | When the operand has a negative exponent, the result is the same |
| 2864 | as using the quantize() operation using the given operand as the |
| 2865 | left-hand-operand, 1E+0 as the right-hand-operand, and the precision |
| 2866 | of the operand as the precision setting, except that no flags will |
| 2867 | be set. The rounding mode is taken from the context. |
| 2868 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2869 | >>> ExtendedContext.to_integral(Decimal('2.1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2870 | Decimal("2") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2871 | >>> ExtendedContext.to_integral(Decimal('100')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2872 | Decimal("100") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2873 | >>> ExtendedContext.to_integral(Decimal('100.0')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2874 | Decimal("100") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2875 | >>> ExtendedContext.to_integral(Decimal('101.5')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2876 | Decimal("102") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2877 | >>> ExtendedContext.to_integral(Decimal('-101.5')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2878 | Decimal("-102") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2879 | >>> ExtendedContext.to_integral(Decimal('10E+5')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2880 | Decimal("1.0E+6") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2881 | >>> ExtendedContext.to_integral(Decimal('7.89E+77')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2882 | Decimal("7.89E+77") |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 2883 | >>> ExtendedContext.to_integral(Decimal('-Inf')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2884 | Decimal("-Infinity") |
| 2885 | """ |
| 2886 | return a.to_integral(context=self) |
| 2887 | |
| 2888 | class _WorkRep(object): |
| 2889 | __slots__ = ('sign','int','exp') |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 2890 | # sign: 0 or 1 |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2891 | # int: int or long |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2892 | # exp: None, int, or string |
| 2893 | |
| 2894 | def __init__(self, value=None): |
| 2895 | if value is None: |
| 2896 | self.sign = None |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2897 | self.int = 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2898 | self.exp = None |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 2899 | elif isinstance(value, Decimal): |
| 2900 | self.sign = value._sign |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2901 | cum = 0 |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 2902 | for digit in value._int: |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2903 | cum = cum * 10 + digit |
| 2904 | self.int = cum |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2905 | self.exp = value._exp |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 2906 | else: |
| 2907 | # assert isinstance(value, tuple) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2908 | self.sign = value[0] |
| 2909 | self.int = value[1] |
| 2910 | self.exp = value[2] |
| 2911 | |
| 2912 | def __repr__(self): |
| 2913 | return "(%r, %r, %r)" % (self.sign, self.int, self.exp) |
| 2914 | |
| 2915 | __str__ = __repr__ |
| 2916 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2917 | |
| 2918 | |
| 2919 | def _normalize(op1, op2, shouldround = 0, prec = 0): |
| 2920 | """Normalizes op1, op2 to have the same exp and length of coefficient. |
| 2921 | |
| 2922 | Done during addition. |
| 2923 | """ |
| 2924 | # Yes, the exponent is a long, but the difference between exponents |
| 2925 | # must be an int-- otherwise you'd get a big memory problem. |
| 2926 | numdigits = int(op1.exp - op2.exp) |
| 2927 | if numdigits < 0: |
| 2928 | numdigits = -numdigits |
| 2929 | tmp = op2 |
| 2930 | other = op1 |
| 2931 | else: |
| 2932 | tmp = op1 |
| 2933 | other = op2 |
| 2934 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2935 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2936 | if shouldround and numdigits > prec + 1: |
| 2937 | # Big difference in exponents - check the adjusted exponents |
| 2938 | tmp_len = len(str(tmp.int)) |
| 2939 | other_len = len(str(other.int)) |
| 2940 | if numdigits > (other_len + prec + 1 - tmp_len): |
| 2941 | # If the difference in adjusted exps is > prec+1, we know |
| 2942 | # other is insignificant, so might as well put a 1 after the precision. |
| 2943 | # (since this is only for addition.) Also stops use of massive longs. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2944 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2945 | extend = prec + 2 - tmp_len |
| 2946 | if extend <= 0: |
| 2947 | extend = 1 |
| 2948 | tmp.int *= 10 ** extend |
| 2949 | tmp.exp -= extend |
| 2950 | other.int = 1 |
| 2951 | other.exp = tmp.exp |
| 2952 | return op1, op2 |
| 2953 | |
| 2954 | tmp.int *= 10 ** numdigits |
| 2955 | tmp.exp -= numdigits |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2956 | return op1, op2 |
| 2957 | |
| 2958 | def _adjust_coefficients(op1, op2): |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2959 | """Adjust op1, op2 so that op2.int * 10 > op1.int >= op2.int. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2960 | |
| 2961 | Returns the adjusted op1, op2 as well as the change in op1.exp-op2.exp. |
| 2962 | |
| 2963 | Used on _WorkRep instances during division. |
| 2964 | """ |
| 2965 | adjust = 0 |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2966 | #If op1 is smaller, make it larger |
| 2967 | while op2.int > op1.int: |
| 2968 | op1.int *= 10 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2969 | op1.exp -= 1 |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2970 | adjust += 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2971 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2972 | #If op2 is too small, make it larger |
| 2973 | while op1.int >= (10 * op2.int): |
| 2974 | op2.int *= 10 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2975 | op2.exp -= 1 |
| 2976 | adjust -= 1 |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2977 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2978 | return op1, op2, adjust |
| 2979 | |
| 2980 | ##### Helper Functions ######################################## |
| 2981 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2982 | def _convert_other(other): |
| 2983 | """Convert other to Decimal. |
| 2984 | |
| 2985 | Verifies that it's ok to use in an implicit construction. |
| 2986 | """ |
| 2987 | if isinstance(other, Decimal): |
| 2988 | return other |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame^] | 2989 | if isinstance(other, (int, int)): |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2990 | return Decimal(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 2991 | return NotImplemented |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2992 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2993 | _infinity_map = { |
| 2994 | 'inf' : 1, |
| 2995 | 'infinity' : 1, |
| 2996 | '+inf' : 1, |
| 2997 | '+infinity' : 1, |
| 2998 | '-inf' : -1, |
| 2999 | '-infinity' : -1 |
| 3000 | } |
| 3001 | |
Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 3002 | def _isinfinity(num): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3003 | """Determines whether a string or float is infinity. |
| 3004 | |
Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 3005 | +1 for negative infinity; 0 for finite ; +1 for positive infinity |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3006 | """ |
| 3007 | num = str(num).lower() |
| 3008 | return _infinity_map.get(num, 0) |
| 3009 | |
Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 3010 | def _isnan(num): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3011 | """Determines whether a string or float is NaN |
| 3012 | |
| 3013 | (1, sign, diagnostic info as string) => NaN |
| 3014 | (2, sign, diagnostic info as string) => sNaN |
| 3015 | 0 => not a NaN |
| 3016 | """ |
| 3017 | num = str(num).lower() |
| 3018 | if not num: |
| 3019 | return 0 |
| 3020 | |
| 3021 | #get the sign, get rid of trailing [+-] |
| 3022 | sign = 0 |
| 3023 | if num[0] == '+': |
| 3024 | num = num[1:] |
| 3025 | elif num[0] == '-': #elif avoids '+-nan' |
| 3026 | num = num[1:] |
| 3027 | sign = 1 |
| 3028 | |
| 3029 | if num.startswith('nan'): |
| 3030 | if len(num) > 3 and not num[3:].isdigit(): #diagnostic info |
| 3031 | return 0 |
| 3032 | return (1, sign, num[3:].lstrip('0')) |
| 3033 | if num.startswith('snan'): |
| 3034 | if len(num) > 4 and not num[4:].isdigit(): |
| 3035 | return 0 |
| 3036 | return (2, sign, num[4:].lstrip('0')) |
| 3037 | return 0 |
| 3038 | |
| 3039 | |
| 3040 | ##### Setup Specific Contexts ################################ |
| 3041 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3042 | # The default context prototype used by Context() |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 3043 | # Is mutable, so that new contexts can have different default values |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3044 | |
| 3045 | DefaultContext = Context( |
Raymond Hettinger | 6ea4845 | 2004-07-03 12:26:21 +0000 | [diff] [blame] | 3046 | prec=28, rounding=ROUND_HALF_EVEN, |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3047 | traps=[DivisionByZero, Overflow, InvalidOperation], |
| 3048 | flags=[], |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3049 | _rounding_decision=ALWAYS_ROUND, |
Raymond Hettinger | 99148e7 | 2004-07-14 19:56:56 +0000 | [diff] [blame] | 3050 | Emax=999999999, |
| 3051 | Emin=-999999999, |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 3052 | capitals=1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3053 | ) |
| 3054 | |
| 3055 | # Pre-made alternate contexts offered by the specification |
| 3056 | # Don't change these; the user should be able to select these |
| 3057 | # contexts and be able to reproduce results from other implementations |
| 3058 | # of the spec. |
| 3059 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3060 | BasicContext = Context( |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3061 | prec=9, rounding=ROUND_HALF_UP, |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3062 | traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow], |
| 3063 | flags=[], |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3064 | ) |
| 3065 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3066 | ExtendedContext = Context( |
Raymond Hettinger | 6ea4845 | 2004-07-03 12:26:21 +0000 | [diff] [blame] | 3067 | prec=9, rounding=ROUND_HALF_EVEN, |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3068 | traps=[], |
| 3069 | flags=[], |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3070 | ) |
| 3071 | |
| 3072 | |
Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 3073 | ##### Useful Constants (internal use only) #################### |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3074 | |
| 3075 | #Reusable defaults |
| 3076 | Inf = Decimal('Inf') |
| 3077 | negInf = Decimal('-Inf') |
| 3078 | |
| 3079 | #Infsign[sign] is infinity w/ that sign |
| 3080 | Infsign = (Inf, negInf) |
| 3081 | |
| 3082 | NaN = Decimal('NaN') |
| 3083 | |
| 3084 | |
| 3085 | ##### crud for parsing strings ################################# |
| 3086 | import re |
| 3087 | |
| 3088 | # There's an optional sign at the start, and an optional exponent |
| 3089 | # at the end. The exponent has an optional sign and at least one |
| 3090 | # digit. In between, must have either at least one digit followed |
| 3091 | # by an optional fraction, or a decimal point followed by at least |
| 3092 | # one digit. Yuck. |
| 3093 | |
| 3094 | _parser = re.compile(r""" |
| 3095 | # \s* |
| 3096 | (?P<sign>[-+])? |
| 3097 | ( |
| 3098 | (?P<int>\d+) (\. (?P<frac>\d*))? |
| 3099 | | |
| 3100 | \. (?P<onlyfrac>\d+) |
| 3101 | ) |
| 3102 | ([eE](?P<exp>[-+]? \d+))? |
| 3103 | # \s* |
| 3104 | $ |
| 3105 | """, re.VERBOSE).match #Uncomment the \s* to allow leading or trailing spaces. |
| 3106 | |
| 3107 | del re |
| 3108 | |
| 3109 | # return sign, n, p s.t. float string value == -1**sign * n * 10**p exactly |
| 3110 | |
| 3111 | def _string2exact(s): |
| 3112 | m = _parser(s) |
| 3113 | if m is None: |
| 3114 | raise ValueError("invalid literal for Decimal: %r" % s) |
| 3115 | |
| 3116 | if m.group('sign') == "-": |
| 3117 | sign = 1 |
| 3118 | else: |
| 3119 | sign = 0 |
| 3120 | |
| 3121 | exp = m.group('exp') |
| 3122 | if exp is None: |
| 3123 | exp = 0 |
| 3124 | else: |
| 3125 | exp = int(exp) |
| 3126 | |
| 3127 | intpart = m.group('int') |
| 3128 | if intpart is None: |
| 3129 | intpart = "" |
| 3130 | fracpart = m.group('onlyfrac') |
| 3131 | else: |
| 3132 | fracpart = m.group('frac') |
| 3133 | if fracpart is None: |
| 3134 | fracpart = "" |
| 3135 | |
| 3136 | exp -= len(fracpart) |
| 3137 | |
| 3138 | mantissa = intpart + fracpart |
| 3139 | tmp = map(int, mantissa) |
| 3140 | backup = tmp |
| 3141 | while tmp and tmp[0] == 0: |
| 3142 | del tmp[0] |
| 3143 | |
| 3144 | # It's a zero |
| 3145 | if not tmp: |
| 3146 | if backup: |
| 3147 | return (sign, tuple(backup), exp) |
| 3148 | return (sign, (0,), exp) |
| 3149 | mantissa = tuple(tmp) |
| 3150 | |
| 3151 | return (sign, mantissa, exp) |
| 3152 | |
| 3153 | |
| 3154 | if __name__ == '__main__': |
| 3155 | import doctest, sys |
| 3156 | doctest.testmod(sys.modules[__name__]) |