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