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