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