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