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