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 |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 38 | of the expected Decimal('0.00') returned by decimal floating point). |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 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) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 45 | Decimal('0') |
| 46 | >>> Decimal('1') |
| 47 | Decimal('1') |
| 48 | >>> Decimal('-.0123') |
| 49 | Decimal('-0.0123') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 50 | >>> Decimal(123456) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 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') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 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)) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 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 | a016deb | 2009-04-27 21:12:27 +0000 | [diff] [blame] | 137 | __version__ = '1.70' # Highest version of the spec this complies with |
Raymond Hettinger | daeceb2 | 2009-03-10 04:49:21 +0000 | [diff] [blame] | 138 | |
Raymond Hettinger | eb26084 | 2005-06-07 18:52:34 +0000 | [diff] [blame] | 139 | import copy as _copy |
Raymond Hettinger | f4d8597 | 2009-01-03 19:02:23 +0000 | [diff] [blame] | 140 | import math as _math |
Raymond Hettinger | 2c8585b | 2009-02-03 03:37:03 +0000 | [diff] [blame] | 141 | import numbers as _numbers |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 142 | |
Raymond Hettinger | 097a190 | 2008-01-11 02:24:13 +0000 | [diff] [blame] | 143 | try: |
| 144 | from collections import namedtuple as _namedtuple |
| 145 | DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent') |
| 146 | except ImportError: |
| 147 | DecimalTuple = lambda *args: args |
| 148 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 149 | # Rounding |
Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 150 | ROUND_DOWN = 'ROUND_DOWN' |
| 151 | ROUND_HALF_UP = 'ROUND_HALF_UP' |
| 152 | ROUND_HALF_EVEN = 'ROUND_HALF_EVEN' |
| 153 | ROUND_CEILING = 'ROUND_CEILING' |
| 154 | ROUND_FLOOR = 'ROUND_FLOOR' |
| 155 | ROUND_UP = 'ROUND_UP' |
| 156 | ROUND_HALF_DOWN = 'ROUND_HALF_DOWN' |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 157 | ROUND_05UP = 'ROUND_05UP' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 158 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 159 | # Errors |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 160 | |
| 161 | class DecimalException(ArithmeticError): |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 162 | """Base exception class. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 163 | |
| 164 | Used exceptions derive from this. |
| 165 | If an exception derives from another exception besides this (such as |
| 166 | Underflow (Inexact, Rounded, Subnormal) that indicates that it is only |
| 167 | called if the others are present. This isn't actually used for |
| 168 | anything, though. |
| 169 | |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 170 | handle -- Called when context._raise_error is called and the |
| 171 | trap_enabler is set. First argument is self, second is the |
| 172 | context. More arguments can be given, those being after |
| 173 | the explanation in _raise_error (For example, |
| 174 | context._raise_error(NewError, '(-x)!', self._sign) would |
| 175 | call NewError().handle(context, self._sign).) |
| 176 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 177 | To define a new exception, it should be sufficient to have it derive |
| 178 | from DecimalException. |
| 179 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 180 | def handle(self, context, *args): |
| 181 | pass |
| 182 | |
| 183 | |
| 184 | class Clamped(DecimalException): |
| 185 | """Exponent of a 0 changed to fit bounds. |
| 186 | |
| 187 | This occurs and signals clamped if the exponent of a result has been |
| 188 | altered in order to fit the constraints of a specific concrete |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 189 | representation. This may occur when the exponent of a zero result would |
| 190 | be outside the bounds of a representation, or when a large normal |
| 191 | number would have an encoded exponent that cannot be represented. In |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 192 | this latter case, the exponent is reduced to fit and the corresponding |
| 193 | number of zero digits are appended to the coefficient ("fold-down"). |
| 194 | """ |
| 195 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 196 | class InvalidOperation(DecimalException): |
| 197 | """An invalid operation was performed. |
| 198 | |
| 199 | Various bad things cause this: |
| 200 | |
| 201 | Something creates a signaling NaN |
| 202 | -INF + INF |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 203 | 0 * (+-)INF |
| 204 | (+-)INF / (+-)INF |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 205 | x % 0 |
| 206 | (+-)INF % x |
| 207 | x._rescale( non-integer ) |
| 208 | sqrt(-x) , x > 0 |
| 209 | 0 ** 0 |
| 210 | x ** (non-integer) |
| 211 | x ** (+-)INF |
| 212 | An operand is invalid |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 213 | |
| 214 | The result of the operation after these is a quiet positive NaN, |
| 215 | except when the cause is a signaling NaN, in which case the result is |
| 216 | also a quiet NaN, but with the original sign, and an optional |
| 217 | diagnostic information. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 218 | """ |
| 219 | def handle(self, context, *args): |
| 220 | if args: |
Facundo Batista | 0f5e7bf | 2007-12-19 12:53:01 +0000 | [diff] [blame] | 221 | ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True) |
| 222 | return ans._fix_nan(context) |
Mark Dickinson | c5de096 | 2009-01-02 23:07:08 +0000 | [diff] [blame] | 223 | return _NaN |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 224 | |
| 225 | class ConversionSyntax(InvalidOperation): |
| 226 | """Trying to convert badly formed string. |
| 227 | |
| 228 | This occurs and signals invalid-operation if an string is being |
| 229 | 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] | 230 | syntax. The result is [0,qNaN]. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 231 | """ |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 232 | def handle(self, context, *args): |
Mark Dickinson | c5de096 | 2009-01-02 23:07:08 +0000 | [diff] [blame] | 233 | return _NaN |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 234 | |
| 235 | class DivisionByZero(DecimalException, ZeroDivisionError): |
| 236 | """Division by 0. |
| 237 | |
| 238 | This occurs and signals division-by-zero if division of a finite number |
| 239 | by zero was attempted (during a divide-integer or divide operation, or a |
| 240 | power operation with negative right-hand operand), and the dividend was |
| 241 | not zero. |
| 242 | |
| 243 | The result of the operation is [sign,inf], where sign is the exclusive |
| 244 | or of the signs of the operands for divide, or is 1 for an odd power of |
| 245 | -0, for power. |
| 246 | """ |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 247 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 248 | def handle(self, context, sign, *args): |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 249 | return _SignedInfinity[sign] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 250 | |
| 251 | class DivisionImpossible(InvalidOperation): |
| 252 | """Cannot perform the division adequately. |
| 253 | |
| 254 | This occurs and signals invalid-operation if the integer result of a |
| 255 | divide-integer or remainder operation had too many digits (would be |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 256 | longer than precision). The result is [0,qNaN]. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 257 | """ |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 258 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 259 | def handle(self, context, *args): |
Mark Dickinson | c5de096 | 2009-01-02 23:07:08 +0000 | [diff] [blame] | 260 | return _NaN |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 261 | |
| 262 | class DivisionUndefined(InvalidOperation, ZeroDivisionError): |
| 263 | """Undefined result of division. |
| 264 | |
| 265 | This occurs and signals invalid-operation if division by zero was |
| 266 | attempted (during a divide-integer, divide, or remainder operation), and |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 267 | the dividend is also zero. The result is [0,qNaN]. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 268 | """ |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 269 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 270 | def handle(self, context, *args): |
Mark Dickinson | c5de096 | 2009-01-02 23:07:08 +0000 | [diff] [blame] | 271 | return _NaN |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 272 | |
| 273 | class Inexact(DecimalException): |
| 274 | """Had to round, losing information. |
| 275 | |
| 276 | This occurs and signals inexact whenever the result of an operation is |
| 277 | 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] | 278 | were non-zero), or if an overflow or underflow condition occurs. The |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 279 | result in all cases is unchanged. |
| 280 | |
| 281 | The inexact signal may be tested (or trapped) to determine if a given |
| 282 | operation (or sequence of operations) was inexact. |
| 283 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 284 | |
| 285 | class InvalidContext(InvalidOperation): |
| 286 | """Invalid context. Unknown rounding, for example. |
| 287 | |
| 288 | This occurs and signals invalid-operation if an invalid context was |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 289 | detected during an operation. This can occur if contexts are not checked |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 290 | on creation and either the precision exceeds the capability of the |
| 291 | underlying concrete representation or an unknown or unsupported rounding |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 292 | was specified. These aspects of the context need only be checked when |
| 293 | the values are required to be used. The result is [0,qNaN]. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 294 | """ |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 295 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 296 | def handle(self, context, *args): |
Mark Dickinson | c5de096 | 2009-01-02 23:07:08 +0000 | [diff] [blame] | 297 | return _NaN |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 298 | |
| 299 | class Rounded(DecimalException): |
| 300 | """Number got rounded (not necessarily changed during rounding). |
| 301 | |
| 302 | This occurs and signals rounded whenever the result of an operation is |
| 303 | rounded (that is, some zero or non-zero digits were discarded from the |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 304 | coefficient), or if an overflow or underflow condition occurs. The |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 305 | result in all cases is unchanged. |
| 306 | |
| 307 | The rounded signal may be tested (or trapped) to determine if a given |
| 308 | operation (or sequence of operations) caused a loss of precision. |
| 309 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 310 | |
| 311 | class Subnormal(DecimalException): |
| 312 | """Exponent < Emin before rounding. |
| 313 | |
| 314 | This occurs and signals subnormal whenever the result of a conversion or |
| 315 | operation is subnormal (that is, its adjusted exponent is less than |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 316 | Emin, before any rounding). The result in all cases is unchanged. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 317 | |
| 318 | The subnormal signal may be tested (or trapped) to determine if a given |
| 319 | or operation (or sequence of operations) yielded a subnormal result. |
| 320 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 321 | |
| 322 | class Overflow(Inexact, Rounded): |
| 323 | """Numerical overflow. |
| 324 | |
| 325 | This occurs and signals overflow if the adjusted exponent of a result |
| 326 | (from a conversion or from an operation that is not an attempt to divide |
| 327 | by zero), after rounding, would be greater than the largest value that |
| 328 | can be handled by the implementation (the value Emax). |
| 329 | |
| 330 | The result depends on the rounding mode: |
| 331 | |
| 332 | For round-half-up and round-half-even (and for round-half-down and |
| 333 | round-up, if implemented), the result of the operation is [sign,inf], |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 334 | 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] | 335 | result is the largest finite number that can be represented in the |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 336 | current precision, with the sign of the intermediate result. For |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 337 | 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] | 338 | 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] | 339 | 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] | 340 | 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] | 341 | will also be raised. |
Facundo Batista | 0f5e7bf | 2007-12-19 12:53:01 +0000 | [diff] [blame] | 342 | """ |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 343 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 344 | def handle(self, context, sign, *args): |
| 345 | if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN, |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 346 | ROUND_HALF_DOWN, ROUND_UP): |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 347 | return _SignedInfinity[sign] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 348 | if sign == 0: |
| 349 | if context.rounding == ROUND_CEILING: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 350 | return _SignedInfinity[sign] |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 351 | return _dec_from_triple(sign, '9'*context.prec, |
| 352 | context.Emax-context.prec+1) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 353 | if sign == 1: |
| 354 | if context.rounding == ROUND_FLOOR: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 355 | return _SignedInfinity[sign] |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 356 | return _dec_from_triple(sign, '9'*context.prec, |
| 357 | context.Emax-context.prec+1) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 358 | |
| 359 | |
| 360 | class Underflow(Inexact, Rounded, Subnormal): |
| 361 | """Numerical underflow with result rounded to 0. |
| 362 | |
| 363 | This occurs and signals underflow if a result is inexact and the |
| 364 | adjusted exponent of the result would be smaller (more negative) than |
| 365 | the smallest value that can be handled by the implementation (the value |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 366 | Emin). That is, the result is both inexact and subnormal. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 367 | |
| 368 | The result after an underflow will be a subnormal number rounded, if |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 369 | 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] | 370 | in 0 with the sign of the intermediate result and an exponent of Etiny. |
| 371 | |
| 372 | In all cases, Inexact, Rounded, and Subnormal will also be raised. |
| 373 | """ |
| 374 | |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 375 | # List of public traps and flags |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 376 | _signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded, |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 377 | Underflow, InvalidOperation, Subnormal] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 378 | |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 379 | # Map conditions (per the spec) to signals |
| 380 | _condition_map = {ConversionSyntax:InvalidOperation, |
| 381 | DivisionImpossible:InvalidOperation, |
| 382 | DivisionUndefined:InvalidOperation, |
| 383 | InvalidContext:InvalidOperation} |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 384 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 385 | ##### Context Functions ################################################## |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 386 | |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 387 | # The getcontext() and setcontext() function manage access to a thread-local |
| 388 | # current context. Py2.4 offers direct support for thread locals. If that |
| 389 | # is not available, use threading.currentThread() which is slower but will |
Raymond Hettinger | 7e71fa5 | 2004-12-18 19:07:19 +0000 | [diff] [blame] | 390 | # 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] | 391 | # mock threading object with threading.local() returning the module namespace. |
Raymond Hettinger | 7e71fa5 | 2004-12-18 19:07:19 +0000 | [diff] [blame] | 392 | |
| 393 | try: |
| 394 | import threading |
| 395 | except ImportError: |
| 396 | # Python was compiled without threads; create a mock object instead |
| 397 | import sys |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 398 | class MockThreading(object): |
Raymond Hettinger | 7e71fa5 | 2004-12-18 19:07:19 +0000 | [diff] [blame] | 399 | def local(self, sys=sys): |
| 400 | return sys.modules[__name__] |
| 401 | threading = MockThreading() |
| 402 | del sys, MockThreading |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 403 | |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 404 | try: |
| 405 | threading.local |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 406 | |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 407 | except AttributeError: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 408 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 409 | # To fix reloading, force it to create a new context |
| 410 | # Old contexts have different exceptions in their dicts, making problems. |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 411 | if hasattr(threading.currentThread(), '__decimal_context__'): |
| 412 | del threading.currentThread().__decimal_context__ |
| 413 | |
| 414 | def setcontext(context): |
| 415 | """Set this thread's context to context.""" |
| 416 | if context in (DefaultContext, BasicContext, ExtendedContext): |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 417 | context = context.copy() |
Raymond Hettinger | 61992ef | 2004-08-06 23:42:16 +0000 | [diff] [blame] | 418 | context.clear_flags() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 419 | threading.currentThread().__decimal_context__ = context |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 420 | |
| 421 | def getcontext(): |
| 422 | """Returns this thread's context. |
| 423 | |
| 424 | If this thread does not yet have a context, returns |
| 425 | a new context and sets this thread's context. |
| 426 | New contexts are copies of DefaultContext. |
| 427 | """ |
| 428 | try: |
| 429 | return threading.currentThread().__decimal_context__ |
| 430 | except AttributeError: |
| 431 | context = Context() |
| 432 | threading.currentThread().__decimal_context__ = context |
| 433 | return context |
| 434 | |
| 435 | else: |
| 436 | |
| 437 | local = threading.local() |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 438 | if hasattr(local, '__decimal_context__'): |
| 439 | del local.__decimal_context__ |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 440 | |
| 441 | def getcontext(_local=local): |
| 442 | """Returns this thread's context. |
| 443 | |
| 444 | If this thread does not yet have a context, returns |
| 445 | a new context and sets this thread's context. |
| 446 | New contexts are copies of DefaultContext. |
| 447 | """ |
| 448 | try: |
| 449 | return _local.__decimal_context__ |
| 450 | except AttributeError: |
| 451 | context = Context() |
| 452 | _local.__decimal_context__ = context |
| 453 | return context |
| 454 | |
| 455 | def setcontext(context, _local=local): |
| 456 | """Set this thread's context to context.""" |
| 457 | if context in (DefaultContext, BasicContext, ExtendedContext): |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 458 | context = context.copy() |
Raymond Hettinger | 61992ef | 2004-08-06 23:42:16 +0000 | [diff] [blame] | 459 | context.clear_flags() |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 460 | _local.__decimal_context__ = context |
| 461 | |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 462 | del threading, local # Don't contaminate the namespace |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 463 | |
Nick Coghlan | 8b6999b | 2006-08-31 12:00:43 +0000 | [diff] [blame] | 464 | def localcontext(ctx=None): |
| 465 | """Return a context manager for a copy of the supplied context |
| 466 | |
| 467 | Uses a copy of the current context if no context is specified |
| 468 | The returned context manager creates a local decimal context |
| 469 | in a with statement: |
| 470 | def sin(x): |
| 471 | with localcontext() as ctx: |
| 472 | ctx.prec += 2 |
| 473 | # Rest of sin calculation algorithm |
| 474 | # uses a precision 2 greater than normal |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 475 | return +s # Convert result to normal precision |
Nick Coghlan | 8b6999b | 2006-08-31 12:00:43 +0000 | [diff] [blame] | 476 | |
| 477 | def sin(x): |
| 478 | with localcontext(ExtendedContext): |
| 479 | # Rest of sin calculation algorithm |
| 480 | # uses the Extended Context from the |
| 481 | # General Decimal Arithmetic Specification |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 482 | return +s # Convert result to normal context |
Nick Coghlan | 8b6999b | 2006-08-31 12:00:43 +0000 | [diff] [blame] | 483 | |
Facundo Batista | ee340e5 | 2008-05-02 17:39:00 +0000 | [diff] [blame] | 484 | >>> setcontext(DefaultContext) |
Nick Coghlan | 8b6999b | 2006-08-31 12:00:43 +0000 | [diff] [blame] | 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 |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 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 | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 521 | Decimal('3.14') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 522 | >>> Decimal(314) # int or long |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 523 | Decimal('314') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 524 | >>> Decimal(Decimal(314)) # another decimal instance |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 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 |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 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 |
Mark Dickinson | 4326ad8 | 2009-08-02 10:59:36 +0000 | [diff] [blame] | 557 | fracpart = m.group('frac') or '' |
Facundo Batista | 0d157a0 | 2007-11-30 17:15:25 +0000 | [diff] [blame] | 558 | exp = int(m.group('exp') or '0') |
Mark Dickinson | 4326ad8 | 2009-08-02 10:59:36 +0000 | [diff] [blame] | 559 | self._int = str(int(intpart+fracpart)) |
| 560 | self._exp = exp - len(fracpart) |
Facundo Batista | 0d157a0 | 2007-11-30 17:15:25 +0000 | [diff] [blame] | 561 | self._is_special = False |
| 562 | else: |
| 563 | diag = m.group('diag') |
| 564 | if diag is not None: |
| 565 | # NaN |
Mark Dickinson | 4326ad8 | 2009-08-02 10:59:36 +0000 | [diff] [blame] | 566 | self._int = str(int(diag or '0')).lstrip('0') |
Facundo Batista | 0d157a0 | 2007-11-30 17:15:25 +0000 | [diff] [blame] | 567 | if m.group('signal'): |
| 568 | self._exp = 'N' |
| 569 | else: |
| 570 | self._exp = 'n' |
| 571 | else: |
| 572 | # infinity |
| 573 | self._int = '0' |
| 574 | self._exp = 'F' |
| 575 | self._is_special = True |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 576 | return self |
| 577 | |
| 578 | # From an integer |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 579 | if isinstance(value, (int,long)): |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 580 | if value >= 0: |
| 581 | self._sign = 0 |
| 582 | else: |
| 583 | self._sign = 1 |
| 584 | self._exp = 0 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 585 | self._int = str(abs(value)) |
Facundo Batista | 0d157a0 | 2007-11-30 17:15:25 +0000 | [diff] [blame] | 586 | self._is_special = False |
| 587 | return self |
| 588 | |
| 589 | # From another decimal |
| 590 | if isinstance(value, Decimal): |
| 591 | self._exp = value._exp |
| 592 | self._sign = value._sign |
| 593 | self._int = value._int |
| 594 | self._is_special = value._is_special |
| 595 | return self |
| 596 | |
| 597 | # From an internal working value |
| 598 | if isinstance(value, _WorkRep): |
| 599 | self._sign = value.sign |
| 600 | self._int = str(value.int) |
| 601 | self._exp = int(value.exp) |
| 602 | self._is_special = False |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 603 | return self |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 604 | |
| 605 | # tuple/list conversion (possibly from as_tuple()) |
| 606 | if isinstance(value, (list,tuple)): |
| 607 | if len(value) != 3: |
Facundo Batista | 9b5e231 | 2007-10-19 19:25:57 +0000 | [diff] [blame] | 608 | raise ValueError('Invalid tuple size in creation of Decimal ' |
| 609 | 'from list or tuple. The list or tuple ' |
| 610 | 'should have exactly three elements.') |
| 611 | # process sign. The isinstance test rejects floats |
| 612 | if not (isinstance(value[0], (int, long)) and value[0] in (0,1)): |
| 613 | raise ValueError("Invalid sign. The first value in the tuple " |
| 614 | "should be an integer; either 0 for a " |
| 615 | "positive number or 1 for a negative number.") |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 616 | self._sign = value[0] |
Facundo Batista | 9b5e231 | 2007-10-19 19:25:57 +0000 | [diff] [blame] | 617 | if value[2] == 'F': |
| 618 | # infinity: value[1] is ignored |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 619 | self._int = '0' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 620 | self._exp = value[2] |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 621 | self._is_special = True |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 622 | else: |
Facundo Batista | 9b5e231 | 2007-10-19 19:25:57 +0000 | [diff] [blame] | 623 | # process and validate the digits in value[1] |
| 624 | digits = [] |
| 625 | for digit in value[1]: |
| 626 | if isinstance(digit, (int, long)) and 0 <= digit <= 9: |
| 627 | # skip leading zeros |
| 628 | if digits or digit != 0: |
| 629 | digits.append(digit) |
| 630 | else: |
| 631 | raise ValueError("The second value in the tuple must " |
| 632 | "be composed of integers in the range " |
| 633 | "0 through 9.") |
| 634 | if value[2] in ('n', 'N'): |
| 635 | # NaN: digits form the diagnostic |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 636 | self._int = ''.join(map(str, digits)) |
Facundo Batista | 9b5e231 | 2007-10-19 19:25:57 +0000 | [diff] [blame] | 637 | self._exp = value[2] |
| 638 | self._is_special = True |
| 639 | elif isinstance(value[2], (int, long)): |
| 640 | # finite number: digits give the coefficient |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 641 | self._int = ''.join(map(str, digits or [0])) |
Facundo Batista | 9b5e231 | 2007-10-19 19:25:57 +0000 | [diff] [blame] | 642 | self._exp = value[2] |
| 643 | self._is_special = False |
| 644 | else: |
| 645 | raise ValueError("The third value in the tuple must " |
| 646 | "be an integer, or one of the " |
| 647 | "strings 'F', 'n', 'N'.") |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 648 | return self |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 649 | |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 650 | if isinstance(value, float): |
Benjamin Peterson | a617e20 | 2010-01-25 03:52:52 +0000 | [diff] [blame] | 651 | raise TypeError("Cannot convert float in Decimal constructor. " |
| 652 | "Use from_float class method.") |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 653 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 654 | raise TypeError("Cannot convert %r to Decimal" % value) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 655 | |
Mark Dickinson | 6a96163 | 2009-01-04 21:10:56 +0000 | [diff] [blame] | 656 | # @classmethod, but @decorator is not valid Python 2.3 syntax, so |
| 657 | # don't use it (see notes on Py2.3 compatibility at top of file) |
Raymond Hettinger | f4d8597 | 2009-01-03 19:02:23 +0000 | [diff] [blame] | 658 | def from_float(cls, f): |
| 659 | """Converts a float to a decimal number, exactly. |
| 660 | |
| 661 | Note that Decimal.from_float(0.1) is not the same as Decimal('0.1'). |
| 662 | Since 0.1 is not exactly representable in binary floating point, the |
| 663 | value is stored as the nearest representable value which is |
| 664 | 0x1.999999999999ap-4. The exact equivalent of the value in decimal |
| 665 | is 0.1000000000000000055511151231257827021181583404541015625. |
| 666 | |
| 667 | >>> Decimal.from_float(0.1) |
| 668 | Decimal('0.1000000000000000055511151231257827021181583404541015625') |
| 669 | >>> Decimal.from_float(float('nan')) |
| 670 | Decimal('NaN') |
| 671 | >>> Decimal.from_float(float('inf')) |
| 672 | Decimal('Infinity') |
| 673 | >>> Decimal.from_float(-float('inf')) |
| 674 | Decimal('-Infinity') |
| 675 | >>> Decimal.from_float(-0.0) |
| 676 | Decimal('-0') |
| 677 | |
| 678 | """ |
| 679 | if isinstance(f, (int, long)): # handle integer inputs |
| 680 | return cls(f) |
| 681 | if _math.isinf(f) or _math.isnan(f): # raises TypeError if not a float |
| 682 | return cls(repr(f)) |
Mark Dickinson | 6a96163 | 2009-01-04 21:10:56 +0000 | [diff] [blame] | 683 | if _math.copysign(1.0, f) == 1.0: |
| 684 | sign = 0 |
| 685 | else: |
| 686 | sign = 1 |
Raymond Hettinger | f4d8597 | 2009-01-03 19:02:23 +0000 | [diff] [blame] | 687 | n, d = abs(f).as_integer_ratio() |
| 688 | k = d.bit_length() - 1 |
| 689 | result = _dec_from_triple(sign, str(n*5**k), -k) |
Mark Dickinson | 6a96163 | 2009-01-04 21:10:56 +0000 | [diff] [blame] | 690 | if cls is Decimal: |
| 691 | return result |
| 692 | else: |
| 693 | return cls(result) |
| 694 | from_float = classmethod(from_float) |
Raymond Hettinger | f4d8597 | 2009-01-03 19:02:23 +0000 | [diff] [blame] | 695 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 696 | def _isnan(self): |
| 697 | """Returns whether the number is not actually one. |
| 698 | |
| 699 | 0 if a number |
Facundo Batista | 0f5e7bf | 2007-12-19 12:53:01 +0000 | [diff] [blame] | 700 | 1 if NaN |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 701 | 2 if sNaN |
| 702 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 703 | if self._is_special: |
| 704 | exp = self._exp |
| 705 | if exp == 'n': |
| 706 | return 1 |
| 707 | elif exp == 'N': |
| 708 | return 2 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 709 | return 0 |
| 710 | |
| 711 | def _isinfinity(self): |
| 712 | """Returns whether the number is infinite |
| 713 | |
| 714 | 0 if finite or not a number |
| 715 | 1 if +INF |
| 716 | -1 if -INF |
| 717 | """ |
| 718 | if self._exp == 'F': |
| 719 | if self._sign: |
| 720 | return -1 |
| 721 | return 1 |
| 722 | return 0 |
| 723 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 724 | def _check_nans(self, other=None, context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 725 | """Returns whether the number is not actually one. |
| 726 | |
| 727 | if self, other are sNaN, signal |
| 728 | if self, other are NaN return nan |
| 729 | return 0 |
| 730 | |
| 731 | Done before operations. |
| 732 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 733 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 734 | self_is_nan = self._isnan() |
| 735 | if other is None: |
| 736 | other_is_nan = False |
| 737 | else: |
| 738 | other_is_nan = other._isnan() |
| 739 | |
| 740 | if self_is_nan or other_is_nan: |
| 741 | if context is None: |
| 742 | context = getcontext() |
| 743 | |
| 744 | if self_is_nan == 2: |
| 745 | return context._raise_error(InvalidOperation, 'sNaN', |
Facundo Batista | 0f5e7bf | 2007-12-19 12:53:01 +0000 | [diff] [blame] | 746 | self) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 747 | if other_is_nan == 2: |
| 748 | return context._raise_error(InvalidOperation, 'sNaN', |
Facundo Batista | 0f5e7bf | 2007-12-19 12:53:01 +0000 | [diff] [blame] | 749 | other) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 750 | if self_is_nan: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 751 | return self._fix_nan(context) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 752 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 753 | return other._fix_nan(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 754 | return 0 |
| 755 | |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 756 | def _compare_check_nans(self, other, context): |
| 757 | """Version of _check_nans used for the signaling comparisons |
| 758 | compare_signal, __le__, __lt__, __ge__, __gt__. |
| 759 | |
| 760 | Signal InvalidOperation if either self or other is a (quiet |
| 761 | or signaling) NaN. Signaling NaNs take precedence over quiet |
| 762 | NaNs. |
| 763 | |
| 764 | Return 0 if neither operand is a NaN. |
| 765 | |
| 766 | """ |
| 767 | if context is None: |
| 768 | context = getcontext() |
| 769 | |
| 770 | if self._is_special or other._is_special: |
| 771 | if self.is_snan(): |
| 772 | return context._raise_error(InvalidOperation, |
| 773 | 'comparison involving sNaN', |
| 774 | self) |
| 775 | elif other.is_snan(): |
| 776 | return context._raise_error(InvalidOperation, |
| 777 | 'comparison involving sNaN', |
| 778 | other) |
| 779 | elif self.is_qnan(): |
| 780 | return context._raise_error(InvalidOperation, |
| 781 | 'comparison involving NaN', |
| 782 | self) |
| 783 | elif other.is_qnan(): |
| 784 | return context._raise_error(InvalidOperation, |
| 785 | 'comparison involving NaN', |
| 786 | other) |
| 787 | return 0 |
| 788 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 789 | def __nonzero__(self): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 790 | """Return True if self is nonzero; otherwise return False. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 791 | |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 792 | NaNs and infinities are considered nonzero. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 793 | """ |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 794 | return self._is_special or self._int != '0' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 795 | |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 796 | def _cmp(self, other): |
| 797 | """Compare the two non-NaN decimal instances self and other. |
| 798 | |
| 799 | Returns -1 if self < other, 0 if self == other and 1 |
| 800 | if self > other. This routine is for internal use only.""" |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 801 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 802 | if self._is_special or other._is_special: |
Mark Dickinson | e52c314 | 2009-01-25 10:39:15 +0000 | [diff] [blame] | 803 | self_inf = self._isinfinity() |
| 804 | other_inf = other._isinfinity() |
| 805 | if self_inf == other_inf: |
| 806 | return 0 |
| 807 | elif self_inf < other_inf: |
| 808 | return -1 |
| 809 | else: |
| 810 | return 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 811 | |
Mark Dickinson | e52c314 | 2009-01-25 10:39:15 +0000 | [diff] [blame] | 812 | # check for zeros; Decimal('0') == Decimal('-0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 813 | if not self: |
| 814 | if not other: |
| 815 | return 0 |
| 816 | else: |
| 817 | return -((-1)**other._sign) |
| 818 | if not other: |
| 819 | return (-1)**self._sign |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 820 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 821 | # If different signs, neg one is less |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 822 | if other._sign < self._sign: |
| 823 | return -1 |
| 824 | if self._sign < other._sign: |
| 825 | return 1 |
| 826 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 827 | self_adjusted = self.adjusted() |
| 828 | other_adjusted = other.adjusted() |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 829 | if self_adjusted == other_adjusted: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 830 | self_padded = self._int + '0'*(self._exp - other._exp) |
| 831 | other_padded = other._int + '0'*(other._exp - self._exp) |
Mark Dickinson | e52c314 | 2009-01-25 10:39:15 +0000 | [diff] [blame] | 832 | if self_padded == other_padded: |
| 833 | return 0 |
| 834 | elif self_padded < other_padded: |
| 835 | return -(-1)**self._sign |
| 836 | else: |
| 837 | return (-1)**self._sign |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 838 | elif self_adjusted > other_adjusted: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 839 | return (-1)**self._sign |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 840 | else: # self_adjusted < other_adjusted |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 841 | return -((-1)**self._sign) |
| 842 | |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 843 | # Note: The Decimal standard doesn't cover rich comparisons for |
| 844 | # Decimals. In particular, the specification is silent on the |
| 845 | # subject of what should happen for a comparison involving a NaN. |
| 846 | # We take the following approach: |
| 847 | # |
Mark Dickinson | e096e82 | 2010-04-02 10:17:07 +0000 | [diff] [blame] | 848 | # == comparisons involving a quiet NaN always return False |
| 849 | # != comparisons involving a quiet NaN always return True |
| 850 | # == or != comparisons involving a signaling NaN signal |
| 851 | # InvalidOperation, and return False or True as above if the |
| 852 | # InvalidOperation is not trapped. |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 853 | # <, >, <= and >= comparisons involving a (quiet or signaling) |
| 854 | # NaN signal InvalidOperation, and return False if the |
Mark Dickinson | 3a94ee0 | 2008-02-10 15:19:58 +0000 | [diff] [blame] | 855 | # InvalidOperation is not trapped. |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 856 | # |
| 857 | # This behavior is designed to conform as closely as possible to |
| 858 | # that specified by IEEE 754. |
| 859 | |
Mark Dickinson | e096e82 | 2010-04-02 10:17:07 +0000 | [diff] [blame] | 860 | def __eq__(self, other, context=None): |
Mark Dickinson | 99d8096 | 2010-04-02 08:53:22 +0000 | [diff] [blame] | 861 | other = _convert_other(other, allow_float=True) |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 862 | if other is NotImplemented: |
| 863 | return other |
Mark Dickinson | e096e82 | 2010-04-02 10:17:07 +0000 | [diff] [blame] | 864 | if self._check_nans(other, context): |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 865 | return False |
| 866 | return self._cmp(other) == 0 |
Raymond Hettinger | 0aeac10 | 2004-07-05 22:53:03 +0000 | [diff] [blame] | 867 | |
Mark Dickinson | e096e82 | 2010-04-02 10:17:07 +0000 | [diff] [blame] | 868 | def __ne__(self, other, context=None): |
Mark Dickinson | 99d8096 | 2010-04-02 08:53:22 +0000 | [diff] [blame] | 869 | other = _convert_other(other, allow_float=True) |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 870 | if other is NotImplemented: |
| 871 | return other |
Mark Dickinson | e096e82 | 2010-04-02 10:17:07 +0000 | [diff] [blame] | 872 | if self._check_nans(other, context): |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 873 | return True |
| 874 | return self._cmp(other) != 0 |
| 875 | |
| 876 | def __lt__(self, other, context=None): |
Mark Dickinson | 99d8096 | 2010-04-02 08:53:22 +0000 | [diff] [blame] | 877 | other = _convert_other(other, allow_float=True) |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 878 | if other is NotImplemented: |
| 879 | return other |
| 880 | ans = self._compare_check_nans(other, context) |
| 881 | if ans: |
| 882 | return False |
| 883 | return self._cmp(other) < 0 |
| 884 | |
| 885 | def __le__(self, other, context=None): |
Mark Dickinson | 99d8096 | 2010-04-02 08:53:22 +0000 | [diff] [blame] | 886 | other = _convert_other(other, allow_float=True) |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 887 | if other is NotImplemented: |
| 888 | return other |
| 889 | ans = self._compare_check_nans(other, context) |
| 890 | if ans: |
| 891 | return False |
| 892 | return self._cmp(other) <= 0 |
| 893 | |
| 894 | def __gt__(self, other, context=None): |
Mark Dickinson | 99d8096 | 2010-04-02 08:53:22 +0000 | [diff] [blame] | 895 | other = _convert_other(other, allow_float=True) |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 896 | if other is NotImplemented: |
| 897 | return other |
| 898 | ans = self._compare_check_nans(other, context) |
| 899 | if ans: |
| 900 | return False |
| 901 | return self._cmp(other) > 0 |
| 902 | |
| 903 | def __ge__(self, other, context=None): |
Mark Dickinson | 99d8096 | 2010-04-02 08:53:22 +0000 | [diff] [blame] | 904 | other = _convert_other(other, allow_float=True) |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 905 | if other is NotImplemented: |
| 906 | return other |
| 907 | ans = self._compare_check_nans(other, context) |
| 908 | if ans: |
| 909 | return False |
| 910 | return self._cmp(other) >= 0 |
Raymond Hettinger | 0aeac10 | 2004-07-05 22:53:03 +0000 | [diff] [blame] | 911 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 912 | def compare(self, other, context=None): |
| 913 | """Compares one to another. |
| 914 | |
| 915 | -1 => a < b |
| 916 | 0 => a = b |
| 917 | 1 => a > b |
| 918 | NaN => one is NaN |
| 919 | Like __cmp__, but returns Decimal instances. |
| 920 | """ |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 921 | other = _convert_other(other, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 922 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 923 | # Compare(NaN, NaN) = NaN |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 924 | if (self._is_special or other and other._is_special): |
| 925 | ans = self._check_nans(other, context) |
| 926 | if ans: |
| 927 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 928 | |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 929 | return Decimal(self._cmp(other)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 930 | |
| 931 | def __hash__(self): |
| 932 | """x.__hash__() <==> hash(x)""" |
| 933 | # Decimal integers must hash the same as the ints |
Facundo Batista | 52b2579 | 2008-01-08 12:25:20 +0000 | [diff] [blame] | 934 | # |
| 935 | # The hash of a nonspecial noninteger Decimal must depend only |
| 936 | # on the value of that Decimal, and not on its representation. |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 937 | # For example: hash(Decimal('100E-1')) == hash(Decimal('10')). |
Mark Dickinson | f3eeca1 | 2010-04-02 10:35:12 +0000 | [diff] [blame] | 938 | |
| 939 | # Equality comparisons involving signaling nans can raise an |
| 940 | # exception; since equality checks are implicitly and |
| 941 | # unpredictably used when checking set and dict membership, we |
| 942 | # prevent signaling nans from being used as set elements or |
| 943 | # dict keys by making __hash__ raise an exception. |
| 944 | if self._is_special: |
| 945 | if self.is_snan(): |
| 946 | raise TypeError('Cannot hash a signaling NaN value.') |
| 947 | elif self.is_nan(): |
| 948 | # 0 to match hash(float('nan')) |
| 949 | return 0 |
| 950 | else: |
| 951 | # values chosen to match hash(float('inf')) and |
| 952 | # hash(float('-inf')). |
| 953 | if self._sign: |
| 954 | return -271828 |
| 955 | else: |
| 956 | return 314159 |
Mark Dickinson | 99d8096 | 2010-04-02 08:53:22 +0000 | [diff] [blame] | 957 | |
| 958 | # In Python 2.7, we're allowing comparisons (but not |
| 959 | # arithmetic operations) between floats and Decimals; so if |
| 960 | # a Decimal instance is exactly representable as a float then |
Mark Dickinson | f3eeca1 | 2010-04-02 10:35:12 +0000 | [diff] [blame] | 961 | # its hash should match that of the float. |
Mark Dickinson | 99d8096 | 2010-04-02 08:53:22 +0000 | [diff] [blame] | 962 | self_as_float = float(self) |
| 963 | if Decimal.from_float(self_as_float) == self: |
| 964 | return hash(self_as_float) |
| 965 | |
Facundo Batista | 8c20244 | 2007-09-19 17:53:25 +0000 | [diff] [blame] | 966 | if self._isinteger(): |
| 967 | op = _WorkRep(self.to_integral_value()) |
| 968 | # to make computation feasible for Decimals with large |
| 969 | # exponent, we use the fact that hash(n) == hash(m) for |
| 970 | # any two nonzero integers n and m such that (i) n and m |
| 971 | # have the same sign, and (ii) n is congruent to m modulo |
| 972 | # 2**64-1. So we can replace hash((-1)**s*c*10**e) with |
| 973 | # hash((-1)**s*c*pow(10, e, 2**64-1). |
| 974 | 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] | 975 | # The value of a nonzero nonspecial Decimal instance is |
| 976 | # faithfully represented by the triple consisting of its sign, |
| 977 | # its adjusted exponent, and its coefficient with trailing |
| 978 | # zeros removed. |
| 979 | return hash((self._sign, |
| 980 | self._exp+len(self._int), |
| 981 | self._int.rstrip('0'))) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 982 | |
| 983 | def as_tuple(self): |
| 984 | """Represents the number as a triple tuple. |
| 985 | |
| 986 | To show the internals exactly as they are. |
| 987 | """ |
Raymond Hettinger | 097a190 | 2008-01-11 02:24:13 +0000 | [diff] [blame] | 988 | return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 989 | |
| 990 | def __repr__(self): |
| 991 | """Represents the number as an instance of Decimal.""" |
| 992 | # Invariant: eval(repr(d)) == d |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 993 | return "Decimal('%s')" % str(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 994 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 995 | def __str__(self, eng=False, context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 996 | """Return string representation of the number in scientific notation. |
| 997 | |
| 998 | Captures all of the information in the underlying representation. |
| 999 | """ |
| 1000 | |
Facundo Batista | 62edb71 | 2007-12-03 16:29:52 +0000 | [diff] [blame] | 1001 | sign = ['', '-'][self._sign] |
Raymond Hettinger | e5a0a96 | 2005-06-20 09:49:42 +0000 | [diff] [blame] | 1002 | if self._is_special: |
Facundo Batista | 62edb71 | 2007-12-03 16:29:52 +0000 | [diff] [blame] | 1003 | if self._exp == 'F': |
| 1004 | return sign + 'Infinity' |
| 1005 | elif self._exp == 'n': |
| 1006 | return sign + 'NaN' + self._int |
| 1007 | else: # self._exp == 'N' |
| 1008 | return sign + 'sNaN' + self._int |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1009 | |
Facundo Batista | 62edb71 | 2007-12-03 16:29:52 +0000 | [diff] [blame] | 1010 | # number of digits of self._int to left of decimal point |
| 1011 | leftdigits = self._exp + len(self._int) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1012 | |
Facundo Batista | 62edb71 | 2007-12-03 16:29:52 +0000 | [diff] [blame] | 1013 | # dotplace is number of digits of self._int to the left of the |
| 1014 | # decimal point in the mantissa of the output string (that is, |
| 1015 | # after adjusting the exponent) |
| 1016 | if self._exp <= 0 and leftdigits > -6: |
| 1017 | # no exponent required |
| 1018 | dotplace = leftdigits |
| 1019 | elif not eng: |
| 1020 | # usual scientific notation: 1 digit on left of the point |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1021 | dotplace = 1 |
Facundo Batista | 62edb71 | 2007-12-03 16:29:52 +0000 | [diff] [blame] | 1022 | elif self._int == '0': |
| 1023 | # engineering notation, zero |
| 1024 | dotplace = (leftdigits + 1) % 3 - 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1025 | else: |
Facundo Batista | 62edb71 | 2007-12-03 16:29:52 +0000 | [diff] [blame] | 1026 | # engineering notation, nonzero |
| 1027 | dotplace = (leftdigits - 1) % 3 + 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1028 | |
Facundo Batista | 62edb71 | 2007-12-03 16:29:52 +0000 | [diff] [blame] | 1029 | if dotplace <= 0: |
| 1030 | intpart = '0' |
| 1031 | fracpart = '.' + '0'*(-dotplace) + self._int |
| 1032 | elif dotplace >= len(self._int): |
| 1033 | intpart = self._int+'0'*(dotplace-len(self._int)) |
| 1034 | fracpart = '' |
| 1035 | else: |
| 1036 | intpart = self._int[:dotplace] |
| 1037 | fracpart = '.' + self._int[dotplace:] |
| 1038 | if leftdigits == dotplace: |
| 1039 | exp = '' |
| 1040 | else: |
| 1041 | if context is None: |
| 1042 | context = getcontext() |
| 1043 | exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace) |
| 1044 | |
| 1045 | return sign + intpart + fracpart + exp |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1046 | |
| 1047 | def to_eng_string(self, context=None): |
| 1048 | """Convert to engineering-type string. |
| 1049 | |
| 1050 | Engineering notation has an exponent which is a multiple of 3, so there |
| 1051 | are up to 3 digits left of the decimal place. |
| 1052 | |
| 1053 | Same rules for when in exponential and when as a value as in __str__. |
| 1054 | """ |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1055 | return self.__str__(eng=True, context=context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1056 | |
| 1057 | def __neg__(self, context=None): |
| 1058 | """Returns a copy with the sign switched. |
| 1059 | |
| 1060 | Rounds, if it has reason. |
| 1061 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1062 | if self._is_special: |
| 1063 | ans = self._check_nans(context=context) |
| 1064 | if ans: |
| 1065 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1066 | |
| 1067 | if not self: |
| 1068 | # -Decimal('0') is Decimal('0'), not Decimal('-0') |
Facundo Batista | 0f5e7bf | 2007-12-19 12:53:01 +0000 | [diff] [blame] | 1069 | ans = self.copy_abs() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1070 | else: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1071 | ans = self.copy_negate() |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1072 | |
| 1073 | if context is None: |
| 1074 | context = getcontext() |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1075 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1076 | |
| 1077 | def __pos__(self, context=None): |
| 1078 | """Returns a copy, unless it is a sNaN. |
| 1079 | |
| 1080 | Rounds the number (if more then precision digits) |
| 1081 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1082 | if self._is_special: |
| 1083 | ans = self._check_nans(context=context) |
| 1084 | if ans: |
| 1085 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1086 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1087 | if not self: |
| 1088 | # + (-0) = 0 |
Facundo Batista | 0f5e7bf | 2007-12-19 12:53:01 +0000 | [diff] [blame] | 1089 | ans = self.copy_abs() |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1090 | else: |
| 1091 | ans = Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1092 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1093 | if context is None: |
| 1094 | context = getcontext() |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1095 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1096 | |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1097 | def __abs__(self, round=True, context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1098 | """Returns the absolute value of self. |
| 1099 | |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1100 | If the keyword argument 'round' is false, do not round. The |
| 1101 | expression self.__abs__(round=False) is equivalent to |
| 1102 | self.copy_abs(). |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1103 | """ |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1104 | if not round: |
| 1105 | return self.copy_abs() |
| 1106 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1107 | if self._is_special: |
| 1108 | ans = self._check_nans(context=context) |
| 1109 | if ans: |
| 1110 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1111 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1112 | if self._sign: |
| 1113 | ans = self.__neg__(context=context) |
| 1114 | else: |
| 1115 | ans = self.__pos__(context=context) |
| 1116 | |
| 1117 | return ans |
| 1118 | |
| 1119 | def __add__(self, other, context=None): |
| 1120 | """Returns self + other. |
| 1121 | |
| 1122 | -INF + INF (or the reverse) cause InvalidOperation errors. |
| 1123 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1124 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1125 | if other is NotImplemented: |
| 1126 | return other |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1127 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1128 | if context is None: |
| 1129 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1130 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1131 | if self._is_special or other._is_special: |
| 1132 | ans = self._check_nans(other, context) |
| 1133 | if ans: |
| 1134 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1135 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1136 | if self._isinfinity(): |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 1137 | # If both INF, same sign => same as both, opposite => error. |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1138 | if self._sign != other._sign and other._isinfinity(): |
| 1139 | return context._raise_error(InvalidOperation, '-INF + INF') |
| 1140 | return Decimal(self) |
| 1141 | if other._isinfinity(): |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 1142 | return Decimal(other) # Can't both be infinity here |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1143 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1144 | exp = min(self._exp, other._exp) |
| 1145 | negativezero = 0 |
| 1146 | if context.rounding == ROUND_FLOOR and self._sign != other._sign: |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 1147 | # 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] | 1148 | negativezero = 1 |
| 1149 | |
| 1150 | if not self and not other: |
| 1151 | sign = min(self._sign, other._sign) |
| 1152 | if negativezero: |
| 1153 | sign = 1 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1154 | ans = _dec_from_triple(sign, '0', exp) |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1155 | ans = ans._fix(context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1156 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1157 | if not self: |
Facundo Batista | 99b5548 | 2004-10-26 23:38:46 +0000 | [diff] [blame] | 1158 | exp = max(exp, other._exp - context.prec-1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1159 | ans = other._rescale(exp, context.rounding) |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1160 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1161 | return ans |
| 1162 | if not other: |
Facundo Batista | 99b5548 | 2004-10-26 23:38:46 +0000 | [diff] [blame] | 1163 | exp = max(exp, self._exp - context.prec-1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1164 | ans = self._rescale(exp, context.rounding) |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1165 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1166 | return ans |
| 1167 | |
| 1168 | op1 = _WorkRep(self) |
| 1169 | op2 = _WorkRep(other) |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1170 | op1, op2 = _normalize(op1, op2, context.prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1171 | |
| 1172 | result = _WorkRep() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1173 | if op1.sign != op2.sign: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1174 | # Equal and opposite |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1175 | if op1.int == op2.int: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1176 | ans = _dec_from_triple(negativezero, '0', exp) |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1177 | ans = ans._fix(context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1178 | return ans |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1179 | if op1.int < op2.int: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1180 | op1, op2 = op2, op1 |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 1181 | # OK, now abs(op1) > abs(op2) |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1182 | if op1.sign == 1: |
| 1183 | result.sign = 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1184 | op1.sign, op2.sign = op2.sign, op1.sign |
| 1185 | else: |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1186 | result.sign = 0 |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 1187 | # So we know the sign, and op1 > 0. |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1188 | elif op1.sign == 1: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1189 | result.sign = 1 |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1190 | op1.sign, op2.sign = (0, 0) |
| 1191 | else: |
| 1192 | result.sign = 0 |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 1193 | # Now, op1 > abs(op2) > 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1194 | |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1195 | if op2.sign == 0: |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1196 | result.int = op1.int + op2.int |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1197 | else: |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1198 | result.int = op1.int - op2.int |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1199 | |
| 1200 | result.exp = op1.exp |
| 1201 | ans = Decimal(result) |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1202 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1203 | return ans |
| 1204 | |
| 1205 | __radd__ = __add__ |
| 1206 | |
| 1207 | def __sub__(self, other, context=None): |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1208 | """Return self - other""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1209 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1210 | if other is NotImplemented: |
| 1211 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1212 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1213 | if self._is_special or other._is_special: |
| 1214 | ans = self._check_nans(other, context=context) |
| 1215 | if ans: |
| 1216 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1217 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1218 | # self - other is computed as self + other.copy_negate() |
| 1219 | return self.__add__(other.copy_negate(), context=context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1220 | |
| 1221 | def __rsub__(self, other, context=None): |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1222 | """Return other - self""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1223 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1224 | if other is NotImplemented: |
| 1225 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1226 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1227 | return other.__sub__(self, context=context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1228 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1229 | def __mul__(self, other, context=None): |
| 1230 | """Return self * other. |
| 1231 | |
| 1232 | (+-) INF * 0 (or its reverse) raise InvalidOperation. |
| 1233 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1234 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1235 | if other is NotImplemented: |
| 1236 | return other |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1237 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1238 | if context is None: |
| 1239 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1240 | |
Raymond Hettinger | d87ac8f | 2004-07-09 10:52:54 +0000 | [diff] [blame] | 1241 | resultsign = self._sign ^ other._sign |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1242 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1243 | if self._is_special or other._is_special: |
| 1244 | ans = self._check_nans(other, context) |
| 1245 | if ans: |
| 1246 | return ans |
| 1247 | |
| 1248 | if self._isinfinity(): |
| 1249 | if not other: |
| 1250 | return context._raise_error(InvalidOperation, '(+-)INF * 0') |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 1251 | return _SignedInfinity[resultsign] |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1252 | |
| 1253 | if other._isinfinity(): |
| 1254 | if not self: |
| 1255 | return context._raise_error(InvalidOperation, '0 * (+-)INF') |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 1256 | return _SignedInfinity[resultsign] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1257 | |
| 1258 | resultexp = self._exp + other._exp |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1259 | |
| 1260 | # Special case for multiplying by zero |
| 1261 | if not self or not other: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1262 | ans = _dec_from_triple(resultsign, '0', resultexp) |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1263 | # Fixing in case the exponent is out of bounds |
| 1264 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1265 | return ans |
| 1266 | |
| 1267 | # Special case for multiplying by power of 10 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1268 | if self._int == '1': |
| 1269 | ans = _dec_from_triple(resultsign, other._int, resultexp) |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1270 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1271 | return ans |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1272 | if other._int == '1': |
| 1273 | ans = _dec_from_triple(resultsign, self._int, resultexp) |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1274 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1275 | return ans |
| 1276 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1277 | op1 = _WorkRep(self) |
| 1278 | op2 = _WorkRep(other) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1279 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1280 | ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp) |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1281 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1282 | |
| 1283 | return ans |
| 1284 | __rmul__ = __mul__ |
| 1285 | |
Mark Dickinson | 8aca9d0 | 2008-05-04 02:05:06 +0000 | [diff] [blame] | 1286 | def __truediv__(self, other, context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1287 | """Return self / other.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1288 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1289 | if other is NotImplemented: |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1290 | return NotImplemented |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1291 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1292 | if context is None: |
| 1293 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1294 | |
Raymond Hettinger | d87ac8f | 2004-07-09 10:52:54 +0000 | [diff] [blame] | 1295 | sign = self._sign ^ other._sign |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1296 | |
| 1297 | if self._is_special or other._is_special: |
| 1298 | ans = self._check_nans(other, context) |
| 1299 | if ans: |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1300 | return ans |
| 1301 | |
| 1302 | if self._isinfinity() and other._isinfinity(): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1303 | return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1304 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1305 | if self._isinfinity(): |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 1306 | return _SignedInfinity[sign] |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1307 | |
| 1308 | if other._isinfinity(): |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1309 | context._raise_error(Clamped, 'Division by infinity') |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1310 | return _dec_from_triple(sign, '0', context.Etiny()) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1311 | |
| 1312 | # Special cases for zeroes |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1313 | if not other: |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1314 | if not self: |
| 1315 | return context._raise_error(DivisionUndefined, '0 / 0') |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1316 | return context._raise_error(DivisionByZero, 'x / 0', sign) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1317 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1318 | if not self: |
| 1319 | exp = self._exp - other._exp |
| 1320 | coeff = 0 |
| 1321 | else: |
| 1322 | # OK, so neither = 0, INF or NaN |
| 1323 | shift = len(other._int) - len(self._int) + context.prec + 1 |
| 1324 | exp = self._exp - other._exp - shift |
| 1325 | op1 = _WorkRep(self) |
| 1326 | op2 = _WorkRep(other) |
| 1327 | if shift >= 0: |
| 1328 | coeff, remainder = divmod(op1.int * 10**shift, op2.int) |
| 1329 | else: |
| 1330 | coeff, remainder = divmod(op1.int, op2.int * 10**-shift) |
| 1331 | if remainder: |
| 1332 | # result is not exact; adjust to ensure correct rounding |
| 1333 | if coeff % 5 == 0: |
| 1334 | coeff += 1 |
| 1335 | else: |
| 1336 | # result is exact; get as close to ideal exponent as possible |
| 1337 | ideal_exp = self._exp - other._exp |
| 1338 | while exp < ideal_exp and coeff % 10 == 0: |
| 1339 | coeff //= 10 |
| 1340 | exp += 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1341 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1342 | ans = _dec_from_triple(sign, str(coeff), exp) |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1343 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1344 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1345 | def _divide(self, other, context): |
| 1346 | """Return (self // other, self % other), to context.prec precision. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1347 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1348 | Assumes that neither self nor other is a NaN, that self is not |
| 1349 | infinite and that other is nonzero. |
| 1350 | """ |
| 1351 | sign = self._sign ^ other._sign |
| 1352 | if other._isinfinity(): |
| 1353 | ideal_exp = self._exp |
| 1354 | else: |
| 1355 | ideal_exp = min(self._exp, other._exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1356 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1357 | expdiff = self.adjusted() - other.adjusted() |
| 1358 | if not self or other._isinfinity() or expdiff <= -2: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1359 | return (_dec_from_triple(sign, '0', 0), |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1360 | self._rescale(ideal_exp, context.rounding)) |
| 1361 | if expdiff <= context.prec: |
| 1362 | op1 = _WorkRep(self) |
| 1363 | op2 = _WorkRep(other) |
| 1364 | if op1.exp >= op2.exp: |
| 1365 | op1.int *= 10**(op1.exp - op2.exp) |
| 1366 | else: |
| 1367 | op2.int *= 10**(op2.exp - op1.exp) |
| 1368 | q, r = divmod(op1.int, op2.int) |
| 1369 | if q < 10**context.prec: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1370 | return (_dec_from_triple(sign, str(q), 0), |
| 1371 | _dec_from_triple(self._sign, str(r), ideal_exp)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1372 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1373 | # Here the quotient is too large to be representable |
| 1374 | ans = context._raise_error(DivisionImpossible, |
| 1375 | 'quotient too large in //, % or divmod') |
| 1376 | return ans, ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1377 | |
Mark Dickinson | 8aca9d0 | 2008-05-04 02:05:06 +0000 | [diff] [blame] | 1378 | def __rtruediv__(self, other, context=None): |
| 1379 | """Swaps self/other and returns __truediv__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1380 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1381 | if other is NotImplemented: |
| 1382 | return other |
Mark Dickinson | 8aca9d0 | 2008-05-04 02:05:06 +0000 | [diff] [blame] | 1383 | return other.__truediv__(self, context=context) |
| 1384 | |
| 1385 | __div__ = __truediv__ |
| 1386 | __rdiv__ = __rtruediv__ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1387 | |
| 1388 | def __divmod__(self, other, context=None): |
| 1389 | """ |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1390 | Return (self // other, self % other) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1391 | """ |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1392 | other = _convert_other(other) |
| 1393 | if other is NotImplemented: |
| 1394 | return other |
| 1395 | |
| 1396 | if context is None: |
| 1397 | context = getcontext() |
| 1398 | |
| 1399 | ans = self._check_nans(other, context) |
| 1400 | if ans: |
| 1401 | return (ans, ans) |
| 1402 | |
| 1403 | sign = self._sign ^ other._sign |
| 1404 | if self._isinfinity(): |
| 1405 | if other._isinfinity(): |
| 1406 | ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)') |
| 1407 | return ans, ans |
| 1408 | else: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 1409 | return (_SignedInfinity[sign], |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1410 | context._raise_error(InvalidOperation, 'INF % x')) |
| 1411 | |
| 1412 | if not other: |
| 1413 | if not self: |
| 1414 | ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)') |
| 1415 | return ans, ans |
| 1416 | else: |
| 1417 | return (context._raise_error(DivisionByZero, 'x // 0', sign), |
| 1418 | context._raise_error(InvalidOperation, 'x % 0')) |
| 1419 | |
| 1420 | quotient, remainder = self._divide(other, context) |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1421 | remainder = remainder._fix(context) |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1422 | return quotient, remainder |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1423 | |
| 1424 | def __rdivmod__(self, other, context=None): |
| 1425 | """Swaps self/other and returns __divmod__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1426 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1427 | if other is NotImplemented: |
| 1428 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1429 | return other.__divmod__(self, context=context) |
| 1430 | |
| 1431 | def __mod__(self, other, context=None): |
| 1432 | """ |
| 1433 | self % other |
| 1434 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1435 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1436 | if other is NotImplemented: |
| 1437 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1438 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1439 | if context is None: |
| 1440 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1441 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1442 | ans = self._check_nans(other, context) |
| 1443 | if ans: |
| 1444 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1445 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1446 | if self._isinfinity(): |
| 1447 | return context._raise_error(InvalidOperation, 'INF % x') |
| 1448 | elif not other: |
| 1449 | if self: |
| 1450 | return context._raise_error(InvalidOperation, 'x % 0') |
| 1451 | else: |
| 1452 | return context._raise_error(DivisionUndefined, '0 % 0') |
| 1453 | |
| 1454 | remainder = self._divide(other, context)[1] |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1455 | remainder = remainder._fix(context) |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1456 | return remainder |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1457 | |
| 1458 | def __rmod__(self, other, context=None): |
| 1459 | """Swaps self/other and returns __mod__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1460 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1461 | if other is NotImplemented: |
| 1462 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1463 | return other.__mod__(self, context=context) |
| 1464 | |
| 1465 | def remainder_near(self, other, context=None): |
| 1466 | """ |
| 1467 | Remainder nearest to 0- abs(remainder-near) <= other/2 |
| 1468 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1469 | if context is None: |
| 1470 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1471 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1472 | other = _convert_other(other, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1473 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1474 | ans = self._check_nans(other, context) |
| 1475 | if ans: |
| 1476 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1477 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1478 | # self == +/-infinity -> InvalidOperation |
| 1479 | if self._isinfinity(): |
| 1480 | return context._raise_error(InvalidOperation, |
| 1481 | 'remainder_near(infinity, x)') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1482 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1483 | # other == 0 -> either InvalidOperation or DivisionUndefined |
| 1484 | if not other: |
| 1485 | if self: |
| 1486 | return context._raise_error(InvalidOperation, |
| 1487 | 'remainder_near(x, 0)') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1488 | else: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1489 | return context._raise_error(DivisionUndefined, |
| 1490 | 'remainder_near(0, 0)') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1491 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1492 | # other = +/-infinity -> remainder = self |
| 1493 | if other._isinfinity(): |
| 1494 | ans = Decimal(self) |
| 1495 | return ans._fix(context) |
| 1496 | |
| 1497 | # self = 0 -> remainder = self, with ideal exponent |
| 1498 | ideal_exponent = min(self._exp, other._exp) |
| 1499 | if not self: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1500 | ans = _dec_from_triple(self._sign, '0', ideal_exponent) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1501 | return ans._fix(context) |
| 1502 | |
| 1503 | # catch most cases of large or small quotient |
| 1504 | expdiff = self.adjusted() - other.adjusted() |
| 1505 | if expdiff >= context.prec + 1: |
| 1506 | # expdiff >= prec+1 => abs(self/other) > 10**prec |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1507 | return context._raise_error(DivisionImpossible) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1508 | if expdiff <= -2: |
| 1509 | # expdiff <= -2 => abs(self/other) < 0.1 |
| 1510 | ans = self._rescale(ideal_exponent, context.rounding) |
| 1511 | return ans._fix(context) |
| 1512 | |
| 1513 | # adjust both arguments to have the same exponent, then divide |
| 1514 | op1 = _WorkRep(self) |
| 1515 | op2 = _WorkRep(other) |
| 1516 | if op1.exp >= op2.exp: |
| 1517 | op1.int *= 10**(op1.exp - op2.exp) |
| 1518 | else: |
| 1519 | op2.int *= 10**(op2.exp - op1.exp) |
| 1520 | q, r = divmod(op1.int, op2.int) |
| 1521 | # remainder is r*10**ideal_exponent; other is +/-op2.int * |
| 1522 | # 10**ideal_exponent. Apply correction to ensure that |
| 1523 | # abs(remainder) <= abs(other)/2 |
| 1524 | if 2*r + (q&1) > op2.int: |
| 1525 | r -= op2.int |
| 1526 | q += 1 |
| 1527 | |
| 1528 | if q >= 10**context.prec: |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1529 | return context._raise_error(DivisionImpossible) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1530 | |
| 1531 | # result has same sign as self unless r is negative |
| 1532 | sign = self._sign |
| 1533 | if r < 0: |
| 1534 | sign = 1-sign |
| 1535 | r = -r |
| 1536 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1537 | ans = _dec_from_triple(sign, str(r), ideal_exponent) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1538 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1539 | |
| 1540 | def __floordiv__(self, other, context=None): |
| 1541 | """self // other""" |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1542 | other = _convert_other(other) |
| 1543 | if other is NotImplemented: |
| 1544 | return other |
| 1545 | |
| 1546 | if context is None: |
| 1547 | context = getcontext() |
| 1548 | |
| 1549 | ans = self._check_nans(other, context) |
| 1550 | if ans: |
| 1551 | return ans |
| 1552 | |
| 1553 | if self._isinfinity(): |
| 1554 | if other._isinfinity(): |
| 1555 | return context._raise_error(InvalidOperation, 'INF // INF') |
| 1556 | else: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 1557 | return _SignedInfinity[self._sign ^ other._sign] |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1558 | |
| 1559 | if not other: |
| 1560 | if self: |
| 1561 | return context._raise_error(DivisionByZero, 'x // 0', |
| 1562 | self._sign ^ other._sign) |
| 1563 | else: |
| 1564 | return context._raise_error(DivisionUndefined, '0 // 0') |
| 1565 | |
| 1566 | return self._divide(other, context)[0] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1567 | |
| 1568 | def __rfloordiv__(self, other, context=None): |
| 1569 | """Swaps self/other and returns __floordiv__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1570 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1571 | if other is NotImplemented: |
| 1572 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1573 | return other.__floordiv__(self, context=context) |
| 1574 | |
| 1575 | def __float__(self): |
| 1576 | """Float representation.""" |
| 1577 | return float(str(self)) |
| 1578 | |
| 1579 | def __int__(self): |
Brett Cannon | 46b0802 | 2005-03-01 03:12:26 +0000 | [diff] [blame] | 1580 | """Converts self to an int, truncating if necessary.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1581 | if self._is_special: |
| 1582 | if self._isnan(): |
Mark Dickinson | 968f169 | 2009-09-07 18:04:58 +0000 | [diff] [blame] | 1583 | raise ValueError("Cannot convert NaN to integer") |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1584 | elif self._isinfinity(): |
Mark Dickinson | 968f169 | 2009-09-07 18:04:58 +0000 | [diff] [blame] | 1585 | raise OverflowError("Cannot convert infinity to integer") |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1586 | s = (-1)**self._sign |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1587 | if self._exp >= 0: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1588 | return s*int(self._int)*10**self._exp |
Raymond Hettinger | 605ed02 | 2004-11-24 07:28:48 +0000 | [diff] [blame] | 1589 | else: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1590 | return s*int(self._int[:self._exp] or '0') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1591 | |
Raymond Hettinger | 5a05364 | 2008-01-24 19:05:29 +0000 | [diff] [blame] | 1592 | __trunc__ = __int__ |
| 1593 | |
Raymond Hettinger | 116f72f | 2008-02-12 01:18:03 +0000 | [diff] [blame] | 1594 | def real(self): |
| 1595 | return self |
Mark Dickinson | 65808ff | 2009-01-04 21:22:02 +0000 | [diff] [blame] | 1596 | real = property(real) |
Raymond Hettinger | 116f72f | 2008-02-12 01:18:03 +0000 | [diff] [blame] | 1597 | |
Raymond Hettinger | 116f72f | 2008-02-12 01:18:03 +0000 | [diff] [blame] | 1598 | def imag(self): |
| 1599 | return Decimal(0) |
Mark Dickinson | 65808ff | 2009-01-04 21:22:02 +0000 | [diff] [blame] | 1600 | imag = property(imag) |
Raymond Hettinger | 116f72f | 2008-02-12 01:18:03 +0000 | [diff] [blame] | 1601 | |
| 1602 | def conjugate(self): |
| 1603 | return self |
| 1604 | |
| 1605 | def __complex__(self): |
| 1606 | return complex(float(self)) |
| 1607 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1608 | def __long__(self): |
| 1609 | """Converts to a long. |
| 1610 | |
| 1611 | Equivalent to long(int(self)) |
| 1612 | """ |
| 1613 | return long(self.__int__()) |
| 1614 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1615 | def _fix_nan(self, context): |
| 1616 | """Decapitate the payload of a NaN to fit the context""" |
| 1617 | payload = self._int |
| 1618 | |
| 1619 | # maximum length of payload is precision if _clamp=0, |
| 1620 | # precision-1 if _clamp=1. |
| 1621 | max_payload_len = context.prec - context._clamp |
| 1622 | if len(payload) > max_payload_len: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1623 | payload = payload[len(payload)-max_payload_len:].lstrip('0') |
| 1624 | return _dec_from_triple(self._sign, payload, self._exp, True) |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 1625 | return Decimal(self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1626 | |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1627 | def _fix(self, context): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1628 | """Round if it is necessary to keep self within prec precision. |
| 1629 | |
| 1630 | Rounds and fixes the exponent. Does not raise on a sNaN. |
| 1631 | |
| 1632 | Arguments: |
| 1633 | self - Decimal instance |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1634 | context - context used. |
| 1635 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1636 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1637 | if self._is_special: |
| 1638 | if self._isnan(): |
| 1639 | # decapitate payload if necessary |
| 1640 | return self._fix_nan(context) |
| 1641 | else: |
| 1642 | # self is +/-Infinity; return unaltered |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 1643 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1644 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1645 | # if self is zero then exponent should be between Etiny and |
| 1646 | # Emax if _clamp==0, and between Etiny and Etop if _clamp==1. |
| 1647 | Etiny = context.Etiny() |
| 1648 | Etop = context.Etop() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1649 | if not self: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1650 | exp_max = [context.Emax, Etop][context._clamp] |
| 1651 | new_exp = min(max(self._exp, Etiny), exp_max) |
| 1652 | if new_exp != self._exp: |
| 1653 | context._raise_error(Clamped) |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1654 | return _dec_from_triple(self._sign, '0', new_exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1655 | else: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 1656 | return Decimal(self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1657 | |
| 1658 | # exp_min is the smallest allowable exponent of the result, |
| 1659 | # equal to max(self.adjusted()-context.prec+1, Etiny) |
| 1660 | exp_min = len(self._int) + self._exp - context.prec |
| 1661 | if exp_min > Etop: |
| 1662 | # overflow: exp_min > Etop iff self.adjusted() > Emax |
| 1663 | context._raise_error(Inexact) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1664 | context._raise_error(Rounded) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1665 | return context._raise_error(Overflow, 'above Emax', self._sign) |
| 1666 | self_is_subnormal = exp_min < Etiny |
| 1667 | if self_is_subnormal: |
| 1668 | context._raise_error(Subnormal) |
| 1669 | exp_min = Etiny |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1670 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1671 | # round if self has too many digits |
| 1672 | if self._exp < exp_min: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1673 | context._raise_error(Rounded) |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1674 | digits = len(self._int) + self._exp - exp_min |
| 1675 | if digits < 0: |
| 1676 | self = _dec_from_triple(self._sign, '1', exp_min-1) |
| 1677 | digits = 0 |
| 1678 | this_function = getattr(self, self._pick_rounding_function[context.rounding]) |
| 1679 | changed = this_function(digits) |
| 1680 | coeff = self._int[:digits] or '0' |
| 1681 | if changed == 1: |
| 1682 | coeff = str(int(coeff)+1) |
| 1683 | ans = _dec_from_triple(self._sign, coeff, exp_min) |
| 1684 | |
| 1685 | if changed: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1686 | context._raise_error(Inexact) |
| 1687 | if self_is_subnormal: |
| 1688 | context._raise_error(Underflow) |
| 1689 | if not ans: |
| 1690 | # raise Clamped on underflow to 0 |
| 1691 | context._raise_error(Clamped) |
| 1692 | elif len(ans._int) == context.prec+1: |
| 1693 | # we get here only if rescaling rounds the |
| 1694 | # cofficient up to exactly 10**context.prec |
| 1695 | if ans._exp < Etop: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1696 | ans = _dec_from_triple(ans._sign, |
| 1697 | ans._int[:-1], ans._exp+1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1698 | else: |
| 1699 | # Inexact and Rounded have already been raised |
| 1700 | ans = context._raise_error(Overflow, 'above Emax', |
| 1701 | self._sign) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1702 | return ans |
| 1703 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1704 | # fold down if _clamp == 1 and self has too few digits |
| 1705 | if context._clamp == 1 and self._exp > Etop: |
| 1706 | context._raise_error(Clamped) |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1707 | self_padded = self._int + '0'*(self._exp - Etop) |
| 1708 | return _dec_from_triple(self._sign, self_padded, Etop) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1709 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1710 | # here self was representable to begin with; return unchanged |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 1711 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1712 | |
| 1713 | _pick_rounding_function = {} |
| 1714 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1715 | # for each of the rounding functions below: |
| 1716 | # self is a finite, nonzero Decimal |
| 1717 | # prec is an integer satisfying 0 <= prec < len(self._int) |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1718 | # |
| 1719 | # each function returns either -1, 0, or 1, as follows: |
| 1720 | # 1 indicates that self should be rounded up (away from zero) |
| 1721 | # 0 indicates that self should be truncated, and that all the |
| 1722 | # digits to be truncated are zeros (so the value is unchanged) |
| 1723 | # -1 indicates that there are nonzero digits to be truncated |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1724 | |
| 1725 | def _round_down(self, prec): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1726 | """Also known as round-towards-0, truncate.""" |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1727 | if _all_zeros(self._int, prec): |
| 1728 | return 0 |
| 1729 | else: |
| 1730 | return -1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1731 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1732 | def _round_up(self, prec): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1733 | """Rounds away from 0.""" |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1734 | return -self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1735 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1736 | def _round_half_up(self, prec): |
| 1737 | """Rounds 5 up (away from 0)""" |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1738 | if self._int[prec] in '56789': |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1739 | return 1 |
| 1740 | elif _all_zeros(self._int, prec): |
| 1741 | return 0 |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1742 | else: |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1743 | return -1 |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1744 | |
| 1745 | def _round_half_down(self, prec): |
| 1746 | """Round 5 down""" |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1747 | if _exact_half(self._int, prec): |
| 1748 | return -1 |
| 1749 | else: |
| 1750 | return self._round_half_up(prec) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1751 | |
| 1752 | def _round_half_even(self, prec): |
| 1753 | """Round 5 to even, rest to nearest.""" |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1754 | if _exact_half(self._int, prec) and \ |
| 1755 | (prec == 0 or self._int[prec-1] in '02468'): |
| 1756 | return -1 |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1757 | else: |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1758 | return self._round_half_up(prec) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1759 | |
| 1760 | def _round_ceiling(self, prec): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1761 | """Rounds up (not away from 0 if negative.)""" |
| 1762 | if self._sign: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1763 | return self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1764 | else: |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1765 | return -self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1766 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1767 | def _round_floor(self, prec): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1768 | """Rounds down (not towards 0 if negative)""" |
| 1769 | if not self._sign: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1770 | return self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1771 | else: |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1772 | return -self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1773 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1774 | def _round_05up(self, prec): |
| 1775 | """Round down unless digit prec-1 is 0 or 5.""" |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1776 | if prec and self._int[prec-1] not in '05': |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1777 | return self._round_down(prec) |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1778 | else: |
| 1779 | return -self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1780 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1781 | def fma(self, other, third, context=None): |
| 1782 | """Fused multiply-add. |
| 1783 | |
| 1784 | Returns self*other+third with no rounding of the intermediate |
| 1785 | product self*other. |
| 1786 | |
| 1787 | self and other are multiplied together, with no rounding of |
| 1788 | the result. The third operand is then added to the result, |
| 1789 | and a single final rounding is performed. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1790 | """ |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1791 | |
| 1792 | other = _convert_other(other, raiseit=True) |
Facundo Batista | 58f6f2e | 2007-12-04 16:31:53 +0000 | [diff] [blame] | 1793 | |
| 1794 | # compute product; raise InvalidOperation if either operand is |
| 1795 | # a signaling NaN or if the product is zero times infinity. |
| 1796 | if self._is_special or other._is_special: |
| 1797 | if context is None: |
| 1798 | context = getcontext() |
| 1799 | if self._exp == 'N': |
Facundo Batista | 0f5e7bf | 2007-12-19 12:53:01 +0000 | [diff] [blame] | 1800 | return context._raise_error(InvalidOperation, 'sNaN', self) |
Facundo Batista | 58f6f2e | 2007-12-04 16:31:53 +0000 | [diff] [blame] | 1801 | if other._exp == 'N': |
Facundo Batista | 0f5e7bf | 2007-12-19 12:53:01 +0000 | [diff] [blame] | 1802 | return context._raise_error(InvalidOperation, 'sNaN', other) |
Facundo Batista | 58f6f2e | 2007-12-04 16:31:53 +0000 | [diff] [blame] | 1803 | if self._exp == 'n': |
| 1804 | product = self |
| 1805 | elif other._exp == 'n': |
| 1806 | product = other |
| 1807 | elif self._exp == 'F': |
| 1808 | if not other: |
| 1809 | return context._raise_error(InvalidOperation, |
| 1810 | 'INF * 0 in fma') |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 1811 | product = _SignedInfinity[self._sign ^ other._sign] |
Facundo Batista | 58f6f2e | 2007-12-04 16:31:53 +0000 | [diff] [blame] | 1812 | elif other._exp == 'F': |
| 1813 | if not self: |
| 1814 | return context._raise_error(InvalidOperation, |
| 1815 | '0 * INF in fma') |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 1816 | product = _SignedInfinity[self._sign ^ other._sign] |
Facundo Batista | 58f6f2e | 2007-12-04 16:31:53 +0000 | [diff] [blame] | 1817 | else: |
| 1818 | product = _dec_from_triple(self._sign ^ other._sign, |
| 1819 | str(int(self._int) * int(other._int)), |
| 1820 | self._exp + other._exp) |
| 1821 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1822 | third = _convert_other(third, raiseit=True) |
Facundo Batista | 58f6f2e | 2007-12-04 16:31:53 +0000 | [diff] [blame] | 1823 | return product.__add__(third, context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1824 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1825 | def _power_modulo(self, other, modulo, context=None): |
| 1826 | """Three argument version of __pow__""" |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1827 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1828 | # if can't convert other and modulo to Decimal, raise |
| 1829 | # TypeError; there's no point returning NotImplemented (no |
| 1830 | # equivalent of __rpow__ for three argument pow) |
| 1831 | other = _convert_other(other, raiseit=True) |
| 1832 | modulo = _convert_other(modulo, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1833 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1834 | if context is None: |
| 1835 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1836 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1837 | # deal with NaNs: if there are any sNaNs then first one wins, |
| 1838 | # (i.e. behaviour for NaNs is identical to that of fma) |
| 1839 | self_is_nan = self._isnan() |
| 1840 | other_is_nan = other._isnan() |
| 1841 | modulo_is_nan = modulo._isnan() |
| 1842 | if self_is_nan or other_is_nan or modulo_is_nan: |
| 1843 | if self_is_nan == 2: |
| 1844 | return context._raise_error(InvalidOperation, 'sNaN', |
Facundo Batista | 0f5e7bf | 2007-12-19 12:53:01 +0000 | [diff] [blame] | 1845 | self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1846 | if other_is_nan == 2: |
| 1847 | return context._raise_error(InvalidOperation, 'sNaN', |
Facundo Batista | 0f5e7bf | 2007-12-19 12:53:01 +0000 | [diff] [blame] | 1848 | other) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1849 | if modulo_is_nan == 2: |
| 1850 | return context._raise_error(InvalidOperation, 'sNaN', |
Facundo Batista | 0f5e7bf | 2007-12-19 12:53:01 +0000 | [diff] [blame] | 1851 | modulo) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1852 | if self_is_nan: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 1853 | return self._fix_nan(context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1854 | if other_is_nan: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 1855 | return other._fix_nan(context) |
| 1856 | return modulo._fix_nan(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1857 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1858 | # check inputs: we apply same restrictions as Python's pow() |
| 1859 | if not (self._isinteger() and |
| 1860 | other._isinteger() and |
| 1861 | modulo._isinteger()): |
| 1862 | return context._raise_error(InvalidOperation, |
| 1863 | 'pow() 3rd argument not allowed ' |
| 1864 | 'unless all arguments are integers') |
| 1865 | if other < 0: |
| 1866 | return context._raise_error(InvalidOperation, |
| 1867 | 'pow() 2nd argument cannot be ' |
| 1868 | 'negative when 3rd argument specified') |
| 1869 | if not modulo: |
| 1870 | return context._raise_error(InvalidOperation, |
| 1871 | 'pow() 3rd argument cannot be 0') |
| 1872 | |
| 1873 | # additional restriction for decimal: the modulus must be less |
| 1874 | # than 10**prec in absolute value |
| 1875 | if modulo.adjusted() >= context.prec: |
| 1876 | return context._raise_error(InvalidOperation, |
| 1877 | 'insufficient precision: pow() 3rd ' |
| 1878 | 'argument must not have more than ' |
| 1879 | 'precision digits') |
| 1880 | |
| 1881 | # define 0**0 == NaN, for consistency with two-argument pow |
| 1882 | # (even though it hurts!) |
| 1883 | if not other and not self: |
| 1884 | return context._raise_error(InvalidOperation, |
| 1885 | 'at least one of pow() 1st argument ' |
| 1886 | 'and 2nd argument must be nonzero ;' |
| 1887 | '0**0 is not defined') |
| 1888 | |
| 1889 | # compute sign of result |
| 1890 | if other._iseven(): |
| 1891 | sign = 0 |
| 1892 | else: |
| 1893 | sign = self._sign |
| 1894 | |
| 1895 | # convert modulo to a Python integer, and self and other to |
| 1896 | # Decimal integers (i.e. force their exponents to be >= 0) |
| 1897 | modulo = abs(int(modulo)) |
| 1898 | base = _WorkRep(self.to_integral_value()) |
| 1899 | exponent = _WorkRep(other.to_integral_value()) |
| 1900 | |
| 1901 | # compute result using integer pow() |
| 1902 | base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo |
| 1903 | for i in xrange(exponent.exp): |
| 1904 | base = pow(base, 10, modulo) |
| 1905 | base = pow(base, exponent.int, modulo) |
| 1906 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1907 | return _dec_from_triple(sign, str(base), 0) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1908 | |
| 1909 | def _power_exact(self, other, p): |
| 1910 | """Attempt to compute self**other exactly. |
| 1911 | |
| 1912 | Given Decimals self and other and an integer p, attempt to |
| 1913 | compute an exact result for the power self**other, with p |
| 1914 | digits of precision. Return None if self**other is not |
| 1915 | exactly representable in p digits. |
| 1916 | |
| 1917 | Assumes that elimination of special cases has already been |
| 1918 | performed: self and other must both be nonspecial; self must |
| 1919 | be positive and not numerically equal to 1; other must be |
| 1920 | nonzero. For efficiency, other._exp should not be too large, |
| 1921 | so that 10**abs(other._exp) is a feasible calculation.""" |
| 1922 | |
| 1923 | # In the comments below, we write x for the value of self and |
| 1924 | # y for the value of other. Write x = xc*10**xe and y = |
| 1925 | # yc*10**ye. |
| 1926 | |
| 1927 | # The main purpose of this method is to identify the *failure* |
| 1928 | # of x**y to be exactly representable with as little effort as |
| 1929 | # possible. So we look for cheap and easy tests that |
| 1930 | # eliminate the possibility of x**y being exact. Only if all |
| 1931 | # these tests are passed do we go on to actually compute x**y. |
| 1932 | |
| 1933 | # Here's the main idea. First normalize both x and y. We |
| 1934 | # express y as a rational m/n, with m and n relatively prime |
| 1935 | # and n>0. Then for x**y to be exactly representable (at |
| 1936 | # *any* precision), xc must be the nth power of a positive |
| 1937 | # integer and xe must be divisible by n. If m is negative |
| 1938 | # then additionally xc must be a power of either 2 or 5, hence |
| 1939 | # a power of 2**n or 5**n. |
| 1940 | # |
| 1941 | # There's a limit to how small |y| can be: if y=m/n as above |
| 1942 | # then: |
| 1943 | # |
| 1944 | # (1) if xc != 1 then for the result to be representable we |
| 1945 | # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So |
| 1946 | # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <= |
| 1947 | # 2**(1/|y|), hence xc**|y| < 2 and the result is not |
| 1948 | # representable. |
| 1949 | # |
| 1950 | # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if |
| 1951 | # |y| < 1/|xe| then the result is not representable. |
| 1952 | # |
| 1953 | # Note that since x is not equal to 1, at least one of (1) and |
| 1954 | # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) < |
| 1955 | # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye. |
| 1956 | # |
| 1957 | # There's also a limit to how large y can be, at least if it's |
| 1958 | # positive: the normalized result will have coefficient xc**y, |
| 1959 | # so if it's representable then xc**y < 10**p, and y < |
| 1960 | # p/log10(xc). Hence if y*log10(xc) >= p then the result is |
| 1961 | # not exactly representable. |
| 1962 | |
| 1963 | # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye, |
| 1964 | # so |y| < 1/xe and the result is not representable. |
| 1965 | # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y| |
| 1966 | # < 1/nbits(xc). |
| 1967 | |
| 1968 | x = _WorkRep(self) |
| 1969 | xc, xe = x.int, x.exp |
| 1970 | while xc % 10 == 0: |
| 1971 | xc //= 10 |
| 1972 | xe += 1 |
| 1973 | |
| 1974 | y = _WorkRep(other) |
| 1975 | yc, ye = y.int, y.exp |
| 1976 | while yc % 10 == 0: |
| 1977 | yc //= 10 |
| 1978 | ye += 1 |
| 1979 | |
| 1980 | # case where xc == 1: result is 10**(xe*y), with xe*y |
| 1981 | # required to be an integer |
| 1982 | if xc == 1: |
| 1983 | if ye >= 0: |
| 1984 | exponent = xe*yc*10**ye |
| 1985 | else: |
| 1986 | exponent, remainder = divmod(xe*yc, 10**-ye) |
| 1987 | if remainder: |
| 1988 | return None |
| 1989 | if y.sign == 1: |
| 1990 | exponent = -exponent |
| 1991 | # if other is a nonnegative integer, use ideal exponent |
| 1992 | if other._isinteger() and other._sign == 0: |
| 1993 | ideal_exponent = self._exp*int(other) |
| 1994 | zeros = min(exponent-ideal_exponent, p-1) |
| 1995 | else: |
| 1996 | zeros = 0 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1997 | return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1998 | |
| 1999 | # case where y is negative: xc must be either a power |
| 2000 | # of 2 or a power of 5. |
| 2001 | if y.sign == 1: |
| 2002 | last_digit = xc % 10 |
| 2003 | if last_digit in (2,4,6,8): |
| 2004 | # quick test for power of 2 |
| 2005 | if xc & -xc != xc: |
| 2006 | return None |
| 2007 | # now xc is a power of 2; e is its exponent |
| 2008 | e = _nbits(xc)-1 |
| 2009 | # find e*y and xe*y; both must be integers |
| 2010 | if ye >= 0: |
| 2011 | y_as_int = yc*10**ye |
| 2012 | e = e*y_as_int |
| 2013 | xe = xe*y_as_int |
| 2014 | else: |
| 2015 | ten_pow = 10**-ye |
| 2016 | e, remainder = divmod(e*yc, ten_pow) |
| 2017 | if remainder: |
| 2018 | return None |
| 2019 | xe, remainder = divmod(xe*yc, ten_pow) |
| 2020 | if remainder: |
| 2021 | return None |
| 2022 | |
| 2023 | if e*65 >= p*93: # 93/65 > log(10)/log(5) |
| 2024 | return None |
| 2025 | xc = 5**e |
| 2026 | |
| 2027 | elif last_digit == 5: |
| 2028 | # e >= log_5(xc) if xc is a power of 5; we have |
| 2029 | # equality all the way up to xc=5**2658 |
| 2030 | e = _nbits(xc)*28//65 |
| 2031 | xc, remainder = divmod(5**e, xc) |
| 2032 | if remainder: |
| 2033 | return None |
| 2034 | while xc % 5 == 0: |
| 2035 | xc //= 5 |
| 2036 | e -= 1 |
| 2037 | if ye >= 0: |
| 2038 | y_as_integer = yc*10**ye |
| 2039 | e = e*y_as_integer |
| 2040 | xe = xe*y_as_integer |
| 2041 | else: |
| 2042 | ten_pow = 10**-ye |
| 2043 | e, remainder = divmod(e*yc, ten_pow) |
| 2044 | if remainder: |
| 2045 | return None |
| 2046 | xe, remainder = divmod(xe*yc, ten_pow) |
| 2047 | if remainder: |
| 2048 | return None |
| 2049 | if e*3 >= p*10: # 10/3 > log(10)/log(2) |
| 2050 | return None |
| 2051 | xc = 2**e |
| 2052 | else: |
| 2053 | return None |
| 2054 | |
| 2055 | if xc >= 10**p: |
| 2056 | return None |
| 2057 | xe = -e-xe |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2058 | return _dec_from_triple(0, str(xc), xe) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2059 | |
| 2060 | # now y is positive; find m and n such that y = m/n |
| 2061 | if ye >= 0: |
| 2062 | m, n = yc*10**ye, 1 |
| 2063 | else: |
| 2064 | if xe != 0 and len(str(abs(yc*xe))) <= -ye: |
| 2065 | return None |
| 2066 | xc_bits = _nbits(xc) |
| 2067 | if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye: |
| 2068 | return None |
| 2069 | m, n = yc, 10**(-ye) |
| 2070 | while m % 2 == n % 2 == 0: |
| 2071 | m //= 2 |
| 2072 | n //= 2 |
| 2073 | while m % 5 == n % 5 == 0: |
| 2074 | m //= 5 |
| 2075 | n //= 5 |
| 2076 | |
| 2077 | # compute nth root of xc*10**xe |
| 2078 | if n > 1: |
| 2079 | # if 1 < xc < 2**n then xc isn't an nth power |
| 2080 | if xc != 1 and xc_bits <= n: |
| 2081 | return None |
| 2082 | |
| 2083 | xe, rem = divmod(xe, n) |
| 2084 | if rem != 0: |
| 2085 | return None |
| 2086 | |
| 2087 | # compute nth root of xc using Newton's method |
| 2088 | a = 1L << -(-_nbits(xc)//n) # initial estimate |
| 2089 | while True: |
| 2090 | q, r = divmod(xc, a**(n-1)) |
| 2091 | if a <= q: |
| 2092 | break |
| 2093 | else: |
| 2094 | a = (a*(n-1) + q)//n |
| 2095 | if not (a == q and r == 0): |
| 2096 | return None |
| 2097 | xc = a |
| 2098 | |
| 2099 | # now xc*10**xe is the nth root of the original xc*10**xe |
| 2100 | # compute mth power of xc*10**xe |
| 2101 | |
| 2102 | # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m > |
| 2103 | # 10**p and the result is not representable. |
| 2104 | if xc > 1 and m > p*100//_log10_lb(xc): |
| 2105 | return None |
| 2106 | xc = xc**m |
| 2107 | xe *= m |
| 2108 | if xc > 10**p: |
| 2109 | return None |
| 2110 | |
| 2111 | # by this point the result *is* exactly representable |
| 2112 | # adjust the exponent to get as close as possible to the ideal |
| 2113 | # exponent, if necessary |
| 2114 | str_xc = str(xc) |
| 2115 | if other._isinteger() and other._sign == 0: |
| 2116 | ideal_exponent = self._exp*int(other) |
| 2117 | zeros = min(xe-ideal_exponent, p-len(str_xc)) |
| 2118 | else: |
| 2119 | zeros = 0 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2120 | return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2121 | |
| 2122 | def __pow__(self, other, modulo=None, context=None): |
| 2123 | """Return self ** other [ % modulo]. |
| 2124 | |
| 2125 | With two arguments, compute self**other. |
| 2126 | |
| 2127 | With three arguments, compute (self**other) % modulo. For the |
| 2128 | three argument form, the following restrictions on the |
| 2129 | arguments hold: |
| 2130 | |
| 2131 | - all three arguments must be integral |
| 2132 | - other must be nonnegative |
| 2133 | - either self or other (or both) must be nonzero |
| 2134 | - modulo must be nonzero and must have at most p digits, |
| 2135 | where p is the context precision. |
| 2136 | |
| 2137 | If any of these restrictions is violated the InvalidOperation |
| 2138 | flag is raised. |
| 2139 | |
| 2140 | The result of pow(self, other, modulo) is identical to the |
| 2141 | result that would be obtained by computing (self**other) % |
| 2142 | modulo with unbounded precision, but is computed more |
| 2143 | efficiently. It is always exact. |
| 2144 | """ |
| 2145 | |
| 2146 | if modulo is not None: |
| 2147 | return self._power_modulo(other, modulo, context) |
| 2148 | |
| 2149 | other = _convert_other(other) |
| 2150 | if other is NotImplemented: |
| 2151 | return other |
| 2152 | |
| 2153 | if context is None: |
| 2154 | context = getcontext() |
| 2155 | |
| 2156 | # either argument is a NaN => result is NaN |
| 2157 | ans = self._check_nans(other, context) |
| 2158 | if ans: |
| 2159 | return ans |
| 2160 | |
| 2161 | # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity) |
| 2162 | if not other: |
| 2163 | if not self: |
| 2164 | return context._raise_error(InvalidOperation, '0 ** 0') |
| 2165 | else: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 2166 | return _One |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2167 | |
| 2168 | # result has sign 1 iff self._sign is 1 and other is an odd integer |
| 2169 | result_sign = 0 |
| 2170 | if self._sign == 1: |
| 2171 | if other._isinteger(): |
| 2172 | if not other._iseven(): |
| 2173 | result_sign = 1 |
| 2174 | else: |
| 2175 | # -ve**noninteger = NaN |
| 2176 | # (-0)**noninteger = 0**noninteger |
| 2177 | if self: |
| 2178 | return context._raise_error(InvalidOperation, |
| 2179 | 'x ** y with x negative and y not an integer') |
| 2180 | # negate self, without doing any unwanted rounding |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2181 | self = self.copy_negate() |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2182 | |
| 2183 | # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity |
| 2184 | if not self: |
| 2185 | if other._sign == 0: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2186 | return _dec_from_triple(result_sign, '0', 0) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2187 | else: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 2188 | return _SignedInfinity[result_sign] |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2189 | |
| 2190 | # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2191 | if self._isinfinity(): |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2192 | if other._sign == 0: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 2193 | return _SignedInfinity[result_sign] |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2194 | else: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2195 | return _dec_from_triple(result_sign, '0', 0) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2196 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2197 | # 1**other = 1, but the choice of exponent and the flags |
| 2198 | # depend on the exponent of self, and on whether other is a |
| 2199 | # positive integer, a negative integer, or neither |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 2200 | if self == _One: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2201 | if other._isinteger(): |
| 2202 | # exp = max(self._exp*max(int(other), 0), |
| 2203 | # 1-context.prec) but evaluating int(other) directly |
| 2204 | # is dangerous until we know other is small (other |
| 2205 | # could be 1e999999999) |
| 2206 | if other._sign == 1: |
| 2207 | multiplier = 0 |
| 2208 | elif other > context.prec: |
| 2209 | multiplier = context.prec |
| 2210 | else: |
| 2211 | multiplier = int(other) |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 2212 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2213 | exp = self._exp * multiplier |
| 2214 | if exp < 1-context.prec: |
| 2215 | exp = 1-context.prec |
| 2216 | context._raise_error(Rounded) |
| 2217 | else: |
| 2218 | context._raise_error(Inexact) |
| 2219 | context._raise_error(Rounded) |
| 2220 | exp = 1-context.prec |
| 2221 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2222 | return _dec_from_triple(result_sign, '1'+'0'*-exp, exp) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2223 | |
| 2224 | # compute adjusted exponent of self |
| 2225 | self_adj = self.adjusted() |
| 2226 | |
| 2227 | # self ** infinity is infinity if self > 1, 0 if self < 1 |
| 2228 | # self ** -infinity is infinity if self < 1, 0 if self > 1 |
| 2229 | if other._isinfinity(): |
| 2230 | if (other._sign == 0) == (self_adj < 0): |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2231 | return _dec_from_triple(result_sign, '0', 0) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2232 | else: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 2233 | return _SignedInfinity[result_sign] |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2234 | |
| 2235 | # from here on, the result always goes through the call |
| 2236 | # to _fix at the end of this function. |
| 2237 | ans = None |
| 2238 | |
| 2239 | # crude test to catch cases of extreme overflow/underflow. If |
| 2240 | # log10(self)*other >= 10**bound and bound >= len(str(Emax)) |
| 2241 | # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence |
| 2242 | # self**other >= 10**(Emax+1), so overflow occurs. The test |
| 2243 | # for underflow is similar. |
| 2244 | bound = self._log10_exp_bound() + other.adjusted() |
| 2245 | if (self_adj >= 0) == (other._sign == 0): |
| 2246 | # self > 1 and other +ve, or self < 1 and other -ve |
| 2247 | # possibility of overflow |
| 2248 | if bound >= len(str(context.Emax)): |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2249 | ans = _dec_from_triple(result_sign, '1', context.Emax+1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2250 | else: |
| 2251 | # self > 1 and other -ve, or self < 1 and other +ve |
| 2252 | # possibility of underflow to 0 |
| 2253 | Etiny = context.Etiny() |
| 2254 | if bound >= len(str(-Etiny)): |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2255 | ans = _dec_from_triple(result_sign, '1', Etiny-1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2256 | |
| 2257 | # try for an exact result with precision +1 |
| 2258 | if ans is None: |
| 2259 | ans = self._power_exact(other, context.prec + 1) |
| 2260 | if ans is not None and result_sign == 1: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2261 | ans = _dec_from_triple(1, ans._int, ans._exp) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2262 | |
| 2263 | # usual case: inexact result, x**y computed directly as exp(y*log(x)) |
| 2264 | if ans is None: |
| 2265 | p = context.prec |
| 2266 | x = _WorkRep(self) |
| 2267 | xc, xe = x.int, x.exp |
| 2268 | y = _WorkRep(other) |
| 2269 | yc, ye = y.int, y.exp |
| 2270 | if y.sign == 1: |
| 2271 | yc = -yc |
| 2272 | |
| 2273 | # compute correctly rounded result: start with precision +3, |
| 2274 | # then increase precision until result is unambiguously roundable |
| 2275 | extra = 3 |
| 2276 | while True: |
| 2277 | coeff, exp = _dpower(xc, xe, yc, ye, p+extra) |
| 2278 | if coeff % (5*10**(len(str(coeff))-p-1)): |
| 2279 | break |
| 2280 | extra += 3 |
| 2281 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2282 | ans = _dec_from_triple(result_sign, str(coeff), exp) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2283 | |
| 2284 | # the specification says that for non-integer other we need to |
| 2285 | # raise Inexact, even when the result is actually exact. In |
| 2286 | # the same way, we need to raise Underflow here if the result |
| 2287 | # is subnormal. (The call to _fix will take care of raising |
| 2288 | # Rounded and Subnormal, as usual.) |
| 2289 | if not other._isinteger(): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2290 | context._raise_error(Inexact) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2291 | # pad with zeros up to length context.prec+1 if necessary |
| 2292 | if len(ans._int) <= context.prec: |
| 2293 | expdiff = context.prec+1 - len(ans._int) |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2294 | ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff, |
| 2295 | ans._exp-expdiff) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2296 | if ans.adjusted() < context.Emin: |
| 2297 | context._raise_error(Underflow) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2298 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2299 | # unlike exp, ln and log10, the power function respects the |
| 2300 | # rounding mode; no need to use ROUND_HALF_EVEN here |
| 2301 | ans = ans._fix(context) |
| 2302 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2303 | |
| 2304 | def __rpow__(self, other, context=None): |
| 2305 | """Swaps self/other and returns __pow__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2306 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 2307 | if other is NotImplemented: |
| 2308 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2309 | return other.__pow__(self, context=context) |
| 2310 | |
| 2311 | def normalize(self, context=None): |
| 2312 | """Normalize- strip trailing 0s, change anything equal to 0 to 0e0""" |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2313 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2314 | if context is None: |
| 2315 | context = getcontext() |
| 2316 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2317 | if self._is_special: |
| 2318 | ans = self._check_nans(context=context) |
| 2319 | if ans: |
| 2320 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2321 | |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 2322 | dup = self._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2323 | if dup._isinfinity(): |
| 2324 | return dup |
| 2325 | |
| 2326 | if not dup: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2327 | return _dec_from_triple(dup._sign, '0', 0) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2328 | exp_max = [context.Emax, context.Etop()][context._clamp] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2329 | end = len(dup._int) |
| 2330 | exp = dup._exp |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2331 | while dup._int[end-1] == '0' and exp < exp_max: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2332 | exp += 1 |
| 2333 | end -= 1 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2334 | return _dec_from_triple(dup._sign, dup._int[:end], exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2335 | |
Facundo Batista | bd2fe83 | 2007-09-13 18:42:09 +0000 | [diff] [blame] | 2336 | def quantize(self, exp, rounding=None, context=None, watchexp=True): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2337 | """Quantize self so its exponent is the same as that of exp. |
| 2338 | |
| 2339 | Similar to self._rescale(exp._exp) but with error checking. |
| 2340 | """ |
Facundo Batista | bd2fe83 | 2007-09-13 18:42:09 +0000 | [diff] [blame] | 2341 | exp = _convert_other(exp, raiseit=True) |
| 2342 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2343 | if context is None: |
| 2344 | context = getcontext() |
| 2345 | if rounding is None: |
| 2346 | rounding = context.rounding |
| 2347 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2348 | if self._is_special or exp._is_special: |
| 2349 | ans = self._check_nans(exp, context) |
| 2350 | if ans: |
| 2351 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2352 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2353 | if exp._isinfinity() or self._isinfinity(): |
| 2354 | if exp._isinfinity() and self._isinfinity(): |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2355 | return Decimal(self) # if both are inf, it is OK |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2356 | return context._raise_error(InvalidOperation, |
| 2357 | 'quantize with one INF') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2358 | |
Facundo Batista | bd2fe83 | 2007-09-13 18:42:09 +0000 | [diff] [blame] | 2359 | # if we're not watching exponents, do a simple rescale |
| 2360 | if not watchexp: |
| 2361 | ans = self._rescale(exp._exp, rounding) |
| 2362 | # raise Inexact and Rounded where appropriate |
| 2363 | if ans._exp > self._exp: |
| 2364 | context._raise_error(Rounded) |
| 2365 | if ans != self: |
| 2366 | context._raise_error(Inexact) |
| 2367 | return ans |
| 2368 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2369 | # exp._exp should be between Etiny and Emax |
| 2370 | if not (context.Etiny() <= exp._exp <= context.Emax): |
| 2371 | return context._raise_error(InvalidOperation, |
| 2372 | 'target exponent out of bounds in quantize') |
| 2373 | |
| 2374 | if not self: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2375 | ans = _dec_from_triple(self._sign, '0', exp._exp) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2376 | return ans._fix(context) |
| 2377 | |
| 2378 | self_adjusted = self.adjusted() |
| 2379 | if self_adjusted > context.Emax: |
| 2380 | return context._raise_error(InvalidOperation, |
| 2381 | 'exponent of quantize result too large for current context') |
| 2382 | if self_adjusted - exp._exp + 1 > context.prec: |
| 2383 | return context._raise_error(InvalidOperation, |
| 2384 | 'quantize result has too many digits for current context') |
| 2385 | |
| 2386 | ans = self._rescale(exp._exp, rounding) |
| 2387 | if ans.adjusted() > context.Emax: |
| 2388 | return context._raise_error(InvalidOperation, |
| 2389 | 'exponent of quantize result too large for current context') |
| 2390 | if len(ans._int) > context.prec: |
| 2391 | return context._raise_error(InvalidOperation, |
| 2392 | 'quantize result has too many digits for current context') |
| 2393 | |
| 2394 | # raise appropriate flags |
| 2395 | if ans._exp > self._exp: |
| 2396 | context._raise_error(Rounded) |
| 2397 | if ans != self: |
| 2398 | context._raise_error(Inexact) |
| 2399 | if ans and ans.adjusted() < context.Emin: |
| 2400 | context._raise_error(Subnormal) |
| 2401 | |
| 2402 | # call to fix takes care of any necessary folddown |
| 2403 | ans = ans._fix(context) |
| 2404 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2405 | |
| 2406 | def same_quantum(self, other): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2407 | """Return True if self and other have the same exponent; otherwise |
| 2408 | return False. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2409 | |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2410 | If either operand is a special value, the following rules are used: |
| 2411 | * return True if both operands are infinities |
| 2412 | * return True if both operands are NaNs |
| 2413 | * otherwise, return False. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2414 | """ |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2415 | other = _convert_other(other, raiseit=True) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2416 | if self._is_special or other._is_special: |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2417 | return (self.is_nan() and other.is_nan() or |
| 2418 | self.is_infinite() and other.is_infinite()) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2419 | return self._exp == other._exp |
| 2420 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2421 | def _rescale(self, exp, rounding): |
| 2422 | """Rescale self so that the exponent is exp, either by padding with zeros |
| 2423 | or by truncating digits, using the given rounding mode. |
| 2424 | |
| 2425 | Specials are returned without change. This operation is |
| 2426 | quiet: it raises no flags, and uses no information from the |
| 2427 | context. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2428 | |
| 2429 | exp = exp to scale to (an integer) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2430 | rounding = rounding mode |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2431 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2432 | if self._is_special: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2433 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2434 | if not self: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2435 | return _dec_from_triple(self._sign, '0', exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2436 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2437 | if self._exp >= exp: |
| 2438 | # pad answer with zeros if necessary |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2439 | return _dec_from_triple(self._sign, |
| 2440 | self._int + '0'*(self._exp - exp), exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2441 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2442 | # too many digits; round and lose data. If self.adjusted() < |
| 2443 | # exp-1, replace self by 10**(exp-1) before rounding |
| 2444 | digits = len(self._int) + self._exp - exp |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2445 | if digits < 0: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2446 | self = _dec_from_triple(self._sign, '1', exp-1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2447 | digits = 0 |
| 2448 | this_function = getattr(self, self._pick_rounding_function[rounding]) |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 2449 | changed = this_function(digits) |
| 2450 | coeff = self._int[:digits] or '0' |
| 2451 | if changed == 1: |
| 2452 | coeff = str(int(coeff)+1) |
| 2453 | return _dec_from_triple(self._sign, coeff, exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2454 | |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 2455 | def _round(self, places, rounding): |
| 2456 | """Round a nonzero, nonspecial Decimal to a fixed number of |
| 2457 | significant figures, using the given rounding mode. |
| 2458 | |
| 2459 | Infinities, NaNs and zeros are returned unaltered. |
| 2460 | |
| 2461 | This operation is quiet: it raises no flags, and uses no |
| 2462 | information from the context. |
| 2463 | |
| 2464 | """ |
| 2465 | if places <= 0: |
| 2466 | raise ValueError("argument should be at least 1 in _round") |
| 2467 | if self._is_special or not self: |
| 2468 | return Decimal(self) |
| 2469 | ans = self._rescale(self.adjusted()+1-places, rounding) |
| 2470 | # it can happen that the rescale alters the adjusted exponent; |
| 2471 | # for example when rounding 99.97 to 3 significant figures. |
| 2472 | # When this happens we end up with an extra 0 at the end of |
| 2473 | # the number; a second rescale fixes this. |
| 2474 | if ans.adjusted() != self.adjusted(): |
| 2475 | ans = ans._rescale(ans.adjusted()+1-places, rounding) |
| 2476 | return ans |
| 2477 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2478 | def to_integral_exact(self, rounding=None, context=None): |
| 2479 | """Rounds to a nearby integer. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2480 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2481 | If no rounding mode is specified, take the rounding mode from |
| 2482 | the context. This method raises the Rounded and Inexact flags |
| 2483 | when appropriate. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2484 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2485 | See also: to_integral_value, which does exactly the same as |
| 2486 | this method except that it doesn't raise Inexact or Rounded. |
| 2487 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2488 | if self._is_special: |
| 2489 | ans = self._check_nans(context=context) |
| 2490 | if ans: |
| 2491 | return ans |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2492 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2493 | if self._exp >= 0: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2494 | return Decimal(self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2495 | if not self: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2496 | return _dec_from_triple(self._sign, '0', 0) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2497 | if context is None: |
| 2498 | context = getcontext() |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2499 | if rounding is None: |
| 2500 | rounding = context.rounding |
| 2501 | context._raise_error(Rounded) |
| 2502 | ans = self._rescale(0, rounding) |
| 2503 | if ans != self: |
| 2504 | context._raise_error(Inexact) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2505 | return ans |
| 2506 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2507 | def to_integral_value(self, rounding=None, context=None): |
| 2508 | """Rounds to the nearest integer, without raising inexact, rounded.""" |
| 2509 | if context is None: |
| 2510 | context = getcontext() |
| 2511 | if rounding is None: |
| 2512 | rounding = context.rounding |
| 2513 | if self._is_special: |
| 2514 | ans = self._check_nans(context=context) |
| 2515 | if ans: |
| 2516 | return ans |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2517 | return Decimal(self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2518 | if self._exp >= 0: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2519 | return Decimal(self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2520 | else: |
| 2521 | return self._rescale(0, rounding) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2522 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2523 | # the method name changed, but we provide also the old one, for compatibility |
| 2524 | to_integral = to_integral_value |
| 2525 | |
| 2526 | def sqrt(self, context=None): |
| 2527 | """Return the square root of self.""" |
Mark Dickinson | 3b24ccb | 2008-03-25 14:33:23 +0000 | [diff] [blame] | 2528 | if context is None: |
| 2529 | context = getcontext() |
| 2530 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2531 | if self._is_special: |
| 2532 | ans = self._check_nans(context=context) |
| 2533 | if ans: |
| 2534 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2535 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2536 | if self._isinfinity() and self._sign == 0: |
| 2537 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2538 | |
| 2539 | if not self: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2540 | # exponent = self._exp // 2. sqrt(-0) = -0 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2541 | ans = _dec_from_triple(self._sign, '0', self._exp // 2) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2542 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2543 | |
| 2544 | if self._sign == 1: |
| 2545 | return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0') |
| 2546 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2547 | # At this point self represents a positive number. Let p be |
| 2548 | # the desired precision and express self in the form c*100**e |
| 2549 | # with c a positive real number and e an integer, c and e |
| 2550 | # being chosen so that 100**(p-1) <= c < 100**p. Then the |
| 2551 | # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1) |
| 2552 | # <= sqrt(c) < 10**p, so the closest representable Decimal at |
| 2553 | # precision p is n*10**e where n = round_half_even(sqrt(c)), |
| 2554 | # the closest integer to sqrt(c) with the even integer chosen |
| 2555 | # in the case of a tie. |
| 2556 | # |
| 2557 | # To ensure correct rounding in all cases, we use the |
| 2558 | # following trick: we compute the square root to an extra |
| 2559 | # place (precision p+1 instead of precision p), rounding down. |
| 2560 | # Then, if the result is inexact and its last digit is 0 or 5, |
| 2561 | # we increase the last digit to 1 or 6 respectively; if it's |
| 2562 | # exact we leave the last digit alone. Now the final round to |
| 2563 | # p places (or fewer in the case of underflow) will round |
| 2564 | # correctly and raise the appropriate flags. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2565 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2566 | # use an extra digit of precision |
| 2567 | prec = context.prec+1 |
| 2568 | |
| 2569 | # write argument in the form c*100**e where e = self._exp//2 |
| 2570 | # is the 'ideal' exponent, to be used if the square root is |
| 2571 | # exactly representable. l is the number of 'digits' of c in |
| 2572 | # base 100, so that 100**(l-1) <= c < 100**l. |
| 2573 | op = _WorkRep(self) |
| 2574 | e = op.exp >> 1 |
| 2575 | if op.exp & 1: |
| 2576 | c = op.int * 10 |
| 2577 | l = (len(self._int) >> 1) + 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2578 | else: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2579 | c = op.int |
| 2580 | l = len(self._int)+1 >> 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2581 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2582 | # rescale so that c has exactly prec base 100 'digits' |
| 2583 | shift = prec-l |
| 2584 | if shift >= 0: |
| 2585 | c *= 100**shift |
| 2586 | exact = True |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2587 | else: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2588 | c, remainder = divmod(c, 100**-shift) |
| 2589 | exact = not remainder |
| 2590 | e -= shift |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 2591 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2592 | # find n = floor(sqrt(c)) using Newton's method |
| 2593 | n = 10**prec |
| 2594 | while True: |
| 2595 | q = c//n |
| 2596 | if n <= q: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2597 | break |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2598 | else: |
| 2599 | n = n + q >> 1 |
| 2600 | exact = exact and n*n == c |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2601 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2602 | if exact: |
| 2603 | # result is exact; rescale to use ideal exponent e |
| 2604 | if shift >= 0: |
| 2605 | # assert n % 10**shift == 0 |
| 2606 | n //= 10**shift |
| 2607 | else: |
| 2608 | n *= 10**-shift |
| 2609 | e += shift |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2610 | else: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2611 | # result is not exact; fix last digit as described above |
| 2612 | if n % 5 == 0: |
| 2613 | n += 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2614 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2615 | ans = _dec_from_triple(0, str(n), e) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2616 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2617 | # round, and fit to current context |
| 2618 | context = context._shallow_copy() |
| 2619 | rounding = context._set_rounding(ROUND_HALF_EVEN) |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 2620 | ans = ans._fix(context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2621 | context.rounding = rounding |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2622 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2623 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2624 | |
| 2625 | def max(self, other, context=None): |
| 2626 | """Returns the larger value. |
| 2627 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2628 | Like max(self, other) except if one is not a number, returns |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2629 | NaN (and signals if one is sNaN). Also rounds. |
| 2630 | """ |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2631 | other = _convert_other(other, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2632 | |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2633 | if context is None: |
| 2634 | context = getcontext() |
| 2635 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2636 | if self._is_special or other._is_special: |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 2637 | # 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] | 2638 | # number is always returned |
| 2639 | sn = self._isnan() |
| 2640 | on = other._isnan() |
| 2641 | if sn or on: |
Facundo Batista | e29d435 | 2008-12-11 04:19:46 +0000 | [diff] [blame] | 2642 | if on == 1 and sn == 0: |
| 2643 | return self._fix(context) |
| 2644 | if sn == 1 and on == 0: |
| 2645 | return other._fix(context) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2646 | return self._check_nans(other, context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2647 | |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 2648 | c = self._cmp(other) |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2649 | if c == 0: |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 2650 | # If both operands are finite and equal in numerical value |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2651 | # then an ordering is applied: |
| 2652 | # |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 2653 | # If the signs differ then max returns the operand with the |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2654 | # positive sign and min returns the operand with the negative sign |
| 2655 | # |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 2656 | # 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] | 2657 | # the result. This is exactly the ordering used in compare_total. |
| 2658 | c = self.compare_total(other) |
| 2659 | |
| 2660 | if c == -1: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2661 | ans = other |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2662 | else: |
| 2663 | ans = self |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2664 | |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 2665 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2666 | |
| 2667 | def min(self, other, context=None): |
| 2668 | """Returns the smaller value. |
| 2669 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 2670 | Like min(self, other) except if one is not a number, returns |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2671 | NaN (and signals if one is sNaN). Also rounds. |
| 2672 | """ |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2673 | other = _convert_other(other, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2674 | |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2675 | if context is None: |
| 2676 | context = getcontext() |
| 2677 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2678 | if self._is_special or other._is_special: |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 2679 | # 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] | 2680 | # number is always returned |
| 2681 | sn = self._isnan() |
| 2682 | on = other._isnan() |
| 2683 | if sn or on: |
Facundo Batista | e29d435 | 2008-12-11 04:19:46 +0000 | [diff] [blame] | 2684 | if on == 1 and sn == 0: |
| 2685 | return self._fix(context) |
| 2686 | if sn == 1 and on == 0: |
| 2687 | return other._fix(context) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2688 | return self._check_nans(other, context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2689 | |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 2690 | c = self._cmp(other) |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2691 | if c == 0: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2692 | c = self.compare_total(other) |
| 2693 | |
| 2694 | if c == -1: |
| 2695 | ans = self |
| 2696 | else: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2697 | ans = other |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2698 | |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 2699 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2700 | |
| 2701 | def _isinteger(self): |
| 2702 | """Returns whether self is an integer""" |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2703 | if self._is_special: |
| 2704 | return False |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2705 | if self._exp >= 0: |
| 2706 | return True |
| 2707 | rest = self._int[self._exp:] |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2708 | return rest == '0'*len(rest) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2709 | |
| 2710 | def _iseven(self): |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2711 | """Returns True if self is even. Assumes self is an integer.""" |
| 2712 | if not self or self._exp > 0: |
| 2713 | return True |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2714 | return self._int[-1+self._exp] in '02468' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2715 | |
| 2716 | def adjusted(self): |
| 2717 | """Return the adjusted exponent of self""" |
| 2718 | try: |
| 2719 | return self._exp + len(self._int) - 1 |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 2720 | # If NaN or Infinity, self._exp is string |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2721 | except TypeError: |
| 2722 | return 0 |
| 2723 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2724 | def canonical(self, context=None): |
| 2725 | """Returns the same Decimal object. |
| 2726 | |
| 2727 | As we do not have different encodings for the same number, the |
| 2728 | received object already is in its canonical form. |
| 2729 | """ |
| 2730 | return self |
| 2731 | |
| 2732 | def compare_signal(self, other, context=None): |
| 2733 | """Compares self to the other operand numerically. |
| 2734 | |
| 2735 | It's pretty much like compare(), but all NaNs signal, with signaling |
| 2736 | NaNs taking precedence over quiet NaNs. |
| 2737 | """ |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 2738 | other = _convert_other(other, raiseit = True) |
| 2739 | ans = self._compare_check_nans(other, context) |
| 2740 | if ans: |
| 2741 | return ans |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2742 | return self.compare(other, context=context) |
| 2743 | |
| 2744 | def compare_total(self, other): |
| 2745 | """Compares self to other using the abstract representations. |
| 2746 | |
| 2747 | This is not like the standard compare, which use their numerical |
| 2748 | value. Note that a total ordering is defined for all possible abstract |
| 2749 | representations. |
| 2750 | """ |
Mark Dickinson | 0c67312 | 2009-10-29 12:04:00 +0000 | [diff] [blame] | 2751 | other = _convert_other(other, raiseit=True) |
| 2752 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2753 | # if one is negative and the other is positive, it's easy |
| 2754 | if self._sign and not other._sign: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 2755 | return _NegativeOne |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2756 | if not self._sign and other._sign: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 2757 | return _One |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2758 | sign = self._sign |
| 2759 | |
| 2760 | # let's handle both NaN types |
| 2761 | self_nan = self._isnan() |
| 2762 | other_nan = other._isnan() |
| 2763 | if self_nan or other_nan: |
| 2764 | if self_nan == other_nan: |
Mark Dickinson | 7a7739d | 2009-08-28 13:25:02 +0000 | [diff] [blame] | 2765 | # compare payloads as though they're integers |
| 2766 | self_key = len(self._int), self._int |
| 2767 | other_key = len(other._int), other._int |
| 2768 | if self_key < other_key: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2769 | if sign: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 2770 | return _One |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2771 | else: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 2772 | return _NegativeOne |
Mark Dickinson | 7a7739d | 2009-08-28 13:25:02 +0000 | [diff] [blame] | 2773 | if self_key > other_key: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2774 | if sign: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 2775 | return _NegativeOne |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2776 | else: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 2777 | return _One |
| 2778 | return _Zero |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2779 | |
| 2780 | if sign: |
| 2781 | if self_nan == 1: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 2782 | return _NegativeOne |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2783 | if other_nan == 1: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 2784 | return _One |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2785 | if self_nan == 2: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 2786 | return _NegativeOne |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2787 | if other_nan == 2: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 2788 | return _One |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2789 | else: |
| 2790 | if self_nan == 1: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 2791 | return _One |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2792 | if other_nan == 1: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 2793 | return _NegativeOne |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2794 | if self_nan == 2: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 2795 | return _One |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2796 | if other_nan == 2: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 2797 | return _NegativeOne |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2798 | |
| 2799 | if self < other: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 2800 | return _NegativeOne |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2801 | if self > other: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 2802 | return _One |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2803 | |
| 2804 | if self._exp < other._exp: |
| 2805 | if sign: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 2806 | return _One |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2807 | else: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 2808 | return _NegativeOne |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2809 | if self._exp > other._exp: |
| 2810 | if sign: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 2811 | return _NegativeOne |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2812 | else: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 2813 | return _One |
| 2814 | return _Zero |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2815 | |
| 2816 | |
| 2817 | def compare_total_mag(self, other): |
| 2818 | """Compares self to other using abstract repr., ignoring sign. |
| 2819 | |
| 2820 | Like compare_total, but with operand's sign ignored and assumed to be 0. |
| 2821 | """ |
Mark Dickinson | 0c67312 | 2009-10-29 12:04:00 +0000 | [diff] [blame] | 2822 | other = _convert_other(other, raiseit=True) |
| 2823 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2824 | s = self.copy_abs() |
| 2825 | o = other.copy_abs() |
| 2826 | return s.compare_total(o) |
| 2827 | |
| 2828 | def copy_abs(self): |
| 2829 | """Returns a copy with the sign set to 0. """ |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2830 | return _dec_from_triple(0, self._int, self._exp, self._is_special) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2831 | |
| 2832 | def copy_negate(self): |
| 2833 | """Returns a copy with the sign inverted.""" |
| 2834 | if self._sign: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2835 | return _dec_from_triple(0, self._int, self._exp, self._is_special) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2836 | else: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2837 | return _dec_from_triple(1, self._int, self._exp, self._is_special) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2838 | |
| 2839 | def copy_sign(self, other): |
| 2840 | """Returns self with the sign of other.""" |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 2841 | other = _convert_other(other, raiseit=True) |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2842 | return _dec_from_triple(other._sign, self._int, |
| 2843 | self._exp, self._is_special) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2844 | |
| 2845 | def exp(self, context=None): |
| 2846 | """Returns e ** self.""" |
| 2847 | |
| 2848 | if context is None: |
| 2849 | context = getcontext() |
| 2850 | |
| 2851 | # exp(NaN) = NaN |
| 2852 | ans = self._check_nans(context=context) |
| 2853 | if ans: |
| 2854 | return ans |
| 2855 | |
| 2856 | # exp(-Infinity) = 0 |
| 2857 | if self._isinfinity() == -1: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 2858 | return _Zero |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2859 | |
| 2860 | # exp(0) = 1 |
| 2861 | if not self: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 2862 | return _One |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2863 | |
| 2864 | # exp(Infinity) = Infinity |
| 2865 | if self._isinfinity() == 1: |
| 2866 | return Decimal(self) |
| 2867 | |
| 2868 | # the result is now guaranteed to be inexact (the true |
| 2869 | # mathematical result is transcendental). There's no need to |
| 2870 | # raise Rounded and Inexact here---they'll always be raised as |
| 2871 | # a result of the call to _fix. |
| 2872 | p = context.prec |
| 2873 | adj = self.adjusted() |
| 2874 | |
| 2875 | # we only need to do any computation for quite a small range |
| 2876 | # of adjusted exponents---for example, -29 <= adj <= 10 for |
| 2877 | # the default context. For smaller exponent the result is |
| 2878 | # indistinguishable from 1 at the given precision, while for |
| 2879 | # larger exponent the result either overflows or underflows. |
| 2880 | if self._sign == 0 and adj > len(str((context.Emax+1)*3)): |
| 2881 | # overflow |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2882 | ans = _dec_from_triple(0, '1', context.Emax+1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2883 | elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)): |
| 2884 | # underflow to 0 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2885 | ans = _dec_from_triple(0, '1', context.Etiny()-1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2886 | elif self._sign == 0 and adj < -p: |
| 2887 | # p+1 digits; final round will raise correct flags |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2888 | ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2889 | elif self._sign == 1 and adj < -p-1: |
| 2890 | # p+1 digits; final round will raise correct flags |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2891 | ans = _dec_from_triple(0, '9'*(p+1), -p-1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2892 | # general case |
| 2893 | else: |
| 2894 | op = _WorkRep(self) |
| 2895 | c, e = op.int, op.exp |
| 2896 | if op.sign == 1: |
| 2897 | c = -c |
| 2898 | |
| 2899 | # compute correctly rounded result: increase precision by |
| 2900 | # 3 digits at a time until we get an unambiguously |
| 2901 | # roundable result |
| 2902 | extra = 3 |
| 2903 | while True: |
| 2904 | coeff, exp = _dexp(c, e, p+extra) |
| 2905 | if coeff % (5*10**(len(str(coeff))-p-1)): |
| 2906 | break |
| 2907 | extra += 3 |
| 2908 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2909 | ans = _dec_from_triple(0, str(coeff), exp) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2910 | |
| 2911 | # at this stage, ans should round correctly with *any* |
| 2912 | # rounding mode, not just with ROUND_HALF_EVEN |
| 2913 | context = context._shallow_copy() |
| 2914 | rounding = context._set_rounding(ROUND_HALF_EVEN) |
| 2915 | ans = ans._fix(context) |
| 2916 | context.rounding = rounding |
| 2917 | |
| 2918 | return ans |
| 2919 | |
| 2920 | def is_canonical(self): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2921 | """Return True if self is canonical; otherwise return False. |
| 2922 | |
| 2923 | Currently, the encoding of a Decimal instance is always |
| 2924 | canonical, so this method returns True for any Decimal. |
| 2925 | """ |
| 2926 | return True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2927 | |
| 2928 | def is_finite(self): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2929 | """Return True if self is finite; otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2930 | |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2931 | A Decimal instance is considered finite if it is neither |
| 2932 | infinite nor a NaN. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2933 | """ |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2934 | return not self._is_special |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2935 | |
| 2936 | def is_infinite(self): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2937 | """Return True if self is infinite; otherwise return False.""" |
| 2938 | return self._exp == 'F' |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2939 | |
| 2940 | def is_nan(self): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2941 | """Return True if self is a qNaN or sNaN; otherwise return False.""" |
| 2942 | return self._exp in ('n', 'N') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2943 | |
| 2944 | def is_normal(self, context=None): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2945 | """Return True if self is a normal number; otherwise return False.""" |
| 2946 | if self._is_special or not self: |
| 2947 | return False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2948 | if context is None: |
| 2949 | context = getcontext() |
Mark Dickinson | a7a52ab | 2009-10-20 13:33:03 +0000 | [diff] [blame] | 2950 | return context.Emin <= self.adjusted() |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2951 | |
| 2952 | def is_qnan(self): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2953 | """Return True if self is a quiet NaN; otherwise return False.""" |
| 2954 | return self._exp == 'n' |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2955 | |
| 2956 | def is_signed(self): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2957 | """Return True if self is negative; otherwise return False.""" |
| 2958 | return self._sign == 1 |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2959 | |
| 2960 | def is_snan(self): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2961 | """Return True if self is a signaling NaN; otherwise return False.""" |
| 2962 | return self._exp == 'N' |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2963 | |
| 2964 | def is_subnormal(self, context=None): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2965 | """Return True if self is subnormal; otherwise return False.""" |
| 2966 | if self._is_special or not self: |
| 2967 | return False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2968 | if context is None: |
| 2969 | context = getcontext() |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2970 | return self.adjusted() < context.Emin |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2971 | |
| 2972 | def is_zero(self): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2973 | """Return True if self is a zero; otherwise return False.""" |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2974 | return not self._is_special and self._int == '0' |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2975 | |
| 2976 | def _ln_exp_bound(self): |
| 2977 | """Compute a lower bound for the adjusted exponent of self.ln(). |
| 2978 | In other words, compute r such that self.ln() >= 10**r. Assumes |
| 2979 | that self is finite and positive and that self != 1. |
| 2980 | """ |
| 2981 | |
| 2982 | # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1 |
| 2983 | adj = self._exp + len(self._int) - 1 |
| 2984 | if adj >= 1: |
| 2985 | # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10) |
| 2986 | return len(str(adj*23//10)) - 1 |
| 2987 | if adj <= -2: |
| 2988 | # argument <= 0.1 |
| 2989 | return len(str((-1-adj)*23//10)) - 1 |
| 2990 | op = _WorkRep(self) |
| 2991 | c, e = op.int, op.exp |
| 2992 | if adj == 0: |
| 2993 | # 1 < self < 10 |
| 2994 | num = str(c-10**-e) |
| 2995 | den = str(c) |
| 2996 | return len(num) - len(den) - (num < den) |
| 2997 | # adj == -1, 0.1 <= self < 1 |
| 2998 | return e + len(str(10**-e - c)) - 1 |
| 2999 | |
| 3000 | |
| 3001 | def ln(self, context=None): |
| 3002 | """Returns the natural (base e) logarithm of self.""" |
| 3003 | |
| 3004 | if context is None: |
| 3005 | context = getcontext() |
| 3006 | |
| 3007 | # ln(NaN) = NaN |
| 3008 | ans = self._check_nans(context=context) |
| 3009 | if ans: |
| 3010 | return ans |
| 3011 | |
| 3012 | # ln(0.0) == -Infinity |
| 3013 | if not self: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 3014 | return _NegativeInfinity |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3015 | |
| 3016 | # ln(Infinity) = Infinity |
| 3017 | if self._isinfinity() == 1: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 3018 | return _Infinity |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3019 | |
| 3020 | # ln(1.0) == 0.0 |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 3021 | if self == _One: |
| 3022 | return _Zero |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3023 | |
| 3024 | # ln(negative) raises InvalidOperation |
| 3025 | if self._sign == 1: |
| 3026 | return context._raise_error(InvalidOperation, |
| 3027 | 'ln of a negative value') |
| 3028 | |
| 3029 | # result is irrational, so necessarily inexact |
| 3030 | op = _WorkRep(self) |
| 3031 | c, e = op.int, op.exp |
| 3032 | p = context.prec |
| 3033 | |
| 3034 | # correctly rounded result: repeatedly increase precision by 3 |
| 3035 | # until we get an unambiguously roundable result |
| 3036 | places = p - self._ln_exp_bound() + 2 # at least p+3 places |
| 3037 | while True: |
| 3038 | coeff = _dlog(c, e, places) |
| 3039 | # assert len(str(abs(coeff)))-p >= 1 |
| 3040 | if coeff % (5*10**(len(str(abs(coeff)))-p-1)): |
| 3041 | break |
| 3042 | places += 3 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3043 | ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3044 | |
| 3045 | context = context._shallow_copy() |
| 3046 | rounding = context._set_rounding(ROUND_HALF_EVEN) |
| 3047 | ans = ans._fix(context) |
| 3048 | context.rounding = rounding |
| 3049 | return ans |
| 3050 | |
| 3051 | def _log10_exp_bound(self): |
| 3052 | """Compute a lower bound for the adjusted exponent of self.log10(). |
| 3053 | In other words, find r such that self.log10() >= 10**r. |
| 3054 | Assumes that self is finite and positive and that self != 1. |
| 3055 | """ |
| 3056 | |
| 3057 | # For x >= 10 or x < 0.1 we only need a bound on the integer |
| 3058 | # part of log10(self), and this comes directly from the |
| 3059 | # exponent of x. For 0.1 <= x <= 10 we use the inequalities |
| 3060 | # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| > |
| 3061 | # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0 |
| 3062 | |
| 3063 | adj = self._exp + len(self._int) - 1 |
| 3064 | if adj >= 1: |
| 3065 | # self >= 10 |
| 3066 | return len(str(adj))-1 |
| 3067 | if adj <= -2: |
| 3068 | # self < 0.1 |
| 3069 | return len(str(-1-adj))-1 |
| 3070 | op = _WorkRep(self) |
| 3071 | c, e = op.int, op.exp |
| 3072 | if adj == 0: |
| 3073 | # 1 < self < 10 |
| 3074 | num = str(c-10**-e) |
| 3075 | den = str(231*c) |
| 3076 | return len(num) - len(den) - (num < den) + 2 |
| 3077 | # adj == -1, 0.1 <= self < 1 |
| 3078 | num = str(10**-e-c) |
| 3079 | return len(num) + e - (num < "231") - 1 |
| 3080 | |
| 3081 | def log10(self, context=None): |
| 3082 | """Returns the base 10 logarithm of self.""" |
| 3083 | |
| 3084 | if context is None: |
| 3085 | context = getcontext() |
| 3086 | |
| 3087 | # log10(NaN) = NaN |
| 3088 | ans = self._check_nans(context=context) |
| 3089 | if ans: |
| 3090 | return ans |
| 3091 | |
| 3092 | # log10(0.0) == -Infinity |
| 3093 | if not self: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 3094 | return _NegativeInfinity |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3095 | |
| 3096 | # log10(Infinity) = Infinity |
| 3097 | if self._isinfinity() == 1: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 3098 | return _Infinity |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3099 | |
| 3100 | # log10(negative or -Infinity) raises InvalidOperation |
| 3101 | if self._sign == 1: |
| 3102 | return context._raise_error(InvalidOperation, |
| 3103 | 'log10 of a negative value') |
| 3104 | |
| 3105 | # log10(10**n) = n |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3106 | 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] | 3107 | # answer may need rounding |
| 3108 | ans = Decimal(self._exp + len(self._int) - 1) |
| 3109 | else: |
| 3110 | # result is irrational, so necessarily inexact |
| 3111 | op = _WorkRep(self) |
| 3112 | c, e = op.int, op.exp |
| 3113 | p = context.prec |
| 3114 | |
| 3115 | # correctly rounded result: repeatedly increase precision |
| 3116 | # until result is unambiguously roundable |
| 3117 | places = p-self._log10_exp_bound()+2 |
| 3118 | while True: |
| 3119 | coeff = _dlog10(c, e, places) |
| 3120 | # assert len(str(abs(coeff)))-p >= 1 |
| 3121 | if coeff % (5*10**(len(str(abs(coeff)))-p-1)): |
| 3122 | break |
| 3123 | places += 3 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3124 | ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3125 | |
| 3126 | context = context._shallow_copy() |
| 3127 | rounding = context._set_rounding(ROUND_HALF_EVEN) |
| 3128 | ans = ans._fix(context) |
| 3129 | context.rounding = rounding |
| 3130 | return ans |
| 3131 | |
| 3132 | def logb(self, context=None): |
| 3133 | """ Returns the exponent of the magnitude of self's MSD. |
| 3134 | |
| 3135 | The result is the integer which is the exponent of the magnitude |
| 3136 | of the most significant digit of self (as though it were truncated |
| 3137 | to a single digit while maintaining the value of that digit and |
| 3138 | without limiting the resulting exponent). |
| 3139 | """ |
| 3140 | # logb(NaN) = NaN |
| 3141 | ans = self._check_nans(context=context) |
| 3142 | if ans: |
| 3143 | return ans |
| 3144 | |
| 3145 | if context is None: |
| 3146 | context = getcontext() |
| 3147 | |
| 3148 | # logb(+/-Inf) = +Inf |
| 3149 | if self._isinfinity(): |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 3150 | return _Infinity |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3151 | |
| 3152 | # logb(0) = -Inf, DivisionByZero |
| 3153 | if not self: |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 3154 | return context._raise_error(DivisionByZero, 'logb(0)', 1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3155 | |
| 3156 | # otherwise, simply return the adjusted exponent of self, as a |
| 3157 | # Decimal. Note that no attempt is made to fit the result |
| 3158 | # into the current context. |
Mark Dickinson | 15ae41c | 2009-10-07 19:22:05 +0000 | [diff] [blame] | 3159 | ans = Decimal(self.adjusted()) |
| 3160 | return ans._fix(context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3161 | |
| 3162 | def _islogical(self): |
| 3163 | """Return True if self is a logical operand. |
| 3164 | |
Andrew M. Kuchling | c8acc88 | 2008-01-16 00:32:03 +0000 | [diff] [blame] | 3165 | 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] | 3166 | an exponent of 0, and a coefficient whose digits must all be |
| 3167 | either 0 or 1. |
| 3168 | """ |
| 3169 | if self._sign != 0 or self._exp != 0: |
| 3170 | return False |
| 3171 | for dig in self._int: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3172 | if dig not in '01': |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3173 | return False |
| 3174 | return True |
| 3175 | |
| 3176 | def _fill_logical(self, context, opa, opb): |
| 3177 | dif = context.prec - len(opa) |
| 3178 | if dif > 0: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3179 | opa = '0'*dif + opa |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3180 | elif dif < 0: |
| 3181 | opa = opa[-context.prec:] |
| 3182 | dif = context.prec - len(opb) |
| 3183 | if dif > 0: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3184 | opb = '0'*dif + opb |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3185 | elif dif < 0: |
| 3186 | opb = opb[-context.prec:] |
| 3187 | return opa, opb |
| 3188 | |
| 3189 | def logical_and(self, other, context=None): |
| 3190 | """Applies an 'and' operation between self and other's digits.""" |
| 3191 | if context is None: |
| 3192 | context = getcontext() |
Mark Dickinson | 0c67312 | 2009-10-29 12:04:00 +0000 | [diff] [blame] | 3193 | |
| 3194 | other = _convert_other(other, raiseit=True) |
| 3195 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3196 | if not self._islogical() or not other._islogical(): |
| 3197 | return context._raise_error(InvalidOperation) |
| 3198 | |
| 3199 | # fill to context.prec |
| 3200 | (opa, opb) = self._fill_logical(context, self._int, other._int) |
| 3201 | |
| 3202 | # make the operation, and clean starting zeroes |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3203 | result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)]) |
| 3204 | return _dec_from_triple(0, result.lstrip('0') or '0', 0) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3205 | |
| 3206 | def logical_invert(self, context=None): |
| 3207 | """Invert all its digits.""" |
| 3208 | if context is None: |
| 3209 | context = getcontext() |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3210 | return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0), |
| 3211 | context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3212 | |
| 3213 | def logical_or(self, other, context=None): |
| 3214 | """Applies an 'or' operation between self and other's digits.""" |
| 3215 | if context is None: |
| 3216 | context = getcontext() |
Mark Dickinson | 0c67312 | 2009-10-29 12:04:00 +0000 | [diff] [blame] | 3217 | |
| 3218 | other = _convert_other(other, raiseit=True) |
| 3219 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3220 | if not self._islogical() or not other._islogical(): |
| 3221 | return context._raise_error(InvalidOperation) |
| 3222 | |
| 3223 | # fill to context.prec |
| 3224 | (opa, opb) = self._fill_logical(context, self._int, other._int) |
| 3225 | |
| 3226 | # make the operation, and clean starting zeroes |
Mark Dickinson | 65808ff | 2009-01-04 21:22:02 +0000 | [diff] [blame] | 3227 | result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)]) |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3228 | return _dec_from_triple(0, result.lstrip('0') or '0', 0) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3229 | |
| 3230 | def logical_xor(self, other, context=None): |
| 3231 | """Applies an 'xor' operation between self and other's digits.""" |
| 3232 | if context is None: |
| 3233 | context = getcontext() |
Mark Dickinson | 0c67312 | 2009-10-29 12:04:00 +0000 | [diff] [blame] | 3234 | |
| 3235 | other = _convert_other(other, raiseit=True) |
| 3236 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3237 | if not self._islogical() or not other._islogical(): |
| 3238 | return context._raise_error(InvalidOperation) |
| 3239 | |
| 3240 | # fill to context.prec |
| 3241 | (opa, opb) = self._fill_logical(context, self._int, other._int) |
| 3242 | |
| 3243 | # make the operation, and clean starting zeroes |
Mark Dickinson | 65808ff | 2009-01-04 21:22:02 +0000 | [diff] [blame] | 3244 | result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)]) |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3245 | return _dec_from_triple(0, result.lstrip('0') or '0', 0) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3246 | |
| 3247 | def max_mag(self, other, context=None): |
| 3248 | """Compares the values numerically with their sign ignored.""" |
| 3249 | other = _convert_other(other, raiseit=True) |
| 3250 | |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 3251 | if context is None: |
| 3252 | context = getcontext() |
| 3253 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3254 | if self._is_special or other._is_special: |
| 3255 | # If one operand is a quiet NaN and the other is number, then the |
| 3256 | # number is always returned |
| 3257 | sn = self._isnan() |
| 3258 | on = other._isnan() |
| 3259 | if sn or on: |
Facundo Batista | e29d435 | 2008-12-11 04:19:46 +0000 | [diff] [blame] | 3260 | if on == 1 and sn == 0: |
| 3261 | return self._fix(context) |
| 3262 | if sn == 1 and on == 0: |
| 3263 | return other._fix(context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3264 | return self._check_nans(other, context) |
| 3265 | |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 3266 | c = self.copy_abs()._cmp(other.copy_abs()) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3267 | if c == 0: |
| 3268 | c = self.compare_total(other) |
| 3269 | |
| 3270 | if c == -1: |
| 3271 | ans = other |
| 3272 | else: |
| 3273 | ans = self |
| 3274 | |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 3275 | return ans._fix(context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3276 | |
| 3277 | def min_mag(self, other, context=None): |
| 3278 | """Compares the values numerically with their sign ignored.""" |
| 3279 | other = _convert_other(other, raiseit=True) |
| 3280 | |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 3281 | if context is None: |
| 3282 | context = getcontext() |
| 3283 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3284 | if self._is_special or other._is_special: |
| 3285 | # If one operand is a quiet NaN and the other is number, then the |
| 3286 | # number is always returned |
| 3287 | sn = self._isnan() |
| 3288 | on = other._isnan() |
| 3289 | if sn or on: |
Facundo Batista | e29d435 | 2008-12-11 04:19:46 +0000 | [diff] [blame] | 3290 | if on == 1 and sn == 0: |
| 3291 | return self._fix(context) |
| 3292 | if sn == 1 and on == 0: |
| 3293 | return other._fix(context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3294 | return self._check_nans(other, context) |
| 3295 | |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 3296 | c = self.copy_abs()._cmp(other.copy_abs()) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3297 | if c == 0: |
| 3298 | c = self.compare_total(other) |
| 3299 | |
| 3300 | if c == -1: |
| 3301 | ans = self |
| 3302 | else: |
| 3303 | ans = other |
| 3304 | |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 3305 | return ans._fix(context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3306 | |
| 3307 | def next_minus(self, context=None): |
| 3308 | """Returns the largest representable number smaller than itself.""" |
| 3309 | if context is None: |
| 3310 | context = getcontext() |
| 3311 | |
| 3312 | ans = self._check_nans(context=context) |
| 3313 | if ans: |
| 3314 | return ans |
| 3315 | |
| 3316 | if self._isinfinity() == -1: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 3317 | return _NegativeInfinity |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3318 | if self._isinfinity() == 1: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3319 | return _dec_from_triple(0, '9'*context.prec, context.Etop()) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3320 | |
| 3321 | context = context.copy() |
| 3322 | context._set_rounding(ROUND_FLOOR) |
| 3323 | context._ignore_all_flags() |
| 3324 | new_self = self._fix(context) |
| 3325 | if new_self != self: |
| 3326 | return new_self |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3327 | return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1), |
| 3328 | context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3329 | |
| 3330 | def next_plus(self, context=None): |
| 3331 | """Returns the smallest representable number larger than itself.""" |
| 3332 | if context is None: |
| 3333 | context = getcontext() |
| 3334 | |
| 3335 | ans = self._check_nans(context=context) |
| 3336 | if ans: |
| 3337 | return ans |
| 3338 | |
| 3339 | if self._isinfinity() == 1: |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 3340 | return _Infinity |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3341 | if self._isinfinity() == -1: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3342 | return _dec_from_triple(1, '9'*context.prec, context.Etop()) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3343 | |
| 3344 | context = context.copy() |
| 3345 | context._set_rounding(ROUND_CEILING) |
| 3346 | context._ignore_all_flags() |
| 3347 | new_self = self._fix(context) |
| 3348 | if new_self != self: |
| 3349 | return new_self |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3350 | return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1), |
| 3351 | context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3352 | |
| 3353 | def next_toward(self, other, context=None): |
| 3354 | """Returns the number closest to self, in the direction towards other. |
| 3355 | |
| 3356 | The result is the closest representable number to self |
| 3357 | (excluding self) that is in the direction towards other, |
| 3358 | unless both have the same value. If the two operands are |
| 3359 | numerically equal, then the result is a copy of self with the |
| 3360 | sign set to be the same as the sign of other. |
| 3361 | """ |
| 3362 | other = _convert_other(other, raiseit=True) |
| 3363 | |
| 3364 | if context is None: |
| 3365 | context = getcontext() |
| 3366 | |
| 3367 | ans = self._check_nans(other, context) |
| 3368 | if ans: |
| 3369 | return ans |
| 3370 | |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 3371 | comparison = self._cmp(other) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3372 | if comparison == 0: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3373 | return self.copy_sign(other) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3374 | |
| 3375 | if comparison == -1: |
| 3376 | ans = self.next_plus(context) |
| 3377 | else: # comparison == 1 |
| 3378 | ans = self.next_minus(context) |
| 3379 | |
| 3380 | # decide which flags to raise using value of ans |
| 3381 | if ans._isinfinity(): |
| 3382 | context._raise_error(Overflow, |
| 3383 | 'Infinite result from next_toward', |
| 3384 | ans._sign) |
| 3385 | context._raise_error(Rounded) |
| 3386 | context._raise_error(Inexact) |
| 3387 | elif ans.adjusted() < context.Emin: |
| 3388 | context._raise_error(Underflow) |
| 3389 | context._raise_error(Subnormal) |
| 3390 | context._raise_error(Rounded) |
| 3391 | context._raise_error(Inexact) |
| 3392 | # if precision == 1 then we don't raise Clamped for a |
| 3393 | # result 0E-Etiny. |
| 3394 | if not ans: |
| 3395 | context._raise_error(Clamped) |
| 3396 | |
| 3397 | return ans |
| 3398 | |
| 3399 | def number_class(self, context=None): |
| 3400 | """Returns an indication of the class of self. |
| 3401 | |
| 3402 | The class is one of the following strings: |
Facundo Batista | 0f5e7bf | 2007-12-19 12:53:01 +0000 | [diff] [blame] | 3403 | sNaN |
| 3404 | NaN |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3405 | -Infinity |
| 3406 | -Normal |
| 3407 | -Subnormal |
| 3408 | -Zero |
| 3409 | +Zero |
| 3410 | +Subnormal |
| 3411 | +Normal |
| 3412 | +Infinity |
| 3413 | """ |
| 3414 | if self.is_snan(): |
| 3415 | return "sNaN" |
| 3416 | if self.is_qnan(): |
| 3417 | return "NaN" |
| 3418 | inf = self._isinfinity() |
| 3419 | if inf == 1: |
| 3420 | return "+Infinity" |
| 3421 | if inf == -1: |
| 3422 | return "-Infinity" |
| 3423 | if self.is_zero(): |
| 3424 | if self._sign: |
| 3425 | return "-Zero" |
| 3426 | else: |
| 3427 | return "+Zero" |
| 3428 | if context is None: |
| 3429 | context = getcontext() |
| 3430 | if self.is_subnormal(context=context): |
| 3431 | if self._sign: |
| 3432 | return "-Subnormal" |
| 3433 | else: |
| 3434 | return "+Subnormal" |
| 3435 | # just a normal, regular, boring number, :) |
| 3436 | if self._sign: |
| 3437 | return "-Normal" |
| 3438 | else: |
| 3439 | return "+Normal" |
| 3440 | |
| 3441 | def radix(self): |
| 3442 | """Just returns 10, as this is Decimal, :)""" |
| 3443 | return Decimal(10) |
| 3444 | |
| 3445 | def rotate(self, other, context=None): |
| 3446 | """Returns a rotated copy of self, value-of-other times.""" |
| 3447 | if context is None: |
| 3448 | context = getcontext() |
| 3449 | |
Mark Dickinson | 0c67312 | 2009-10-29 12:04:00 +0000 | [diff] [blame] | 3450 | other = _convert_other(other, raiseit=True) |
| 3451 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3452 | ans = self._check_nans(other, context) |
| 3453 | if ans: |
| 3454 | return ans |
| 3455 | |
| 3456 | if other._exp != 0: |
| 3457 | return context._raise_error(InvalidOperation) |
| 3458 | if not (-context.prec <= int(other) <= context.prec): |
| 3459 | return context._raise_error(InvalidOperation) |
| 3460 | |
| 3461 | if self._isinfinity(): |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 3462 | return Decimal(self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3463 | |
| 3464 | # get values, pad if necessary |
| 3465 | torot = int(other) |
| 3466 | rotdig = self._int |
| 3467 | topad = context.prec - len(rotdig) |
Mark Dickinson | 6f39001 | 2009-10-29 12:11:18 +0000 | [diff] [blame] | 3468 | if topad > 0: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3469 | rotdig = '0'*topad + rotdig |
Mark Dickinson | 6f39001 | 2009-10-29 12:11:18 +0000 | [diff] [blame] | 3470 | elif topad < 0: |
| 3471 | rotdig = rotdig[-topad:] |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3472 | |
| 3473 | # let's rotate! |
| 3474 | rotated = rotdig[torot:] + rotdig[:torot] |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3475 | return _dec_from_triple(self._sign, |
| 3476 | rotated.lstrip('0') or '0', self._exp) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3477 | |
Mark Dickinson | 0c67312 | 2009-10-29 12:04:00 +0000 | [diff] [blame] | 3478 | def scaleb(self, other, context=None): |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3479 | """Returns self operand after adding the second value to its exp.""" |
| 3480 | if context is None: |
| 3481 | context = getcontext() |
| 3482 | |
Mark Dickinson | 0c67312 | 2009-10-29 12:04:00 +0000 | [diff] [blame] | 3483 | other = _convert_other(other, raiseit=True) |
| 3484 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3485 | ans = self._check_nans(other, context) |
| 3486 | if ans: |
| 3487 | return ans |
| 3488 | |
| 3489 | if other._exp != 0: |
| 3490 | return context._raise_error(InvalidOperation) |
| 3491 | liminf = -2 * (context.Emax + context.prec) |
| 3492 | limsup = 2 * (context.Emax + context.prec) |
| 3493 | if not (liminf <= int(other) <= limsup): |
| 3494 | return context._raise_error(InvalidOperation) |
| 3495 | |
| 3496 | if self._isinfinity(): |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 3497 | return Decimal(self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3498 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3499 | d = _dec_from_triple(self._sign, self._int, self._exp + int(other)) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3500 | d = d._fix(context) |
| 3501 | return d |
| 3502 | |
| 3503 | def shift(self, other, context=None): |
| 3504 | """Returns a shifted copy of self, value-of-other times.""" |
| 3505 | if context is None: |
| 3506 | context = getcontext() |
| 3507 | |
Mark Dickinson | 0c67312 | 2009-10-29 12:04:00 +0000 | [diff] [blame] | 3508 | other = _convert_other(other, raiseit=True) |
| 3509 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3510 | ans = self._check_nans(other, context) |
| 3511 | if ans: |
| 3512 | return ans |
| 3513 | |
| 3514 | if other._exp != 0: |
| 3515 | return context._raise_error(InvalidOperation) |
| 3516 | if not (-context.prec <= int(other) <= context.prec): |
| 3517 | return context._raise_error(InvalidOperation) |
| 3518 | |
| 3519 | if self._isinfinity(): |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 3520 | return Decimal(self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3521 | |
| 3522 | # get values, pad if necessary |
| 3523 | torot = int(other) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3524 | rotdig = self._int |
| 3525 | topad = context.prec - len(rotdig) |
Mark Dickinson | 6f39001 | 2009-10-29 12:11:18 +0000 | [diff] [blame] | 3526 | if topad > 0: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3527 | rotdig = '0'*topad + rotdig |
Mark Dickinson | 6f39001 | 2009-10-29 12:11:18 +0000 | [diff] [blame] | 3528 | elif topad < 0: |
| 3529 | rotdig = rotdig[-topad:] |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3530 | |
| 3531 | # let's shift! |
| 3532 | if torot < 0: |
Mark Dickinson | 6f39001 | 2009-10-29 12:11:18 +0000 | [diff] [blame] | 3533 | shifted = rotdig[:torot] |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3534 | else: |
Mark Dickinson | 6f39001 | 2009-10-29 12:11:18 +0000 | [diff] [blame] | 3535 | shifted = rotdig + '0'*torot |
| 3536 | shifted = shifted[-context.prec:] |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3537 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3538 | return _dec_from_triple(self._sign, |
Mark Dickinson | 6f39001 | 2009-10-29 12:11:18 +0000 | [diff] [blame] | 3539 | shifted.lstrip('0') or '0', self._exp) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3540 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3541 | # Support for pickling, copy, and deepcopy |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3542 | def __reduce__(self): |
| 3543 | return (self.__class__, (str(self),)) |
| 3544 | |
| 3545 | def __copy__(self): |
Benjamin Peterson | 28e369a | 2010-01-25 03:58:21 +0000 | [diff] [blame] | 3546 | if type(self) is Decimal: |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 3547 | return self # I'm immutable; therefore I am my own clone |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3548 | return self.__class__(str(self)) |
| 3549 | |
| 3550 | def __deepcopy__(self, memo): |
Benjamin Peterson | 28e369a | 2010-01-25 03:58:21 +0000 | [diff] [blame] | 3551 | if type(self) is Decimal: |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 3552 | return self # My components are also immutable |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3553 | return self.__class__(str(self)) |
| 3554 | |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 3555 | # PEP 3101 support. the _localeconv keyword argument should be |
| 3556 | # considered private: it's provided for ease of testing only. |
| 3557 | def __format__(self, specifier, context=None, _localeconv=None): |
Mark Dickinson | f4da777 | 2008-02-29 03:29:17 +0000 | [diff] [blame] | 3558 | """Format a Decimal instance according to the given specifier. |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 3559 | |
| 3560 | The specifier should be a standard format specifier, with the |
| 3561 | form described in PEP 3101. Formatting types 'e', 'E', 'f', |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 3562 | 'F', 'g', 'G', 'n' and '%' are supported. If the formatting |
| 3563 | type is omitted it defaults to 'g' or 'G', depending on the |
| 3564 | value of context.capitals. |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 3565 | """ |
| 3566 | |
| 3567 | # Note: PEP 3101 says that if the type is not present then |
| 3568 | # there should be at least one digit after the decimal point. |
| 3569 | # We take the liberty of ignoring this requirement for |
| 3570 | # Decimal---it's presumably there to make sure that |
| 3571 | # format(float, '') behaves similarly to str(float). |
| 3572 | if context is None: |
| 3573 | context = getcontext() |
| 3574 | |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 3575 | spec = _parse_format_specifier(specifier, _localeconv=_localeconv) |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 3576 | |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 3577 | # special values don't care about the type or precision |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 3578 | if self._is_special: |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 3579 | sign = _format_sign(self._sign, spec) |
| 3580 | body = str(self.copy_abs()) |
| 3581 | return _format_align(sign, body, spec) |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 3582 | |
| 3583 | # a type of None defaults to 'g' or 'G', depending on context |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 3584 | if spec['type'] is None: |
| 3585 | spec['type'] = ['g', 'G'][context.capitals] |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 3586 | |
| 3587 | # if type is '%', adjust exponent of self accordingly |
| 3588 | if spec['type'] == '%': |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 3589 | self = _dec_from_triple(self._sign, self._int, self._exp+2) |
| 3590 | |
| 3591 | # round if necessary, taking rounding mode from the context |
| 3592 | rounding = context.rounding |
| 3593 | precision = spec['precision'] |
| 3594 | if precision is not None: |
| 3595 | if spec['type'] in 'eE': |
| 3596 | self = self._round(precision+1, rounding) |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 3597 | elif spec['type'] in 'fF%': |
| 3598 | self = self._rescale(-precision, rounding) |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 3599 | elif spec['type'] in 'gG' and len(self._int) > precision: |
| 3600 | self = self._round(precision, rounding) |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 3601 | # special case: zeros with a positive exponent can't be |
| 3602 | # represented in fixed point; rescale them to 0e0. |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 3603 | if not self and self._exp > 0 and spec['type'] in 'fF%': |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 3604 | self = self._rescale(0, rounding) |
| 3605 | |
| 3606 | # figure out placement of the decimal point |
| 3607 | leftdigits = self._exp + len(self._int) |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 3608 | if spec['type'] in 'eE': |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 3609 | if not self and precision is not None: |
| 3610 | dotplace = 1 - precision |
| 3611 | else: |
| 3612 | dotplace = 1 |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 3613 | elif spec['type'] in 'fF%': |
| 3614 | dotplace = leftdigits |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 3615 | elif spec['type'] in 'gG': |
| 3616 | if self._exp <= 0 and leftdigits > -6: |
| 3617 | dotplace = leftdigits |
| 3618 | else: |
| 3619 | dotplace = 1 |
| 3620 | |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 3621 | # find digits before and after decimal point, and get exponent |
| 3622 | if dotplace < 0: |
| 3623 | intpart = '0' |
| 3624 | fracpart = '0'*(-dotplace) + self._int |
| 3625 | elif dotplace > len(self._int): |
| 3626 | intpart = self._int + '0'*(dotplace-len(self._int)) |
| 3627 | fracpart = '' |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 3628 | else: |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 3629 | intpart = self._int[:dotplace] or '0' |
| 3630 | fracpart = self._int[dotplace:] |
| 3631 | exp = leftdigits-dotplace |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 3632 | |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 3633 | # done with the decimal-specific stuff; hand over the rest |
| 3634 | # of the formatting to the _format_number function |
| 3635 | return _format_number(self._sign, intpart, fracpart, exp, spec) |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 3636 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3637 | def _dec_from_triple(sign, coefficient, exponent, special=False): |
| 3638 | """Create a decimal instance directly, without any validation, |
| 3639 | normalization (e.g. removal of leading zeros) or argument |
| 3640 | conversion. |
| 3641 | |
| 3642 | This function is for *internal use only*. |
| 3643 | """ |
| 3644 | |
| 3645 | self = object.__new__(Decimal) |
| 3646 | self._sign = sign |
| 3647 | self._int = coefficient |
| 3648 | self._exp = exponent |
| 3649 | self._is_special = special |
| 3650 | |
| 3651 | return self |
| 3652 | |
Raymond Hettinger | 2c8585b | 2009-02-03 03:37:03 +0000 | [diff] [blame] | 3653 | # Register Decimal as a kind of Number (an abstract base class). |
| 3654 | # However, do not register it as Real (because Decimals are not |
| 3655 | # interoperable with floats). |
| 3656 | _numbers.Number.register(Decimal) |
| 3657 | |
| 3658 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3659 | ##### Context class ####################################################### |
Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 3660 | |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 3661 | |
| 3662 | # get rounding method function: |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3663 | rounding_functions = [name for name in Decimal.__dict__.keys() |
| 3664 | if name.startswith('_round_')] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3665 | for name in rounding_functions: |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3666 | # 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] | 3667 | globalname = name[1:].upper() |
| 3668 | val = globals()[globalname] |
| 3669 | Decimal._pick_rounding_function[val] = name |
| 3670 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3671 | del name, val, globalname, rounding_functions |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3672 | |
Nick Coghlan | ced1218 | 2006-09-02 03:54:17 +0000 | [diff] [blame] | 3673 | class _ContextManager(object): |
Nick Coghlan | 8b6999b | 2006-08-31 12:00:43 +0000 | [diff] [blame] | 3674 | """Context manager class to support localcontext(). |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 3675 | |
Nick Coghlan | ced1218 | 2006-09-02 03:54:17 +0000 | [diff] [blame] | 3676 | Sets a copy of the supplied context in __enter__() and restores |
Nick Coghlan | 8b6999b | 2006-08-31 12:00:43 +0000 | [diff] [blame] | 3677 | the previous decimal context in __exit__() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 3678 | """ |
| 3679 | def __init__(self, new_context): |
Nick Coghlan | ced1218 | 2006-09-02 03:54:17 +0000 | [diff] [blame] | 3680 | self.new_context = new_context.copy() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 3681 | def __enter__(self): |
| 3682 | self.saved_context = getcontext() |
| 3683 | setcontext(self.new_context) |
| 3684 | return self.new_context |
| 3685 | def __exit__(self, t, v, tb): |
| 3686 | setcontext(self.saved_context) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 3687 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3688 | class Context(object): |
| 3689 | """Contains the context for a Decimal instance. |
| 3690 | |
| 3691 | Contains: |
| 3692 | prec - precision (for use in rounding, division, square roots..) |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3693 | rounding - rounding type (how you round) |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3694 | traps - If traps[exception] = 1, then the exception is |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3695 | raised when it is caused. Otherwise, a value is |
| 3696 | substituted in. |
Mark Dickinson | 1840c1a | 2008-05-03 18:23:14 +0000 | [diff] [blame] | 3697 | flags - When an exception is caused, flags[exception] is set. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3698 | (Whether or not the trap_enabler is set) |
| 3699 | Should be reset by user of Decimal instance. |
Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 3700 | Emin - Minimum exponent |
| 3701 | Emax - Maximum exponent |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3702 | capitals - If 1, 1*10^1 is printed as 1E+1. |
| 3703 | If 0, printed as 1e1 |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 3704 | _clamp - If 1, change exponents if too high (Default 0) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3705 | """ |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3706 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3707 | def __init__(self, prec=None, rounding=None, |
Raymond Hettinger | abf8a56 | 2004-10-12 09:12:16 +0000 | [diff] [blame] | 3708 | traps=None, flags=None, |
Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 3709 | Emin=None, Emax=None, |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 3710 | capitals=None, _clamp=0, |
Raymond Hettinger | abf8a56 | 2004-10-12 09:12:16 +0000 | [diff] [blame] | 3711 | _ignored_flags=None): |
| 3712 | if flags is None: |
| 3713 | flags = [] |
| 3714 | if _ignored_flags is None: |
| 3715 | _ignored_flags = [] |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3716 | if not isinstance(flags, dict): |
Mark Dickinson | 71f3b85 | 2008-05-04 02:25:46 +0000 | [diff] [blame] | 3717 | flags = dict([(s, int(s in flags)) for s in _signals]) |
Raymond Hettinger | b91af52 | 2004-07-14 16:35:30 +0000 | [diff] [blame] | 3718 | del s |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3719 | if traps is not None and not isinstance(traps, dict): |
Mark Dickinson | 71f3b85 | 2008-05-04 02:25:46 +0000 | [diff] [blame] | 3720 | traps = dict([(s, int(s in traps)) for s in _signals]) |
Raymond Hettinger | b91af52 | 2004-07-14 16:35:30 +0000 | [diff] [blame] | 3721 | del s |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3722 | for name, val in locals().items(): |
| 3723 | if val is None: |
Raymond Hettinger | eb26084 | 2005-06-07 18:52:34 +0000 | [diff] [blame] | 3724 | setattr(self, name, _copy.copy(getattr(DefaultContext, name))) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3725 | else: |
| 3726 | setattr(self, name, val) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3727 | del self.self |
| 3728 | |
Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 3729 | def __repr__(self): |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3730 | """Show the current context.""" |
Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 3731 | s = [] |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3732 | s.append('Context(prec=%(prec)d, rounding=%(rounding)s, ' |
| 3733 | 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d' |
| 3734 | % vars(self)) |
| 3735 | names = [f.__name__ for f, v in self.flags.items() if v] |
| 3736 | s.append('flags=[' + ', '.join(names) + ']') |
| 3737 | names = [t.__name__ for t, v in self.traps.items() if v] |
| 3738 | s.append('traps=[' + ', '.join(names) + ']') |
Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 3739 | return ', '.join(s) + ')' |
| 3740 | |
Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 3741 | def clear_flags(self): |
| 3742 | """Reset all flags to zero""" |
| 3743 | for flag in self.flags: |
Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 3744 | self.flags[flag] = 0 |
Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 3745 | |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 3746 | def _shallow_copy(self): |
| 3747 | """Returns a shallow copy from self.""" |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 3748 | nc = Context(self.prec, self.rounding, self.traps, |
| 3749 | self.flags, self.Emin, self.Emax, |
| 3750 | self.capitals, self._clamp, self._ignored_flags) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3751 | return nc |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 3752 | |
| 3753 | def copy(self): |
| 3754 | """Returns a deep copy from self.""" |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3755 | nc = Context(self.prec, self.rounding, self.traps.copy(), |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 3756 | self.flags.copy(), self.Emin, self.Emax, |
| 3757 | self.capitals, self._clamp, self._ignored_flags) |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 3758 | return nc |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3759 | __copy__ = copy |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3760 | |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 3761 | def _raise_error(self, condition, explanation = None, *args): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3762 | """Handles an error |
| 3763 | |
| 3764 | If the flag is in _ignored_flags, returns the default response. |
Mark Dickinson | 1840c1a | 2008-05-03 18:23:14 +0000 | [diff] [blame] | 3765 | Otherwise, it sets the flag, then, if the corresponding |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3766 | trap_enabler is set, it reaises the exception. Otherwise, it returns |
Mark Dickinson | 1840c1a | 2008-05-03 18:23:14 +0000 | [diff] [blame] | 3767 | the default value after setting the flag. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3768 | """ |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 3769 | error = _condition_map.get(condition, condition) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3770 | if error in self._ignored_flags: |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3771 | # Don't touch the flag |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3772 | return error().handle(self, *args) |
| 3773 | |
Mark Dickinson | 1840c1a | 2008-05-03 18:23:14 +0000 | [diff] [blame] | 3774 | self.flags[error] = 1 |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3775 | if not self.traps[error]: |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3776 | # The errors define how to handle themselves. |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 3777 | return condition().handle(self, *args) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3778 | |
| 3779 | # Errors should only be risked on copies of the context |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3780 | # self._ignored_flags = [] |
Mark Dickinson | 8aca9d0 | 2008-05-04 02:05:06 +0000 | [diff] [blame] | 3781 | raise error(explanation) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3782 | |
| 3783 | def _ignore_all_flags(self): |
| 3784 | """Ignore all flags, if they are raised""" |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 3785 | return self._ignore_flags(*_signals) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3786 | |
| 3787 | def _ignore_flags(self, *flags): |
| 3788 | """Ignore the flags, if they are raised""" |
| 3789 | # Do not mutate-- This way, copies of a context leave the original |
| 3790 | # alone. |
| 3791 | self._ignored_flags = (self._ignored_flags + list(flags)) |
| 3792 | return list(flags) |
| 3793 | |
| 3794 | def _regard_flags(self, *flags): |
| 3795 | """Stop ignoring the flags, if they are raised""" |
| 3796 | if flags and isinstance(flags[0], (tuple,list)): |
| 3797 | flags = flags[0] |
| 3798 | for flag in flags: |
| 3799 | self._ignored_flags.remove(flag) |
| 3800 | |
Nick Coghlan | 53663a6 | 2008-07-15 14:27:37 +0000 | [diff] [blame] | 3801 | # We inherit object.__hash__, so we must deny this explicitly |
| 3802 | __hash__ = None |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 3803 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3804 | def Etiny(self): |
| 3805 | """Returns Etiny (= Emin - prec + 1)""" |
| 3806 | return int(self.Emin - self.prec + 1) |
| 3807 | |
| 3808 | def Etop(self): |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 3809 | """Returns maximum exponent (= Emax - prec + 1)""" |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3810 | return int(self.Emax - self.prec + 1) |
| 3811 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3812 | def _set_rounding(self, type): |
| 3813 | """Sets the rounding type. |
| 3814 | |
| 3815 | Sets the rounding type, and returns the current (previous) |
| 3816 | rounding type. Often used like: |
| 3817 | |
| 3818 | context = context.copy() |
| 3819 | # so you don't change the calling context |
| 3820 | # if an error occurs in the middle. |
| 3821 | rounding = context._set_rounding(ROUND_UP) |
| 3822 | val = self.__sub__(other, context=context) |
| 3823 | context._set_rounding(rounding) |
| 3824 | |
| 3825 | This will make it round up for that operation. |
| 3826 | """ |
| 3827 | rounding = self.rounding |
| 3828 | self.rounding= type |
| 3829 | return rounding |
| 3830 | |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 3831 | def create_decimal(self, num='0'): |
Mark Dickinson | 59bc20b | 2008-01-12 01:56:00 +0000 | [diff] [blame] | 3832 | """Creates a new Decimal instance but using self as context. |
| 3833 | |
| 3834 | This method implements the to-number operation of the |
| 3835 | IBM Decimal specification.""" |
| 3836 | |
| 3837 | if isinstance(num, basestring) and num != num.strip(): |
| 3838 | return self._raise_error(ConversionSyntax, |
| 3839 | "no trailing or leading whitespace is " |
| 3840 | "permitted.") |
| 3841 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3842 | d = Decimal(num, context=self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3843 | if d._isnan() and len(d._int) > self.prec - self._clamp: |
| 3844 | return self._raise_error(ConversionSyntax, |
| 3845 | "diagnostic info too long in NaN") |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 3846 | return d._fix(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3847 | |
Raymond Hettinger | f4d8597 | 2009-01-03 19:02:23 +0000 | [diff] [blame] | 3848 | def create_decimal_from_float(self, f): |
| 3849 | """Creates a new Decimal instance from a float but rounding using self |
| 3850 | as the context. |
| 3851 | |
| 3852 | >>> context = Context(prec=5, rounding=ROUND_DOWN) |
| 3853 | >>> context.create_decimal_from_float(3.1415926535897932) |
| 3854 | Decimal('3.1415') |
| 3855 | >>> context = Context(prec=5, traps=[Inexact]) |
| 3856 | >>> context.create_decimal_from_float(3.1415926535897932) |
| 3857 | Traceback (most recent call last): |
| 3858 | ... |
| 3859 | Inexact: None |
| 3860 | |
| 3861 | """ |
| 3862 | d = Decimal.from_float(f) # An exact conversion |
| 3863 | return d._fix(self) # Apply the context rounding |
| 3864 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3865 | # Methods |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3866 | def abs(self, a): |
| 3867 | """Returns the absolute value of the operand. |
| 3868 | |
| 3869 | 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] | 3870 | operation on the operand. Otherwise, the result is the same as using |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3871 | the plus operation on the operand. |
| 3872 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3873 | >>> ExtendedContext.abs(Decimal('2.1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3874 | Decimal('2.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3875 | >>> ExtendedContext.abs(Decimal('-100')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3876 | Decimal('100') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3877 | >>> ExtendedContext.abs(Decimal('101.5')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3878 | Decimal('101.5') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3879 | >>> ExtendedContext.abs(Decimal('-101.5')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3880 | Decimal('101.5') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 3881 | >>> ExtendedContext.abs(-1) |
| 3882 | Decimal('1') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3883 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 3884 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3885 | return a.__abs__(context=self) |
| 3886 | |
| 3887 | def add(self, a, b): |
| 3888 | """Return the sum of the two operands. |
| 3889 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3890 | >>> ExtendedContext.add(Decimal('12'), Decimal('7.00')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3891 | Decimal('19.00') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3892 | >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3893 | Decimal('1.02E+4') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 3894 | >>> ExtendedContext.add(1, Decimal(2)) |
| 3895 | Decimal('3') |
| 3896 | >>> ExtendedContext.add(Decimal(8), 5) |
| 3897 | Decimal('13') |
| 3898 | >>> ExtendedContext.add(5, 5) |
| 3899 | Decimal('10') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3900 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 3901 | a = _convert_other(a, raiseit=True) |
| 3902 | r = a.__add__(b, context=self) |
| 3903 | if r is NotImplemented: |
| 3904 | raise TypeError("Unable to convert %s to Decimal" % b) |
| 3905 | else: |
| 3906 | return r |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3907 | |
| 3908 | def _apply(self, a): |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 3909 | return str(a._fix(self)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3910 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3911 | def canonical(self, a): |
| 3912 | """Returns the same Decimal object. |
| 3913 | |
| 3914 | As we do not have different encodings for the same number, the |
| 3915 | received object already is in its canonical form. |
| 3916 | |
| 3917 | >>> ExtendedContext.canonical(Decimal('2.50')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3918 | Decimal('2.50') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3919 | """ |
| 3920 | return a.canonical(context=self) |
| 3921 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3922 | def compare(self, a, b): |
| 3923 | """Compares values numerically. |
| 3924 | |
| 3925 | If the signs of the operands differ, a value representing each operand |
| 3926 | ('-1' if the operand is less than zero, '0' if the operand is zero or |
| 3927 | negative zero, or '1' if the operand is greater than zero) is used in |
| 3928 | place of that operand for the comparison instead of the actual |
| 3929 | operand. |
| 3930 | |
| 3931 | The comparison is then effected by subtracting the second operand from |
| 3932 | the first and then returning a value according to the result of the |
| 3933 | subtraction: '-1' if the result is less than zero, '0' if the result is |
| 3934 | zero or negative zero, or '1' if the result is greater than zero. |
| 3935 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3936 | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3937 | Decimal('-1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3938 | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3939 | Decimal('0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3940 | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3941 | Decimal('0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3942 | >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3943 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3944 | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3945 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3946 | >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3947 | Decimal('-1') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 3948 | >>> ExtendedContext.compare(1, 2) |
| 3949 | Decimal('-1') |
| 3950 | >>> ExtendedContext.compare(Decimal(1), 2) |
| 3951 | Decimal('-1') |
| 3952 | >>> ExtendedContext.compare(1, Decimal(2)) |
| 3953 | Decimal('-1') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3954 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 3955 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3956 | return a.compare(b, context=self) |
| 3957 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3958 | def compare_signal(self, a, b): |
| 3959 | """Compares the values of the two operands numerically. |
| 3960 | |
| 3961 | It's pretty much like compare(), but all NaNs signal, with signaling |
| 3962 | NaNs taking precedence over quiet NaNs. |
| 3963 | |
| 3964 | >>> c = ExtendedContext |
| 3965 | >>> c.compare_signal(Decimal('2.1'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3966 | Decimal('-1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3967 | >>> c.compare_signal(Decimal('2.1'), Decimal('2.1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3968 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3969 | >>> c.flags[InvalidOperation] = 0 |
| 3970 | >>> print c.flags[InvalidOperation] |
| 3971 | 0 |
| 3972 | >>> c.compare_signal(Decimal('NaN'), Decimal('2.1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3973 | Decimal('NaN') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3974 | >>> print c.flags[InvalidOperation] |
| 3975 | 1 |
| 3976 | >>> c.flags[InvalidOperation] = 0 |
| 3977 | >>> print c.flags[InvalidOperation] |
| 3978 | 0 |
| 3979 | >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3980 | Decimal('NaN') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3981 | >>> print c.flags[InvalidOperation] |
| 3982 | 1 |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 3983 | >>> c.compare_signal(-1, 2) |
| 3984 | Decimal('-1') |
| 3985 | >>> c.compare_signal(Decimal(-1), 2) |
| 3986 | Decimal('-1') |
| 3987 | >>> c.compare_signal(-1, Decimal(2)) |
| 3988 | Decimal('-1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3989 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 3990 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3991 | return a.compare_signal(b, context=self) |
| 3992 | |
| 3993 | def compare_total(self, a, b): |
| 3994 | """Compares two operands using their abstract representation. |
| 3995 | |
| 3996 | This is not like the standard compare, which use their numerical |
| 3997 | value. Note that a total ordering is defined for all possible abstract |
| 3998 | representations. |
| 3999 | |
| 4000 | >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4001 | Decimal('-1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4002 | >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4003 | Decimal('-1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4004 | >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4005 | Decimal('-1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4006 | >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4007 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4008 | >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4009 | Decimal('1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4010 | >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4011 | Decimal('-1') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4012 | >>> ExtendedContext.compare_total(1, 2) |
| 4013 | Decimal('-1') |
| 4014 | >>> ExtendedContext.compare_total(Decimal(1), 2) |
| 4015 | Decimal('-1') |
| 4016 | >>> ExtendedContext.compare_total(1, Decimal(2)) |
| 4017 | Decimal('-1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4018 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4019 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4020 | return a.compare_total(b) |
| 4021 | |
| 4022 | def compare_total_mag(self, a, b): |
| 4023 | """Compares two operands using their abstract representation ignoring sign. |
| 4024 | |
| 4025 | Like compare_total, but with operand's sign ignored and assumed to be 0. |
| 4026 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4027 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4028 | return a.compare_total_mag(b) |
| 4029 | |
| 4030 | def copy_abs(self, a): |
| 4031 | """Returns a copy of the operand with the sign set to 0. |
| 4032 | |
| 4033 | >>> ExtendedContext.copy_abs(Decimal('2.1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4034 | Decimal('2.1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4035 | >>> ExtendedContext.copy_abs(Decimal('-100')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4036 | Decimal('100') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4037 | >>> ExtendedContext.copy_abs(-1) |
| 4038 | Decimal('1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4039 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4040 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4041 | return a.copy_abs() |
| 4042 | |
| 4043 | def copy_decimal(self, a): |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4044 | """Returns a copy of the decimal object. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4045 | |
| 4046 | >>> ExtendedContext.copy_decimal(Decimal('2.1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4047 | Decimal('2.1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4048 | >>> ExtendedContext.copy_decimal(Decimal('-1.00')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4049 | Decimal('-1.00') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4050 | >>> ExtendedContext.copy_decimal(1) |
| 4051 | Decimal('1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4052 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4053 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 4054 | return Decimal(a) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4055 | |
| 4056 | def copy_negate(self, a): |
| 4057 | """Returns a copy of the operand with the sign inverted. |
| 4058 | |
| 4059 | >>> ExtendedContext.copy_negate(Decimal('101.5')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4060 | Decimal('-101.5') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4061 | >>> ExtendedContext.copy_negate(Decimal('-101.5')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4062 | Decimal('101.5') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4063 | >>> ExtendedContext.copy_negate(1) |
| 4064 | Decimal('-1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4065 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4066 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4067 | return a.copy_negate() |
| 4068 | |
| 4069 | def copy_sign(self, a, b): |
| 4070 | """Copies the second operand's sign to the first one. |
| 4071 | |
| 4072 | In detail, it returns a copy of the first operand with the sign |
| 4073 | equal to the sign of the second operand. |
| 4074 | |
| 4075 | >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4076 | Decimal('1.50') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4077 | >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4078 | Decimal('1.50') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4079 | >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4080 | Decimal('-1.50') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4081 | >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4082 | Decimal('-1.50') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4083 | >>> ExtendedContext.copy_sign(1, -2) |
| 4084 | Decimal('-1') |
| 4085 | >>> ExtendedContext.copy_sign(Decimal(1), -2) |
| 4086 | Decimal('-1') |
| 4087 | >>> ExtendedContext.copy_sign(1, Decimal(-2)) |
| 4088 | Decimal('-1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4089 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4090 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4091 | return a.copy_sign(b) |
| 4092 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4093 | def divide(self, a, b): |
| 4094 | """Decimal division in a specified context. |
| 4095 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4096 | >>> ExtendedContext.divide(Decimal('1'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4097 | Decimal('0.333333333') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4098 | >>> ExtendedContext.divide(Decimal('2'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4099 | Decimal('0.666666667') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4100 | >>> ExtendedContext.divide(Decimal('5'), Decimal('2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4101 | Decimal('2.5') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4102 | >>> ExtendedContext.divide(Decimal('1'), Decimal('10')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4103 | Decimal('0.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4104 | >>> ExtendedContext.divide(Decimal('12'), Decimal('12')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4105 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4106 | >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4107 | Decimal('4.00') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4108 | >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4109 | Decimal('1.20') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4110 | >>> ExtendedContext.divide(Decimal('1000'), Decimal('100')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4111 | Decimal('10') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4112 | >>> ExtendedContext.divide(Decimal('1000'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4113 | Decimal('1000') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4114 | >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4115 | Decimal('1.20E+6') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4116 | >>> ExtendedContext.divide(5, 5) |
| 4117 | Decimal('1') |
| 4118 | >>> ExtendedContext.divide(Decimal(5), 5) |
| 4119 | Decimal('1') |
| 4120 | >>> ExtendedContext.divide(5, Decimal(5)) |
| 4121 | Decimal('1') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4122 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4123 | a = _convert_other(a, raiseit=True) |
| 4124 | r = a.__div__(b, context=self) |
| 4125 | if r is NotImplemented: |
| 4126 | raise TypeError("Unable to convert %s to Decimal" % b) |
| 4127 | else: |
| 4128 | return r |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4129 | |
| 4130 | def divide_int(self, a, b): |
| 4131 | """Divides two numbers and returns the integer part of the result. |
| 4132 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4133 | >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4134 | Decimal('0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4135 | >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4136 | Decimal('3') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4137 | >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4138 | Decimal('3') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4139 | >>> ExtendedContext.divide_int(10, 3) |
| 4140 | Decimal('3') |
| 4141 | >>> ExtendedContext.divide_int(Decimal(10), 3) |
| 4142 | Decimal('3') |
| 4143 | >>> ExtendedContext.divide_int(10, Decimal(3)) |
| 4144 | Decimal('3') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4145 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4146 | a = _convert_other(a, raiseit=True) |
| 4147 | r = a.__floordiv__(b, context=self) |
| 4148 | if r is NotImplemented: |
| 4149 | raise TypeError("Unable to convert %s to Decimal" % b) |
| 4150 | else: |
| 4151 | return r |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4152 | |
| 4153 | def divmod(self, a, b): |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4154 | """Return (a // b, a % b). |
Mark Dickinson | 202eb90 | 2010-01-06 16:20:22 +0000 | [diff] [blame] | 4155 | |
| 4156 | >>> ExtendedContext.divmod(Decimal(8), Decimal(3)) |
| 4157 | (Decimal('2'), Decimal('2')) |
| 4158 | >>> ExtendedContext.divmod(Decimal(8), Decimal(4)) |
| 4159 | (Decimal('2'), Decimal('0')) |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4160 | >>> ExtendedContext.divmod(8, 4) |
| 4161 | (Decimal('2'), Decimal('0')) |
| 4162 | >>> ExtendedContext.divmod(Decimal(8), 4) |
| 4163 | (Decimal('2'), Decimal('0')) |
| 4164 | >>> ExtendedContext.divmod(8, Decimal(4)) |
| 4165 | (Decimal('2'), Decimal('0')) |
Mark Dickinson | 202eb90 | 2010-01-06 16:20:22 +0000 | [diff] [blame] | 4166 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4167 | a = _convert_other(a, raiseit=True) |
| 4168 | r = a.__divmod__(b, context=self) |
| 4169 | if r is NotImplemented: |
| 4170 | raise TypeError("Unable to convert %s to Decimal" % b) |
| 4171 | else: |
| 4172 | return r |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4173 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4174 | def exp(self, a): |
| 4175 | """Returns e ** a. |
| 4176 | |
| 4177 | >>> c = ExtendedContext.copy() |
| 4178 | >>> c.Emin = -999 |
| 4179 | >>> c.Emax = 999 |
| 4180 | >>> c.exp(Decimal('-Infinity')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4181 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4182 | >>> c.exp(Decimal('-1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4183 | Decimal('0.367879441') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4184 | >>> c.exp(Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4185 | Decimal('1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4186 | >>> c.exp(Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4187 | Decimal('2.71828183') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4188 | >>> c.exp(Decimal('0.693147181')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4189 | Decimal('2.00000000') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4190 | >>> c.exp(Decimal('+Infinity')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4191 | Decimal('Infinity') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4192 | >>> c.exp(10) |
| 4193 | Decimal('22026.4658') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4194 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4195 | a =_convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4196 | return a.exp(context=self) |
| 4197 | |
| 4198 | def fma(self, a, b, c): |
| 4199 | """Returns a multiplied by b, plus c. |
| 4200 | |
| 4201 | The first two operands are multiplied together, using multiply, |
| 4202 | the third operand is then added to the result of that |
| 4203 | multiplication, using add, all with only one final rounding. |
| 4204 | |
| 4205 | >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4206 | Decimal('22') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4207 | >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4208 | Decimal('-8') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4209 | >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4210 | Decimal('1.38435736E+12') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4211 | >>> ExtendedContext.fma(1, 3, 4) |
| 4212 | Decimal('7') |
| 4213 | >>> ExtendedContext.fma(1, Decimal(3), 4) |
| 4214 | Decimal('7') |
| 4215 | >>> ExtendedContext.fma(1, 3, Decimal(4)) |
| 4216 | Decimal('7') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4217 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4218 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4219 | return a.fma(b, c, context=self) |
| 4220 | |
| 4221 | def is_canonical(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4222 | """Return True if the operand is canonical; otherwise return False. |
| 4223 | |
| 4224 | Currently, the encoding of a Decimal instance is always |
| 4225 | canonical, so this method returns True for any Decimal. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4226 | |
| 4227 | >>> ExtendedContext.is_canonical(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4228 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4229 | """ |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4230 | return a.is_canonical() |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4231 | |
| 4232 | def is_finite(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4233 | """Return True if the operand is finite; otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4234 | |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4235 | A Decimal instance is considered finite if it is neither |
| 4236 | infinite nor a NaN. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4237 | |
| 4238 | >>> ExtendedContext.is_finite(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4239 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4240 | >>> ExtendedContext.is_finite(Decimal('-0.3')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4241 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4242 | >>> ExtendedContext.is_finite(Decimal('0')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4243 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4244 | >>> ExtendedContext.is_finite(Decimal('Inf')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4245 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4246 | >>> ExtendedContext.is_finite(Decimal('NaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4247 | False |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4248 | >>> ExtendedContext.is_finite(1) |
| 4249 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4250 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4251 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4252 | return a.is_finite() |
| 4253 | |
| 4254 | def is_infinite(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4255 | """Return True if the operand is infinite; otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4256 | |
| 4257 | >>> ExtendedContext.is_infinite(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4258 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4259 | >>> ExtendedContext.is_infinite(Decimal('-Inf')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4260 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4261 | >>> ExtendedContext.is_infinite(Decimal('NaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4262 | False |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4263 | >>> ExtendedContext.is_infinite(1) |
| 4264 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4265 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4266 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4267 | return a.is_infinite() |
| 4268 | |
| 4269 | def is_nan(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4270 | """Return True if the operand is a qNaN or sNaN; |
| 4271 | otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4272 | |
| 4273 | >>> ExtendedContext.is_nan(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4274 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4275 | >>> ExtendedContext.is_nan(Decimal('NaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4276 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4277 | >>> ExtendedContext.is_nan(Decimal('-sNaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4278 | True |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4279 | >>> ExtendedContext.is_nan(1) |
| 4280 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4281 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4282 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4283 | return a.is_nan() |
| 4284 | |
| 4285 | def is_normal(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4286 | """Return True if the operand is a normal number; |
| 4287 | otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4288 | |
| 4289 | >>> c = ExtendedContext.copy() |
| 4290 | >>> c.Emin = -999 |
| 4291 | >>> c.Emax = 999 |
| 4292 | >>> c.is_normal(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4293 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4294 | >>> c.is_normal(Decimal('0.1E-999')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4295 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4296 | >>> c.is_normal(Decimal('0.00')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4297 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4298 | >>> c.is_normal(Decimal('-Inf')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4299 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4300 | >>> c.is_normal(Decimal('NaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4301 | False |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4302 | >>> c.is_normal(1) |
| 4303 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4304 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4305 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4306 | return a.is_normal(context=self) |
| 4307 | |
| 4308 | def is_qnan(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4309 | """Return True if the operand is a quiet NaN; otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4310 | |
| 4311 | >>> ExtendedContext.is_qnan(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4312 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4313 | >>> ExtendedContext.is_qnan(Decimal('NaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4314 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4315 | >>> ExtendedContext.is_qnan(Decimal('sNaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4316 | False |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4317 | >>> ExtendedContext.is_qnan(1) |
| 4318 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4319 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4320 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4321 | return a.is_qnan() |
| 4322 | |
| 4323 | def is_signed(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4324 | """Return True if the operand is negative; otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4325 | |
| 4326 | >>> ExtendedContext.is_signed(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4327 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4328 | >>> ExtendedContext.is_signed(Decimal('-12')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4329 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4330 | >>> ExtendedContext.is_signed(Decimal('-0')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4331 | True |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4332 | >>> ExtendedContext.is_signed(8) |
| 4333 | False |
| 4334 | >>> ExtendedContext.is_signed(-8) |
| 4335 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4336 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4337 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4338 | return a.is_signed() |
| 4339 | |
| 4340 | def is_snan(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4341 | """Return True if the operand is a signaling NaN; |
| 4342 | otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4343 | |
| 4344 | >>> ExtendedContext.is_snan(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4345 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4346 | >>> ExtendedContext.is_snan(Decimal('NaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4347 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4348 | >>> ExtendedContext.is_snan(Decimal('sNaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4349 | True |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4350 | >>> ExtendedContext.is_snan(1) |
| 4351 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4352 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4353 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4354 | return a.is_snan() |
| 4355 | |
| 4356 | def is_subnormal(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4357 | """Return True if the operand is subnormal; otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4358 | |
| 4359 | >>> c = ExtendedContext.copy() |
| 4360 | >>> c.Emin = -999 |
| 4361 | >>> c.Emax = 999 |
| 4362 | >>> c.is_subnormal(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4363 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4364 | >>> c.is_subnormal(Decimal('0.1E-999')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4365 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4366 | >>> c.is_subnormal(Decimal('0.00')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4367 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4368 | >>> c.is_subnormal(Decimal('-Inf')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4369 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4370 | >>> c.is_subnormal(Decimal('NaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4371 | False |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4372 | >>> c.is_subnormal(1) |
| 4373 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4374 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4375 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4376 | return a.is_subnormal(context=self) |
| 4377 | |
| 4378 | def is_zero(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4379 | """Return True if the operand is a zero; otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4380 | |
| 4381 | >>> ExtendedContext.is_zero(Decimal('0')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4382 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4383 | >>> ExtendedContext.is_zero(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4384 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4385 | >>> ExtendedContext.is_zero(Decimal('-0E+2')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4386 | True |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4387 | >>> ExtendedContext.is_zero(1) |
| 4388 | False |
| 4389 | >>> ExtendedContext.is_zero(0) |
| 4390 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4391 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4392 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4393 | return a.is_zero() |
| 4394 | |
| 4395 | def ln(self, a): |
| 4396 | """Returns the natural (base e) logarithm of the operand. |
| 4397 | |
| 4398 | >>> c = ExtendedContext.copy() |
| 4399 | >>> c.Emin = -999 |
| 4400 | >>> c.Emax = 999 |
| 4401 | >>> c.ln(Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4402 | Decimal('-Infinity') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4403 | >>> c.ln(Decimal('1.000')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4404 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4405 | >>> c.ln(Decimal('2.71828183')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4406 | Decimal('1.00000000') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4407 | >>> c.ln(Decimal('10')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4408 | Decimal('2.30258509') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4409 | >>> c.ln(Decimal('+Infinity')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4410 | Decimal('Infinity') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4411 | >>> c.ln(1) |
| 4412 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4413 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4414 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4415 | return a.ln(context=self) |
| 4416 | |
| 4417 | def log10(self, a): |
| 4418 | """Returns the base 10 logarithm of the operand. |
| 4419 | |
| 4420 | >>> c = ExtendedContext.copy() |
| 4421 | >>> c.Emin = -999 |
| 4422 | >>> c.Emax = 999 |
| 4423 | >>> c.log10(Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4424 | Decimal('-Infinity') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4425 | >>> c.log10(Decimal('0.001')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4426 | Decimal('-3') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4427 | >>> c.log10(Decimal('1.000')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4428 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4429 | >>> c.log10(Decimal('2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4430 | Decimal('0.301029996') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4431 | >>> c.log10(Decimal('10')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4432 | Decimal('1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4433 | >>> c.log10(Decimal('70')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4434 | Decimal('1.84509804') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4435 | >>> c.log10(Decimal('+Infinity')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4436 | Decimal('Infinity') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4437 | >>> c.log10(0) |
| 4438 | Decimal('-Infinity') |
| 4439 | >>> c.log10(1) |
| 4440 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4441 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4442 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4443 | return a.log10(context=self) |
| 4444 | |
| 4445 | def logb(self, a): |
| 4446 | """ Returns the exponent of the magnitude of the operand's MSD. |
| 4447 | |
| 4448 | The result is the integer which is the exponent of the magnitude |
| 4449 | of the most significant digit of the operand (as though the |
| 4450 | operand were truncated to a single digit while maintaining the |
| 4451 | value of that digit and without limiting the resulting exponent). |
| 4452 | |
| 4453 | >>> ExtendedContext.logb(Decimal('250')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4454 | Decimal('2') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4455 | >>> ExtendedContext.logb(Decimal('2.50')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4456 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4457 | >>> ExtendedContext.logb(Decimal('0.03')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4458 | Decimal('-2') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4459 | >>> ExtendedContext.logb(Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4460 | Decimal('-Infinity') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4461 | >>> ExtendedContext.logb(1) |
| 4462 | Decimal('0') |
| 4463 | >>> ExtendedContext.logb(10) |
| 4464 | Decimal('1') |
| 4465 | >>> ExtendedContext.logb(100) |
| 4466 | Decimal('2') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4467 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4468 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4469 | return a.logb(context=self) |
| 4470 | |
| 4471 | def logical_and(self, a, b): |
| 4472 | """Applies the logical operation 'and' between each operand's digits. |
| 4473 | |
| 4474 | The operands must be both logical numbers. |
| 4475 | |
| 4476 | >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4477 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4478 | >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4479 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4480 | >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4481 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4482 | >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4483 | Decimal('1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4484 | >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4485 | Decimal('1000') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4486 | >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4487 | Decimal('10') |
Mark Dickinson | 456e165 | 2010-02-18 14:45:33 +0000 | [diff] [blame] | 4488 | >>> ExtendedContext.logical_and(110, 1101) |
| 4489 | Decimal('100') |
| 4490 | >>> ExtendedContext.logical_and(Decimal(110), 1101) |
| 4491 | Decimal('100') |
| 4492 | >>> ExtendedContext.logical_and(110, Decimal(1101)) |
| 4493 | Decimal('100') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4494 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4495 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4496 | return a.logical_and(b, context=self) |
| 4497 | |
| 4498 | def logical_invert(self, a): |
| 4499 | """Invert all the digits in the operand. |
| 4500 | |
| 4501 | The operand must be a logical number. |
| 4502 | |
| 4503 | >>> ExtendedContext.logical_invert(Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4504 | Decimal('111111111') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4505 | >>> ExtendedContext.logical_invert(Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4506 | Decimal('111111110') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4507 | >>> ExtendedContext.logical_invert(Decimal('111111111')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4508 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4509 | >>> ExtendedContext.logical_invert(Decimal('101010101')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4510 | Decimal('10101010') |
Mark Dickinson | 456e165 | 2010-02-18 14:45:33 +0000 | [diff] [blame] | 4511 | >>> ExtendedContext.logical_invert(1101) |
| 4512 | Decimal('111110010') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4513 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4514 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4515 | return a.logical_invert(context=self) |
| 4516 | |
| 4517 | def logical_or(self, a, b): |
| 4518 | """Applies the logical operation 'or' between each operand's digits. |
| 4519 | |
| 4520 | The operands must be both logical numbers. |
| 4521 | |
| 4522 | >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4523 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4524 | >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4525 | Decimal('1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4526 | >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4527 | Decimal('1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4528 | >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4529 | Decimal('1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4530 | >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4531 | Decimal('1110') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4532 | >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4533 | Decimal('1110') |
Mark Dickinson | 456e165 | 2010-02-18 14:45:33 +0000 | [diff] [blame] | 4534 | >>> ExtendedContext.logical_or(110, 1101) |
| 4535 | Decimal('1111') |
| 4536 | >>> ExtendedContext.logical_or(Decimal(110), 1101) |
| 4537 | Decimal('1111') |
| 4538 | >>> ExtendedContext.logical_or(110, Decimal(1101)) |
| 4539 | Decimal('1111') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4540 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4541 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4542 | return a.logical_or(b, context=self) |
| 4543 | |
| 4544 | def logical_xor(self, a, b): |
| 4545 | """Applies the logical operation 'xor' between each operand's digits. |
| 4546 | |
| 4547 | The operands must be both logical numbers. |
| 4548 | |
| 4549 | >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4550 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4551 | >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4552 | Decimal('1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4553 | >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4554 | Decimal('1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4555 | >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4556 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4557 | >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4558 | Decimal('110') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4559 | >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4560 | Decimal('1101') |
Mark Dickinson | 456e165 | 2010-02-18 14:45:33 +0000 | [diff] [blame] | 4561 | >>> ExtendedContext.logical_xor(110, 1101) |
| 4562 | Decimal('1011') |
| 4563 | >>> ExtendedContext.logical_xor(Decimal(110), 1101) |
| 4564 | Decimal('1011') |
| 4565 | >>> ExtendedContext.logical_xor(110, Decimal(1101)) |
| 4566 | Decimal('1011') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4567 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4568 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4569 | return a.logical_xor(b, context=self) |
| 4570 | |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4571 | def max(self, a, b): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4572 | """max compares two values numerically and returns the maximum. |
| 4573 | |
| 4574 | If either operand is a NaN then the general rules apply. |
Andrew M. Kuchling | c8acc88 | 2008-01-16 00:32:03 +0000 | [diff] [blame] | 4575 | Otherwise, the operands are compared as though by the compare |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 4576 | operation. If they are numerically equal then the left-hand operand |
| 4577 | is chosen as the result. Otherwise the maximum (closer to positive |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4578 | infinity) of the two operands is chosen as the result. |
| 4579 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4580 | >>> ExtendedContext.max(Decimal('3'), Decimal('2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4581 | Decimal('3') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4582 | >>> ExtendedContext.max(Decimal('-10'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4583 | Decimal('3') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4584 | >>> ExtendedContext.max(Decimal('1.0'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4585 | Decimal('1') |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 4586 | >>> ExtendedContext.max(Decimal('7'), Decimal('NaN')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4587 | Decimal('7') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4588 | >>> ExtendedContext.max(1, 2) |
| 4589 | Decimal('2') |
| 4590 | >>> ExtendedContext.max(Decimal(1), 2) |
| 4591 | Decimal('2') |
| 4592 | >>> ExtendedContext.max(1, Decimal(2)) |
| 4593 | Decimal('2') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4594 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4595 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4596 | return a.max(b, context=self) |
| 4597 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4598 | def max_mag(self, a, b): |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4599 | """Compares the values numerically with their sign ignored. |
| 4600 | |
| 4601 | >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN')) |
| 4602 | Decimal('7') |
| 4603 | >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10')) |
| 4604 | Decimal('-10') |
| 4605 | >>> ExtendedContext.max_mag(1, -2) |
| 4606 | Decimal('-2') |
| 4607 | >>> ExtendedContext.max_mag(Decimal(1), -2) |
| 4608 | Decimal('-2') |
| 4609 | >>> ExtendedContext.max_mag(1, Decimal(-2)) |
| 4610 | Decimal('-2') |
| 4611 | """ |
| 4612 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4613 | return a.max_mag(b, context=self) |
| 4614 | |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4615 | def min(self, a, b): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4616 | """min compares two values numerically and returns the minimum. |
| 4617 | |
| 4618 | If either operand is a NaN then the general rules apply. |
Andrew M. Kuchling | c8acc88 | 2008-01-16 00:32:03 +0000 | [diff] [blame] | 4619 | Otherwise, the operands are compared as though by the compare |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 4620 | operation. If they are numerically equal then the left-hand operand |
| 4621 | is chosen as the result. Otherwise the minimum (closer to negative |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4622 | infinity) of the two operands is chosen as the result. |
| 4623 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4624 | >>> ExtendedContext.min(Decimal('3'), Decimal('2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4625 | Decimal('2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4626 | >>> ExtendedContext.min(Decimal('-10'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4627 | Decimal('-10') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4628 | >>> ExtendedContext.min(Decimal('1.0'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4629 | Decimal('1.0') |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 4630 | >>> ExtendedContext.min(Decimal('7'), Decimal('NaN')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4631 | Decimal('7') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4632 | >>> ExtendedContext.min(1, 2) |
| 4633 | Decimal('1') |
| 4634 | >>> ExtendedContext.min(Decimal(1), 2) |
| 4635 | Decimal('1') |
| 4636 | >>> ExtendedContext.min(1, Decimal(29)) |
| 4637 | Decimal('1') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4638 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4639 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4640 | return a.min(b, context=self) |
| 4641 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4642 | def min_mag(self, a, b): |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4643 | """Compares the values numerically with their sign ignored. |
| 4644 | |
| 4645 | >>> ExtendedContext.min_mag(Decimal('3'), Decimal('-2')) |
| 4646 | Decimal('-2') |
| 4647 | >>> ExtendedContext.min_mag(Decimal('-3'), Decimal('NaN')) |
| 4648 | Decimal('-3') |
| 4649 | >>> ExtendedContext.min_mag(1, -2) |
| 4650 | Decimal('1') |
| 4651 | >>> ExtendedContext.min_mag(Decimal(1), -2) |
| 4652 | Decimal('1') |
| 4653 | >>> ExtendedContext.min_mag(1, Decimal(-2)) |
| 4654 | Decimal('1') |
| 4655 | """ |
| 4656 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4657 | return a.min_mag(b, context=self) |
| 4658 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4659 | def minus(self, a): |
| 4660 | """Minus corresponds to unary prefix minus in Python. |
| 4661 | |
| 4662 | The operation is evaluated using the same rules as subtract; the |
| 4663 | operation minus(a) is calculated as subtract('0', a) where the '0' |
| 4664 | has the same exponent as the operand. |
| 4665 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4666 | >>> ExtendedContext.minus(Decimal('1.3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4667 | Decimal('-1.3') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4668 | >>> ExtendedContext.minus(Decimal('-1.3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4669 | Decimal('1.3') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4670 | >>> ExtendedContext.minus(1) |
| 4671 | Decimal('-1') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4672 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4673 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4674 | return a.__neg__(context=self) |
| 4675 | |
| 4676 | def multiply(self, a, b): |
| 4677 | """multiply multiplies two operands. |
| 4678 | |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 4679 | If either operand is a special value then the general rules apply. |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4680 | Otherwise, the operands are multiplied together |
| 4681 | ('long multiplication'), resulting in a number which may be as long as |
| 4682 | the sum of the lengths of the two operands. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4683 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4684 | >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4685 | Decimal('3.60') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4686 | >>> ExtendedContext.multiply(Decimal('7'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4687 | Decimal('21') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4688 | >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4689 | Decimal('0.72') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4690 | >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4691 | Decimal('-0.0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4692 | >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4693 | Decimal('4.28135971E+11') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4694 | >>> ExtendedContext.multiply(7, 7) |
| 4695 | Decimal('49') |
| 4696 | >>> ExtendedContext.multiply(Decimal(7), 7) |
| 4697 | Decimal('49') |
| 4698 | >>> ExtendedContext.multiply(7, Decimal(7)) |
| 4699 | Decimal('49') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4700 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4701 | a = _convert_other(a, raiseit=True) |
| 4702 | r = a.__mul__(b, context=self) |
| 4703 | if r is NotImplemented: |
| 4704 | raise TypeError("Unable to convert %s to Decimal" % b) |
| 4705 | else: |
| 4706 | return r |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4707 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4708 | def next_minus(self, a): |
| 4709 | """Returns the largest representable number smaller than a. |
| 4710 | |
| 4711 | >>> c = ExtendedContext.copy() |
| 4712 | >>> c.Emin = -999 |
| 4713 | >>> c.Emax = 999 |
| 4714 | >>> ExtendedContext.next_minus(Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4715 | Decimal('0.999999999') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4716 | >>> c.next_minus(Decimal('1E-1007')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4717 | Decimal('0E-1007') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4718 | >>> ExtendedContext.next_minus(Decimal('-1.00000003')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4719 | Decimal('-1.00000004') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4720 | >>> c.next_minus(Decimal('Infinity')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4721 | Decimal('9.99999999E+999') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4722 | >>> c.next_minus(1) |
| 4723 | Decimal('0.999999999') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4724 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4725 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4726 | return a.next_minus(context=self) |
| 4727 | |
| 4728 | def next_plus(self, a): |
| 4729 | """Returns the smallest representable number larger than a. |
| 4730 | |
| 4731 | >>> c = ExtendedContext.copy() |
| 4732 | >>> c.Emin = -999 |
| 4733 | >>> c.Emax = 999 |
| 4734 | >>> ExtendedContext.next_plus(Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4735 | Decimal('1.00000001') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4736 | >>> c.next_plus(Decimal('-1E-1007')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4737 | Decimal('-0E-1007') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4738 | >>> ExtendedContext.next_plus(Decimal('-1.00000003')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4739 | Decimal('-1.00000002') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4740 | >>> c.next_plus(Decimal('-Infinity')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4741 | Decimal('-9.99999999E+999') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4742 | >>> c.next_plus(1) |
| 4743 | Decimal('1.00000001') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4744 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4745 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4746 | return a.next_plus(context=self) |
| 4747 | |
| 4748 | def next_toward(self, a, b): |
| 4749 | """Returns the number closest to a, in direction towards b. |
| 4750 | |
| 4751 | The result is the closest representable number from the first |
| 4752 | operand (but not the first operand) that is in the direction |
| 4753 | towards the second operand, unless the operands have the same |
| 4754 | value. |
| 4755 | |
| 4756 | >>> c = ExtendedContext.copy() |
| 4757 | >>> c.Emin = -999 |
| 4758 | >>> c.Emax = 999 |
| 4759 | >>> c.next_toward(Decimal('1'), Decimal('2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4760 | Decimal('1.00000001') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4761 | >>> c.next_toward(Decimal('-1E-1007'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4762 | Decimal('-0E-1007') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4763 | >>> c.next_toward(Decimal('-1.00000003'), Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4764 | Decimal('-1.00000002') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4765 | >>> c.next_toward(Decimal('1'), Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4766 | Decimal('0.999999999') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4767 | >>> c.next_toward(Decimal('1E-1007'), Decimal('-100')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4768 | Decimal('0E-1007') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4769 | >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4770 | Decimal('-1.00000004') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4771 | >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4772 | Decimal('-0.00') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4773 | >>> c.next_toward(0, 1) |
| 4774 | Decimal('1E-1007') |
| 4775 | >>> c.next_toward(Decimal(0), 1) |
| 4776 | Decimal('1E-1007') |
| 4777 | >>> c.next_toward(0, Decimal(1)) |
| 4778 | Decimal('1E-1007') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4779 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4780 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4781 | return a.next_toward(b, context=self) |
| 4782 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4783 | def normalize(self, a): |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 4784 | """normalize reduces an operand to its simplest form. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4785 | |
| 4786 | Essentially a plus operation with all trailing zeros removed from the |
| 4787 | result. |
| 4788 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4789 | >>> ExtendedContext.normalize(Decimal('2.1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4790 | Decimal('2.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4791 | >>> ExtendedContext.normalize(Decimal('-2.0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4792 | Decimal('-2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4793 | >>> ExtendedContext.normalize(Decimal('1.200')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4794 | Decimal('1.2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4795 | >>> ExtendedContext.normalize(Decimal('-120')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4796 | Decimal('-1.2E+2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4797 | >>> ExtendedContext.normalize(Decimal('120.00')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4798 | Decimal('1.2E+2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4799 | >>> ExtendedContext.normalize(Decimal('0.00')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4800 | Decimal('0') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4801 | >>> ExtendedContext.normalize(6) |
| 4802 | Decimal('6') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4803 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4804 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4805 | return a.normalize(context=self) |
| 4806 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4807 | def number_class(self, a): |
| 4808 | """Returns an indication of the class of the operand. |
| 4809 | |
| 4810 | The class is one of the following strings: |
| 4811 | -sNaN |
| 4812 | -NaN |
| 4813 | -Infinity |
| 4814 | -Normal |
| 4815 | -Subnormal |
| 4816 | -Zero |
| 4817 | +Zero |
| 4818 | +Subnormal |
| 4819 | +Normal |
| 4820 | +Infinity |
| 4821 | |
| 4822 | >>> c = Context(ExtendedContext) |
| 4823 | >>> c.Emin = -999 |
| 4824 | >>> c.Emax = 999 |
| 4825 | >>> c.number_class(Decimal('Infinity')) |
| 4826 | '+Infinity' |
| 4827 | >>> c.number_class(Decimal('1E-10')) |
| 4828 | '+Normal' |
| 4829 | >>> c.number_class(Decimal('2.50')) |
| 4830 | '+Normal' |
| 4831 | >>> c.number_class(Decimal('0.1E-999')) |
| 4832 | '+Subnormal' |
| 4833 | >>> c.number_class(Decimal('0')) |
| 4834 | '+Zero' |
| 4835 | >>> c.number_class(Decimal('-0')) |
| 4836 | '-Zero' |
| 4837 | >>> c.number_class(Decimal('-0.1E-999')) |
| 4838 | '-Subnormal' |
| 4839 | >>> c.number_class(Decimal('-1E-10')) |
| 4840 | '-Normal' |
| 4841 | >>> c.number_class(Decimal('-2.50')) |
| 4842 | '-Normal' |
| 4843 | >>> c.number_class(Decimal('-Infinity')) |
| 4844 | '-Infinity' |
| 4845 | >>> c.number_class(Decimal('NaN')) |
| 4846 | 'NaN' |
| 4847 | >>> c.number_class(Decimal('-NaN')) |
| 4848 | 'NaN' |
| 4849 | >>> c.number_class(Decimal('sNaN')) |
| 4850 | 'sNaN' |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4851 | >>> c.number_class(123) |
| 4852 | '+Normal' |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4853 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4854 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4855 | return a.number_class(context=self) |
| 4856 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4857 | def plus(self, a): |
| 4858 | """Plus corresponds to unary prefix plus in Python. |
| 4859 | |
| 4860 | The operation is evaluated using the same rules as add; the |
| 4861 | operation plus(a) is calculated as add('0', a) where the '0' |
| 4862 | has the same exponent as the operand. |
| 4863 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4864 | >>> ExtendedContext.plus(Decimal('1.3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4865 | Decimal('1.3') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4866 | >>> ExtendedContext.plus(Decimal('-1.3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4867 | Decimal('-1.3') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4868 | >>> ExtendedContext.plus(-1) |
| 4869 | Decimal('-1') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4870 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4871 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4872 | return a.__pos__(context=self) |
| 4873 | |
| 4874 | def power(self, a, b, modulo=None): |
| 4875 | """Raises a to the power of b, to modulo if given. |
| 4876 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4877 | With two arguments, compute a**b. If a is negative then b |
| 4878 | must be integral. The result will be inexact unless b is |
| 4879 | integral and the result is finite and can be expressed exactly |
| 4880 | in 'precision' digits. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4881 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4882 | With three arguments, compute (a**b) % modulo. For the |
| 4883 | three argument form, the following restrictions on the |
| 4884 | arguments hold: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4885 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4886 | - all three arguments must be integral |
| 4887 | - b must be nonnegative |
| 4888 | - at least one of a or b must be nonzero |
| 4889 | - modulo must be nonzero and have at most 'precision' digits |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4890 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4891 | The result of pow(a, b, modulo) is identical to the result |
| 4892 | that would be obtained by computing (a**b) % modulo with |
| 4893 | unbounded precision, but is computed more efficiently. It is |
| 4894 | always exact. |
| 4895 | |
| 4896 | >>> c = ExtendedContext.copy() |
| 4897 | >>> c.Emin = -999 |
| 4898 | >>> c.Emax = 999 |
| 4899 | >>> c.power(Decimal('2'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4900 | Decimal('8') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4901 | >>> c.power(Decimal('-2'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4902 | Decimal('-8') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4903 | >>> c.power(Decimal('2'), Decimal('-3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4904 | Decimal('0.125') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4905 | >>> c.power(Decimal('1.7'), Decimal('8')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4906 | Decimal('69.7575744') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4907 | >>> c.power(Decimal('10'), Decimal('0.301029996')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4908 | Decimal('2.00000000') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4909 | >>> c.power(Decimal('Infinity'), Decimal('-1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4910 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4911 | >>> c.power(Decimal('Infinity'), Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4912 | Decimal('1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4913 | >>> c.power(Decimal('Infinity'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4914 | Decimal('Infinity') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4915 | >>> c.power(Decimal('-Infinity'), Decimal('-1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4916 | Decimal('-0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4917 | >>> c.power(Decimal('-Infinity'), Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4918 | Decimal('1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4919 | >>> c.power(Decimal('-Infinity'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4920 | Decimal('-Infinity') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4921 | >>> c.power(Decimal('-Infinity'), Decimal('2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4922 | Decimal('Infinity') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4923 | >>> c.power(Decimal('0'), Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4924 | Decimal('NaN') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4925 | |
| 4926 | >>> c.power(Decimal('3'), Decimal('7'), Decimal('16')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4927 | Decimal('11') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4928 | >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4929 | Decimal('-11') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4930 | >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4931 | Decimal('1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4932 | >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4933 | Decimal('11') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4934 | >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4935 | Decimal('11729830') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4936 | >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4937 | Decimal('-0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4938 | >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4939 | Decimal('1') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4940 | >>> ExtendedContext.power(7, 7) |
| 4941 | Decimal('823543') |
| 4942 | >>> ExtendedContext.power(Decimal(7), 7) |
| 4943 | Decimal('823543') |
| 4944 | >>> ExtendedContext.power(7, Decimal(7), 2) |
| 4945 | Decimal('1') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4946 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 4947 | a = _convert_other(a, raiseit=True) |
| 4948 | r = a.__pow__(b, modulo, context=self) |
| 4949 | if r is NotImplemented: |
| 4950 | raise TypeError("Unable to convert %s to Decimal" % b) |
| 4951 | else: |
| 4952 | return r |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4953 | |
| 4954 | def quantize(self, a, b): |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 4955 | """Returns a value equal to 'a' (rounded), having the exponent of 'b'. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4956 | |
| 4957 | 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] | 4958 | operand. It may be rounded using the current rounding setting (if the |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4959 | exponent is being increased), multiplied by a positive power of ten (if |
| 4960 | the exponent is being decreased), or is unchanged (if the exponent is |
| 4961 | already equal to that of the right-hand operand). |
| 4962 | |
| 4963 | Unlike other operations, if the length of the coefficient after the |
| 4964 | quantize operation would be greater than precision then an Invalid |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 4965 | operation condition is raised. This guarantees that, unless there is |
| 4966 | 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] | 4967 | equal to that of the right-hand operand. |
| 4968 | |
| 4969 | Also unlike other operations, quantize will never raise Underflow, even |
| 4970 | if the result is subnormal and inexact. |
| 4971 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4972 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4973 | Decimal('2.170') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4974 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4975 | Decimal('2.17') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4976 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4977 | Decimal('2.2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4978 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4979 | Decimal('2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4980 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4981 | Decimal('0E+1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4982 | >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4983 | Decimal('-Infinity') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4984 | >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4985 | Decimal('NaN') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4986 | >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4987 | Decimal('-0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4988 | >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4989 | Decimal('-0E+5') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4990 | >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4991 | Decimal('NaN') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4992 | >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4993 | Decimal('NaN') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4994 | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4995 | Decimal('217.0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4996 | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4997 | Decimal('217') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4998 | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4999 | Decimal('2.2E+2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5000 | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5001 | Decimal('2E+2') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 5002 | >>> ExtendedContext.quantize(1, 2) |
| 5003 | Decimal('1') |
| 5004 | >>> ExtendedContext.quantize(Decimal(1), 2) |
| 5005 | Decimal('1') |
| 5006 | >>> ExtendedContext.quantize(1, Decimal(2)) |
| 5007 | Decimal('1') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5008 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 5009 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5010 | return a.quantize(b, context=self) |
| 5011 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5012 | def radix(self): |
| 5013 | """Just returns 10, as this is Decimal, :) |
| 5014 | |
| 5015 | >>> ExtendedContext.radix() |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5016 | Decimal('10') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5017 | """ |
| 5018 | return Decimal(10) |
| 5019 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5020 | def remainder(self, a, b): |
| 5021 | """Returns the remainder from integer division. |
| 5022 | |
| 5023 | The result is the residue of the dividend after the operation of |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 5024 | calculating integer division as described for divide-integer, rounded |
Neal Norwitz | 0d4c06e | 2007-04-25 06:30:05 +0000 | [diff] [blame] | 5025 | to precision digits if necessary. The sign of the result, if |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 5026 | non-zero, is the same as that of the original dividend. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5027 | |
| 5028 | This operation will fail under the same conditions as integer division |
| 5029 | (that is, if integer division on the same two operands would fail, the |
| 5030 | remainder cannot be calculated). |
| 5031 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5032 | >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5033 | Decimal('2.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5034 | >>> ExtendedContext.remainder(Decimal('10'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5035 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5036 | >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5037 | Decimal('-1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5038 | >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5039 | Decimal('0.2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5040 | >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5041 | Decimal('0.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5042 | >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5043 | Decimal('1.0') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 5044 | >>> ExtendedContext.remainder(22, 6) |
| 5045 | Decimal('4') |
| 5046 | >>> ExtendedContext.remainder(Decimal(22), 6) |
| 5047 | Decimal('4') |
| 5048 | >>> ExtendedContext.remainder(22, Decimal(6)) |
| 5049 | Decimal('4') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5050 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 5051 | a = _convert_other(a, raiseit=True) |
| 5052 | r = a.__mod__(b, context=self) |
| 5053 | if r is NotImplemented: |
| 5054 | raise TypeError("Unable to convert %s to Decimal" % b) |
| 5055 | else: |
| 5056 | return r |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5057 | |
| 5058 | def remainder_near(self, a, b): |
| 5059 | """Returns to be "a - b * n", where n is the integer nearest the exact |
| 5060 | 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] | 5061 | 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] | 5062 | sign of a. |
| 5063 | |
| 5064 | This operation will fail under the same conditions as integer division |
| 5065 | (that is, if integer division on the same two operands would fail, the |
| 5066 | remainder cannot be calculated). |
| 5067 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5068 | >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5069 | Decimal('-0.9') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5070 | >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5071 | Decimal('-2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5072 | >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5073 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5074 | >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5075 | Decimal('-1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5076 | >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5077 | Decimal('0.2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5078 | >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5079 | Decimal('0.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5080 | >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5081 | Decimal('-0.3') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 5082 | >>> ExtendedContext.remainder_near(3, 11) |
| 5083 | Decimal('3') |
| 5084 | >>> ExtendedContext.remainder_near(Decimal(3), 11) |
| 5085 | Decimal('3') |
| 5086 | >>> ExtendedContext.remainder_near(3, Decimal(11)) |
| 5087 | Decimal('3') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5088 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 5089 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5090 | return a.remainder_near(b, context=self) |
| 5091 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5092 | def rotate(self, a, b): |
| 5093 | """Returns a rotated copy of a, b times. |
| 5094 | |
| 5095 | The coefficient of the result is a rotated copy of the digits in |
| 5096 | the coefficient of the first operand. The number of places of |
| 5097 | rotation is taken from the absolute value of the second operand, |
| 5098 | with the rotation being to the left if the second operand is |
| 5099 | positive or to the right otherwise. |
| 5100 | |
| 5101 | >>> ExtendedContext.rotate(Decimal('34'), Decimal('8')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5102 | Decimal('400000003') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5103 | >>> ExtendedContext.rotate(Decimal('12'), Decimal('9')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5104 | Decimal('12') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5105 | >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5106 | Decimal('891234567') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5107 | >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5108 | Decimal('123456789') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5109 | >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5110 | Decimal('345678912') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 5111 | >>> ExtendedContext.rotate(1333333, 1) |
| 5112 | Decimal('13333330') |
| 5113 | >>> ExtendedContext.rotate(Decimal(1333333), 1) |
| 5114 | Decimal('13333330') |
| 5115 | >>> ExtendedContext.rotate(1333333, Decimal(1)) |
| 5116 | Decimal('13333330') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5117 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 5118 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5119 | return a.rotate(b, context=self) |
| 5120 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5121 | def same_quantum(self, a, b): |
| 5122 | """Returns True if the two operands have the same exponent. |
| 5123 | |
| 5124 | The result is never affected by either the sign or the coefficient of |
| 5125 | either operand. |
| 5126 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5127 | >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5128 | False |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5129 | >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5130 | True |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5131 | >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5132 | False |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5133 | >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5134 | True |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 5135 | >>> ExtendedContext.same_quantum(10000, -1) |
| 5136 | True |
| 5137 | >>> ExtendedContext.same_quantum(Decimal(10000), -1) |
| 5138 | True |
| 5139 | >>> ExtendedContext.same_quantum(10000, Decimal(-1)) |
| 5140 | True |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5141 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 5142 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5143 | return a.same_quantum(b) |
| 5144 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5145 | def scaleb (self, a, b): |
| 5146 | """Returns the first operand after adding the second value its exp. |
| 5147 | |
| 5148 | >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5149 | Decimal('0.0750') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5150 | >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5151 | Decimal('7.50') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5152 | >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5153 | Decimal('7.50E+3') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 5154 | >>> ExtendedContext.scaleb(1, 4) |
| 5155 | Decimal('1E+4') |
| 5156 | >>> ExtendedContext.scaleb(Decimal(1), 4) |
| 5157 | Decimal('1E+4') |
| 5158 | >>> ExtendedContext.scaleb(1, Decimal(4)) |
| 5159 | Decimal('1E+4') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5160 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 5161 | a = _convert_other(a, raiseit=True) |
| 5162 | return a.scaleb(b, context=self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5163 | |
| 5164 | def shift(self, a, b): |
| 5165 | """Returns a shifted copy of a, b times. |
| 5166 | |
| 5167 | The coefficient of the result is a shifted copy of the digits |
| 5168 | in the coefficient of the first operand. The number of places |
| 5169 | to shift is taken from the absolute value of the second operand, |
| 5170 | with the shift being to the left if the second operand is |
| 5171 | positive or to the right otherwise. Digits shifted into the |
| 5172 | coefficient are zeros. |
| 5173 | |
| 5174 | >>> ExtendedContext.shift(Decimal('34'), Decimal('8')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5175 | Decimal('400000000') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5176 | >>> ExtendedContext.shift(Decimal('12'), Decimal('9')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5177 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5178 | >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5179 | Decimal('1234567') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5180 | >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5181 | Decimal('123456789') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5182 | >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5183 | Decimal('345678900') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 5184 | >>> ExtendedContext.shift(88888888, 2) |
| 5185 | Decimal('888888800') |
| 5186 | >>> ExtendedContext.shift(Decimal(88888888), 2) |
| 5187 | Decimal('888888800') |
| 5188 | >>> ExtendedContext.shift(88888888, Decimal(2)) |
| 5189 | Decimal('888888800') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5190 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 5191 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5192 | return a.shift(b, context=self) |
| 5193 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5194 | def sqrt(self, a): |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 5195 | """Square root of a non-negative number to context precision. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5196 | |
| 5197 | If the result must be inexact, it is rounded using the round-half-even |
| 5198 | algorithm. |
| 5199 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5200 | >>> ExtendedContext.sqrt(Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5201 | Decimal('0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5202 | >>> ExtendedContext.sqrt(Decimal('-0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5203 | Decimal('-0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5204 | >>> ExtendedContext.sqrt(Decimal('0.39')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5205 | Decimal('0.624499800') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5206 | >>> ExtendedContext.sqrt(Decimal('100')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5207 | Decimal('10') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5208 | >>> ExtendedContext.sqrt(Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5209 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5210 | >>> ExtendedContext.sqrt(Decimal('1.0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5211 | Decimal('1.0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5212 | >>> ExtendedContext.sqrt(Decimal('1.00')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5213 | Decimal('1.0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5214 | >>> ExtendedContext.sqrt(Decimal('7')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5215 | Decimal('2.64575131') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5216 | >>> ExtendedContext.sqrt(Decimal('10')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5217 | Decimal('3.16227766') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 5218 | >>> ExtendedContext.sqrt(2) |
| 5219 | Decimal('1.41421356') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5220 | >>> ExtendedContext.prec |
Raymond Hettinger | 6ea4845 | 2004-07-03 12:26:21 +0000 | [diff] [blame] | 5221 | 9 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5222 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 5223 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5224 | return a.sqrt(context=self) |
| 5225 | |
| 5226 | def subtract(self, a, b): |
Georg Brandl | f33d01d | 2005-08-22 19:35:18 +0000 | [diff] [blame] | 5227 | """Return the difference between the two operands. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5228 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5229 | >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5230 | Decimal('0.23') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5231 | >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5232 | Decimal('0.00') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5233 | >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5234 | Decimal('-0.77') |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 5235 | >>> ExtendedContext.subtract(8, 5) |
| 5236 | Decimal('3') |
| 5237 | >>> ExtendedContext.subtract(Decimal(8), 5) |
| 5238 | Decimal('3') |
| 5239 | >>> ExtendedContext.subtract(8, Decimal(5)) |
| 5240 | Decimal('3') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5241 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 5242 | a = _convert_other(a, raiseit=True) |
| 5243 | r = a.__sub__(b, context=self) |
| 5244 | if r is NotImplemented: |
| 5245 | raise TypeError("Unable to convert %s to Decimal" % b) |
| 5246 | else: |
| 5247 | return r |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5248 | |
| 5249 | def to_eng_string(self, a): |
| 5250 | """Converts a number to a string, using scientific notation. |
| 5251 | |
| 5252 | The operation is not affected by the context. |
| 5253 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 5254 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5255 | return a.to_eng_string(context=self) |
| 5256 | |
| 5257 | def to_sci_string(self, a): |
| 5258 | """Converts a number to a string, using scientific notation. |
| 5259 | |
| 5260 | The operation is not affected by the context. |
| 5261 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 5262 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5263 | return a.__str__(context=self) |
| 5264 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5265 | def to_integral_exact(self, a): |
| 5266 | """Rounds to an integer. |
| 5267 | |
| 5268 | When the operand has a negative exponent, the result is the same |
| 5269 | as using the quantize() operation using the given operand as the |
| 5270 | left-hand-operand, 1E+0 as the right-hand-operand, and the precision |
| 5271 | of the operand as the precision setting; Inexact and Rounded flags |
| 5272 | are allowed in this operation. The rounding mode is taken from the |
| 5273 | context. |
| 5274 | |
| 5275 | >>> ExtendedContext.to_integral_exact(Decimal('2.1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5276 | Decimal('2') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5277 | >>> ExtendedContext.to_integral_exact(Decimal('100')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5278 | Decimal('100') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5279 | >>> ExtendedContext.to_integral_exact(Decimal('100.0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5280 | Decimal('100') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5281 | >>> ExtendedContext.to_integral_exact(Decimal('101.5')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5282 | Decimal('102') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5283 | >>> ExtendedContext.to_integral_exact(Decimal('-101.5')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5284 | Decimal('-102') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5285 | >>> ExtendedContext.to_integral_exact(Decimal('10E+5')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5286 | Decimal('1.0E+6') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5287 | >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5288 | Decimal('7.89E+77') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5289 | >>> ExtendedContext.to_integral_exact(Decimal('-Inf')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5290 | Decimal('-Infinity') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5291 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 5292 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5293 | return a.to_integral_exact(context=self) |
| 5294 | |
| 5295 | def to_integral_value(self, a): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5296 | """Rounds to an integer. |
| 5297 | |
| 5298 | When the operand has a negative exponent, the result is the same |
| 5299 | as using the quantize() operation using the given operand as the |
| 5300 | left-hand-operand, 1E+0 as the right-hand-operand, and the precision |
| 5301 | of the operand as the precision setting, except that no flags will |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 5302 | be set. The rounding mode is taken from the context. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5303 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5304 | >>> ExtendedContext.to_integral_value(Decimal('2.1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5305 | Decimal('2') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5306 | >>> ExtendedContext.to_integral_value(Decimal('100')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5307 | Decimal('100') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5308 | >>> ExtendedContext.to_integral_value(Decimal('100.0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5309 | Decimal('100') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5310 | >>> ExtendedContext.to_integral_value(Decimal('101.5')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5311 | Decimal('102') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5312 | >>> ExtendedContext.to_integral_value(Decimal('-101.5')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5313 | Decimal('-102') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5314 | >>> ExtendedContext.to_integral_value(Decimal('10E+5')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5315 | Decimal('1.0E+6') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5316 | >>> ExtendedContext.to_integral_value(Decimal('7.89E+77')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5317 | Decimal('7.89E+77') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5318 | >>> ExtendedContext.to_integral_value(Decimal('-Inf')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 5319 | Decimal('-Infinity') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5320 | """ |
Mark Dickinson | 6d8effb | 2010-02-18 14:27:02 +0000 | [diff] [blame] | 5321 | a = _convert_other(a, raiseit=True) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5322 | return a.to_integral_value(context=self) |
| 5323 | |
| 5324 | # the method name changed, but we provide also the old one, for compatibility |
| 5325 | to_integral = to_integral_value |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5326 | |
| 5327 | class _WorkRep(object): |
| 5328 | __slots__ = ('sign','int','exp') |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 5329 | # sign: 0 or 1 |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5330 | # int: int or long |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5331 | # exp: None, int, or string |
| 5332 | |
| 5333 | def __init__(self, value=None): |
| 5334 | if value is None: |
| 5335 | self.sign = None |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5336 | self.int = 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5337 | self.exp = None |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 5338 | elif isinstance(value, Decimal): |
| 5339 | self.sign = value._sign |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 5340 | self.int = int(value._int) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5341 | self.exp = value._exp |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 5342 | else: |
| 5343 | # assert isinstance(value, tuple) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5344 | self.sign = value[0] |
| 5345 | self.int = value[1] |
| 5346 | self.exp = value[2] |
| 5347 | |
| 5348 | def __repr__(self): |
| 5349 | return "(%r, %r, %r)" % (self.sign, self.int, self.exp) |
| 5350 | |
| 5351 | __str__ = __repr__ |
| 5352 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5353 | |
| 5354 | |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 5355 | def _normalize(op1, op2, prec = 0): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5356 | """Normalizes op1, op2 to have the same exp and length of coefficient. |
| 5357 | |
| 5358 | Done during addition. |
| 5359 | """ |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5360 | if op1.exp < op2.exp: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5361 | tmp = op2 |
| 5362 | other = op1 |
| 5363 | else: |
| 5364 | tmp = op1 |
| 5365 | other = op2 |
| 5366 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5367 | # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1). |
| 5368 | # Then adding 10**exp to tmp has the same effect (after rounding) |
| 5369 | # as adding any positive quantity smaller than 10**exp; similarly |
| 5370 | # for subtraction. So if other is smaller than 10**exp we replace |
| 5371 | # 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] | 5372 | tmp_len = len(str(tmp.int)) |
| 5373 | other_len = len(str(other.int)) |
| 5374 | exp = tmp.exp + min(-1, tmp_len - prec - 2) |
| 5375 | if other_len + other.exp - 1 < exp: |
| 5376 | other.int = 1 |
| 5377 | other.exp = exp |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5378 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5379 | tmp.int *= 10 ** (tmp.exp - other.exp) |
| 5380 | tmp.exp = other.exp |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5381 | return op1, op2 |
| 5382 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5383 | ##### Integer arithmetic functions used by ln, log10, exp and __pow__ ##### |
| 5384 | |
| 5385 | # This function from Tim Peters was taken from here: |
| 5386 | # http://mail.python.org/pipermail/python-list/1999-July/007758.html |
| 5387 | # The correction being in the function definition is for speed, and |
| 5388 | # the whole function is not resolved with math.log because of avoiding |
| 5389 | # the use of floats. |
| 5390 | def _nbits(n, correction = { |
| 5391 | '0': 4, '1': 3, '2': 2, '3': 2, |
| 5392 | '4': 1, '5': 1, '6': 1, '7': 1, |
| 5393 | '8': 0, '9': 0, 'a': 0, 'b': 0, |
| 5394 | 'c': 0, 'd': 0, 'e': 0, 'f': 0}): |
| 5395 | """Number of bits in binary representation of the positive integer n, |
| 5396 | or 0 if n == 0. |
| 5397 | """ |
| 5398 | if n < 0: |
| 5399 | raise ValueError("The argument to _nbits should be nonnegative.") |
| 5400 | hex_n = "%x" % n |
| 5401 | return 4*len(hex_n) - correction[hex_n[0]] |
| 5402 | |
| 5403 | def _sqrt_nearest(n, a): |
| 5404 | """Closest integer to the square root of the positive integer n. a is |
| 5405 | an initial approximation to the square root. Any positive integer |
| 5406 | will do for a, but the closer a is to the square root of n the |
| 5407 | faster convergence will be. |
| 5408 | |
| 5409 | """ |
| 5410 | if n <= 0 or a <= 0: |
| 5411 | raise ValueError("Both arguments to _sqrt_nearest should be positive.") |
| 5412 | |
| 5413 | b=0 |
| 5414 | while a != b: |
| 5415 | b, a = a, a--n//a>>1 |
| 5416 | return a |
| 5417 | |
| 5418 | def _rshift_nearest(x, shift): |
| 5419 | """Given an integer x and a nonnegative integer shift, return closest |
| 5420 | integer to x / 2**shift; use round-to-even in case of a tie. |
| 5421 | |
| 5422 | """ |
| 5423 | b, q = 1L << shift, x >> shift |
| 5424 | return q + (2*(x & (b-1)) + (q&1) > b) |
| 5425 | |
| 5426 | def _div_nearest(a, b): |
| 5427 | """Closest integer to a/b, a and b positive integers; rounds to even |
| 5428 | in the case of a tie. |
| 5429 | |
| 5430 | """ |
| 5431 | q, r = divmod(a, b) |
| 5432 | return q + (2*r + (q&1) > b) |
| 5433 | |
| 5434 | def _ilog(x, M, L = 8): |
| 5435 | """Integer approximation to M*log(x/M), with absolute error boundable |
| 5436 | in terms only of x/M. |
| 5437 | |
| 5438 | Given positive integers x and M, return an integer approximation to |
| 5439 | M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference |
| 5440 | between the approximation and the exact result is at most 22. For |
| 5441 | L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In |
| 5442 | both cases these are upper bounds on the error; it will usually be |
| 5443 | much smaller.""" |
| 5444 | |
| 5445 | # The basic algorithm is the following: let log1p be the function |
| 5446 | # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use |
| 5447 | # the reduction |
| 5448 | # |
| 5449 | # log1p(y) = 2*log1p(y/(1+sqrt(1+y))) |
| 5450 | # |
| 5451 | # repeatedly until the argument to log1p is small (< 2**-L in |
| 5452 | # absolute value). For small y we can use the Taylor series |
| 5453 | # expansion |
| 5454 | # |
| 5455 | # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T |
| 5456 | # |
| 5457 | # truncating at T such that y**T is small enough. The whole |
| 5458 | # computation is carried out in a form of fixed-point arithmetic, |
| 5459 | # with a real number z being represented by an integer |
| 5460 | # approximation to z*M. To avoid loss of precision, the y below |
| 5461 | # is actually an integer approximation to 2**R*y*M, where R is the |
| 5462 | # number of reductions performed so far. |
| 5463 | |
| 5464 | y = x-M |
| 5465 | # argument reduction; R = number of reductions performed |
| 5466 | R = 0 |
| 5467 | while (R <= L and long(abs(y)) << L-R >= M or |
| 5468 | R > L and abs(y) >> R-L >= M): |
| 5469 | y = _div_nearest(long(M*y) << 1, |
| 5470 | M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M)) |
| 5471 | R += 1 |
| 5472 | |
| 5473 | # Taylor series with T terms |
| 5474 | T = -int(-10*len(str(M))//(3*L)) |
| 5475 | yshift = _rshift_nearest(y, R) |
| 5476 | w = _div_nearest(M, T) |
| 5477 | for k in xrange(T-1, 0, -1): |
| 5478 | w = _div_nearest(M, k) - _div_nearest(yshift*w, M) |
| 5479 | |
| 5480 | return _div_nearest(w*y, M) |
| 5481 | |
| 5482 | def _dlog10(c, e, p): |
| 5483 | """Given integers c, e and p with c > 0, p >= 0, compute an integer |
| 5484 | approximation to 10**p * log10(c*10**e), with an absolute error of |
| 5485 | at most 1. Assumes that c*10**e is not exactly 1.""" |
| 5486 | |
| 5487 | # increase precision by 2; compensate for this by dividing |
| 5488 | # final result by 100 |
| 5489 | p += 2 |
| 5490 | |
| 5491 | # write c*10**e as d*10**f with either: |
| 5492 | # f >= 0 and 1 <= d <= 10, or |
| 5493 | # f <= 0 and 0.1 <= d <= 1. |
| 5494 | # Thus for c*10**e close to 1, f = 0 |
| 5495 | l = len(str(c)) |
| 5496 | f = e+l - (e+l >= 1) |
| 5497 | |
| 5498 | if p > 0: |
| 5499 | M = 10**p |
| 5500 | k = e+p-f |
| 5501 | if k >= 0: |
| 5502 | c *= 10**k |
| 5503 | else: |
| 5504 | c = _div_nearest(c, 10**-k) |
| 5505 | |
| 5506 | log_d = _ilog(c, M) # error < 5 + 22 = 27 |
Facundo Batista | be6c7ba | 2007-10-02 18:21:18 +0000 | [diff] [blame] | 5507 | log_10 = _log10_digits(p) # error < 1 |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5508 | log_d = _div_nearest(log_d*M, log_10) |
| 5509 | log_tenpower = f*M # exact |
| 5510 | else: |
| 5511 | log_d = 0 # error < 2.31 |
Neal Norwitz | 18aa388 | 2008-08-24 05:04:52 +0000 | [diff] [blame] | 5512 | log_tenpower = _div_nearest(f, 10**-p) # error < 0.5 |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5513 | |
| 5514 | return _div_nearest(log_tenpower+log_d, 100) |
| 5515 | |
| 5516 | def _dlog(c, e, p): |
| 5517 | """Given integers c, e and p with c > 0, compute an integer |
| 5518 | approximation to 10**p * log(c*10**e), with an absolute error of |
| 5519 | at most 1. Assumes that c*10**e is not exactly 1.""" |
| 5520 | |
| 5521 | # Increase precision by 2. The precision increase is compensated |
| 5522 | # for at the end with a division by 100. |
| 5523 | p += 2 |
| 5524 | |
| 5525 | # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10, |
| 5526 | # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e) |
| 5527 | # as 10**p * log(d) + 10**p*f * log(10). |
| 5528 | l = len(str(c)) |
| 5529 | f = e+l - (e+l >= 1) |
| 5530 | |
| 5531 | # compute approximation to 10**p*log(d), with error < 27 |
| 5532 | if p > 0: |
| 5533 | k = e+p-f |
| 5534 | if k >= 0: |
| 5535 | c *= 10**k |
| 5536 | else: |
| 5537 | c = _div_nearest(c, 10**-k) # error of <= 0.5 in c |
| 5538 | |
| 5539 | # _ilog magnifies existing error in c by a factor of at most 10 |
| 5540 | log_d = _ilog(c, 10**p) # error < 5 + 22 = 27 |
| 5541 | else: |
| 5542 | # p <= 0: just approximate the whole thing by 0; error < 2.31 |
| 5543 | log_d = 0 |
| 5544 | |
Facundo Batista | be6c7ba | 2007-10-02 18:21:18 +0000 | [diff] [blame] | 5545 | # compute approximation to f*10**p*log(10), with error < 11. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5546 | if f: |
Facundo Batista | be6c7ba | 2007-10-02 18:21:18 +0000 | [diff] [blame] | 5547 | extra = len(str(abs(f)))-1 |
| 5548 | if p + extra >= 0: |
| 5549 | # error in f * _log10_digits(p+extra) < |f| * 1 = |f| |
| 5550 | # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11 |
| 5551 | f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5552 | else: |
| 5553 | f_log_ten = 0 |
| 5554 | else: |
| 5555 | f_log_ten = 0 |
| 5556 | |
Facundo Batista | be6c7ba | 2007-10-02 18:21:18 +0000 | [diff] [blame] | 5557 | # 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] | 5558 | return _div_nearest(f_log_ten + log_d, 100) |
| 5559 | |
Facundo Batista | be6c7ba | 2007-10-02 18:21:18 +0000 | [diff] [blame] | 5560 | class _Log10Memoize(object): |
| 5561 | """Class to compute, store, and allow retrieval of, digits of the |
| 5562 | constant log(10) = 2.302585.... This constant is needed by |
| 5563 | Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__.""" |
| 5564 | def __init__(self): |
| 5565 | self.digits = "23025850929940456840179914546843642076011014886" |
| 5566 | |
| 5567 | def getdigits(self, p): |
| 5568 | """Given an integer p >= 0, return floor(10**p)*log(10). |
| 5569 | |
| 5570 | For example, self.getdigits(3) returns 2302. |
| 5571 | """ |
| 5572 | # digits are stored as a string, for quick conversion to |
| 5573 | # integer in the case that we've already computed enough |
| 5574 | # digits; the stored digits should always be correct |
| 5575 | # (truncated, not rounded to nearest). |
| 5576 | if p < 0: |
| 5577 | raise ValueError("p should be nonnegative") |
| 5578 | |
| 5579 | if p >= len(self.digits): |
| 5580 | # compute p+3, p+6, p+9, ... digits; continue until at |
| 5581 | # least one of the extra digits is nonzero |
| 5582 | extra = 3 |
| 5583 | while True: |
| 5584 | # compute p+extra digits, correct to within 1ulp |
| 5585 | M = 10**(p+extra+2) |
| 5586 | digits = str(_div_nearest(_ilog(10*M, M), 100)) |
| 5587 | if digits[-extra:] != '0'*extra: |
| 5588 | break |
| 5589 | extra += 3 |
| 5590 | # keep all reliable digits so far; remove trailing zeros |
| 5591 | # and next nonzero digit |
| 5592 | self.digits = digits.rstrip('0')[:-1] |
| 5593 | return int(self.digits[:p+1]) |
| 5594 | |
| 5595 | _log10_digits = _Log10Memoize().getdigits |
| 5596 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5597 | def _iexp(x, M, L=8): |
| 5598 | """Given integers x and M, M > 0, such that x/M is small in absolute |
| 5599 | value, compute an integer approximation to M*exp(x/M). For 0 <= |
| 5600 | x/M <= 2.4, the absolute error in the result is bounded by 60 (and |
| 5601 | is usually much smaller).""" |
| 5602 | |
| 5603 | # Algorithm: to compute exp(z) for a real number z, first divide z |
| 5604 | # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then |
| 5605 | # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor |
| 5606 | # series |
| 5607 | # |
| 5608 | # expm1(x) = x + x**2/2! + x**3/3! + ... |
| 5609 | # |
| 5610 | # Now use the identity |
| 5611 | # |
| 5612 | # expm1(2x) = expm1(x)*(expm1(x)+2) |
| 5613 | # |
| 5614 | # R times to compute the sequence expm1(z/2**R), |
| 5615 | # expm1(z/2**(R-1)), ... , exp(z/2), exp(z). |
| 5616 | |
| 5617 | # Find R such that x/2**R/M <= 2**-L |
| 5618 | R = _nbits((long(x)<<L)//M) |
| 5619 | |
| 5620 | # Taylor series. (2**L)**T > M |
| 5621 | T = -int(-10*len(str(M))//(3*L)) |
| 5622 | y = _div_nearest(x, T) |
| 5623 | Mshift = long(M)<<R |
| 5624 | for i in xrange(T-1, 0, -1): |
| 5625 | y = _div_nearest(x*(Mshift + y), Mshift * i) |
| 5626 | |
| 5627 | # Expansion |
| 5628 | for k in xrange(R-1, -1, -1): |
| 5629 | Mshift = long(M)<<(k+2) |
| 5630 | y = _div_nearest(y*(y+Mshift), Mshift) |
| 5631 | |
| 5632 | return M+y |
| 5633 | |
| 5634 | def _dexp(c, e, p): |
| 5635 | """Compute an approximation to exp(c*10**e), with p decimal places of |
| 5636 | precision. |
| 5637 | |
Facundo Batista | be6c7ba | 2007-10-02 18:21:18 +0000 | [diff] [blame] | 5638 | Returns integers d, f such that: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5639 | |
| 5640 | 10**(p-1) <= d <= 10**p, and |
| 5641 | (d-1)*10**f < exp(c*10**e) < (d+1)*10**f |
| 5642 | |
| 5643 | In other words, d*10**f is an approximation to exp(c*10**e) with p |
| 5644 | digits of precision, and with an error in d of at most 1. This is |
| 5645 | almost, but not quite, the same as the error being < 1ulp: when d |
| 5646 | = 10**(p-1) the error could be up to 10 ulp.""" |
| 5647 | |
| 5648 | # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision |
| 5649 | p += 2 |
| 5650 | |
Facundo Batista | be6c7ba | 2007-10-02 18:21:18 +0000 | [diff] [blame] | 5651 | # compute log(10) with extra precision = adjusted exponent of c*10**e |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5652 | extra = max(0, e + len(str(c)) - 1) |
| 5653 | q = p + extra |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5654 | |
Facundo Batista | be6c7ba | 2007-10-02 18:21:18 +0000 | [diff] [blame] | 5655 | # 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] | 5656 | # rounding down |
| 5657 | shift = e+q |
| 5658 | if shift >= 0: |
| 5659 | cshift = c*10**shift |
| 5660 | else: |
| 5661 | cshift = c//10**-shift |
Facundo Batista | be6c7ba | 2007-10-02 18:21:18 +0000 | [diff] [blame] | 5662 | quot, rem = divmod(cshift, _log10_digits(q)) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5663 | |
| 5664 | # reduce remainder back to original precision |
| 5665 | rem = _div_nearest(rem, 10**extra) |
| 5666 | |
| 5667 | # error in result of _iexp < 120; error after division < 0.62 |
| 5668 | return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3 |
| 5669 | |
| 5670 | def _dpower(xc, xe, yc, ye, p): |
| 5671 | """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and |
| 5672 | y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that: |
| 5673 | |
| 5674 | 10**(p-1) <= c <= 10**p, and |
| 5675 | (c-1)*10**e < x**y < (c+1)*10**e |
| 5676 | |
| 5677 | in other words, c*10**e is an approximation to x**y with p digits |
| 5678 | of precision, and with an error in c of at most 1. (This is |
| 5679 | almost, but not quite, the same as the error being < 1ulp: when c |
| 5680 | == 10**(p-1) we can only guarantee error < 10ulp.) |
| 5681 | |
| 5682 | We assume that: x is positive and not equal to 1, and y is nonzero. |
| 5683 | """ |
| 5684 | |
| 5685 | # Find b such that 10**(b-1) <= |y| <= 10**b |
| 5686 | b = len(str(abs(yc))) + ye |
| 5687 | |
| 5688 | # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point |
| 5689 | lxc = _dlog(xc, xe, p+b+1) |
| 5690 | |
| 5691 | # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1) |
| 5692 | shift = ye-b |
| 5693 | if shift >= 0: |
| 5694 | pc = lxc*yc*10**shift |
| 5695 | else: |
| 5696 | pc = _div_nearest(lxc*yc, 10**-shift) |
| 5697 | |
| 5698 | if pc == 0: |
| 5699 | # we prefer a result that isn't exactly 1; this makes it |
| 5700 | # easier to compute a correctly rounded result in __pow__ |
| 5701 | if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1: |
| 5702 | coeff, exp = 10**(p-1)+1, 1-p |
| 5703 | else: |
| 5704 | coeff, exp = 10**p-1, -p |
| 5705 | else: |
| 5706 | coeff, exp = _dexp(pc, -(p+1), p+1) |
| 5707 | coeff = _div_nearest(coeff, 10) |
| 5708 | exp += 1 |
| 5709 | |
| 5710 | return coeff, exp |
| 5711 | |
| 5712 | def _log10_lb(c, correction = { |
| 5713 | '1': 100, '2': 70, '3': 53, '4': 40, '5': 31, |
| 5714 | '6': 23, '7': 16, '8': 10, '9': 5}): |
| 5715 | """Compute a lower bound for 100*log10(c) for a positive integer c.""" |
| 5716 | if c <= 0: |
| 5717 | raise ValueError("The argument to _log10_lb should be nonnegative.") |
| 5718 | str_c = str(c) |
| 5719 | return 100*len(str_c) - correction[str_c[0]] |
| 5720 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 5721 | ##### Helper Functions #################################################### |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5722 | |
Mark Dickinson | 99d8096 | 2010-04-02 08:53:22 +0000 | [diff] [blame] | 5723 | def _convert_other(other, raiseit=False, allow_float=False): |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5724 | """Convert other to Decimal. |
| 5725 | |
| 5726 | Verifies that it's ok to use in an implicit construction. |
Mark Dickinson | 99d8096 | 2010-04-02 08:53:22 +0000 | [diff] [blame] | 5727 | If allow_float is true, allow conversion from float; this |
| 5728 | is used in the comparison methods (__eq__ and friends). |
| 5729 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5730 | """ |
| 5731 | if isinstance(other, Decimal): |
| 5732 | return other |
| 5733 | if isinstance(other, (int, long)): |
| 5734 | return Decimal(other) |
Mark Dickinson | 99d8096 | 2010-04-02 08:53:22 +0000 | [diff] [blame] | 5735 | if allow_float and isinstance(other, float): |
| 5736 | return Decimal.from_float(other) |
| 5737 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5738 | if raiseit: |
| 5739 | raise TypeError("Unable to convert %s to Decimal" % other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 5740 | return NotImplemented |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5741 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 5742 | ##### Setup Specific Contexts ############################################ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5743 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5744 | # The default context prototype used by Context() |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 5745 | # Is mutable, so that new contexts can have different default values |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5746 | |
| 5747 | DefaultContext = Context( |
Raymond Hettinger | 6ea4845 | 2004-07-03 12:26:21 +0000 | [diff] [blame] | 5748 | prec=28, rounding=ROUND_HALF_EVEN, |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 5749 | traps=[DivisionByZero, Overflow, InvalidOperation], |
| 5750 | flags=[], |
Raymond Hettinger | 99148e7 | 2004-07-14 19:56:56 +0000 | [diff] [blame] | 5751 | Emax=999999999, |
| 5752 | Emin=-999999999, |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 5753 | capitals=1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5754 | ) |
| 5755 | |
| 5756 | # Pre-made alternate contexts offered by the specification |
| 5757 | # Don't change these; the user should be able to select these |
| 5758 | # contexts and be able to reproduce results from other implementations |
| 5759 | # of the spec. |
| 5760 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5761 | BasicContext = Context( |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5762 | prec=9, rounding=ROUND_HALF_UP, |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 5763 | traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow], |
| 5764 | flags=[], |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5765 | ) |
| 5766 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5767 | ExtendedContext = Context( |
Raymond Hettinger | 6ea4845 | 2004-07-03 12:26:21 +0000 | [diff] [blame] | 5768 | prec=9, rounding=ROUND_HALF_EVEN, |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 5769 | traps=[], |
| 5770 | flags=[], |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5771 | ) |
| 5772 | |
| 5773 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 5774 | ##### crud for parsing strings ############################################# |
Mark Dickinson | 6a123cb | 2008-02-24 18:12:36 +0000 | [diff] [blame] | 5775 | # |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 5776 | # Regular expression used for parsing numeric strings. Additional |
| 5777 | # comments: |
| 5778 | # |
| 5779 | # 1. Uncomment the two '\s*' lines to allow leading and/or trailing |
| 5780 | # whitespace. But note that the specification disallows whitespace in |
| 5781 | # a numeric string. |
| 5782 | # |
| 5783 | # 2. For finite numbers (not infinities and NaNs) the body of the |
| 5784 | # number between the optional sign and the optional exponent must have |
| 5785 | # at least one decimal digit, possibly after the decimal point. The |
| 5786 | # lookahead expression '(?=\d|\.\d)' checks this. |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 5787 | |
| 5788 | import re |
Mark Dickinson | 70c3289 | 2008-07-02 09:37:01 +0000 | [diff] [blame] | 5789 | _parser = re.compile(r""" # A numeric string consists of: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 5790 | # \s* |
Mark Dickinson | 70c3289 | 2008-07-02 09:37:01 +0000 | [diff] [blame] | 5791 | (?P<sign>[-+])? # an optional sign, followed by either... |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 5792 | ( |
Mark Dickinson | 4326ad8 | 2009-08-02 10:59:36 +0000 | [diff] [blame] | 5793 | (?=\d|\.\d) # ...a number (with at least one digit) |
| 5794 | (?P<int>\d*) # having a (possibly empty) integer part |
| 5795 | (\.(?P<frac>\d*))? # followed by an optional fractional part |
| 5796 | (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or... |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 5797 | | |
Mark Dickinson | 70c3289 | 2008-07-02 09:37:01 +0000 | [diff] [blame] | 5798 | Inf(inity)? # ...an infinity, or... |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 5799 | | |
Mark Dickinson | 70c3289 | 2008-07-02 09:37:01 +0000 | [diff] [blame] | 5800 | (?P<signal>s)? # ...an (optionally signaling) |
| 5801 | NaN # NaN |
Mark Dickinson | 4326ad8 | 2009-08-02 10:59:36 +0000 | [diff] [blame] | 5802 | (?P<diag>\d*) # with (possibly empty) diagnostic info. |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 5803 | ) |
| 5804 | # \s* |
Mark Dickinson | 59bc20b | 2008-01-12 01:56:00 +0000 | [diff] [blame] | 5805 | \Z |
Mark Dickinson | 4326ad8 | 2009-08-02 10:59:36 +0000 | [diff] [blame] | 5806 | """, re.VERBOSE | re.IGNORECASE | re.UNICODE).match |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 5807 | |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 5808 | _all_zeros = re.compile('0*$').match |
| 5809 | _exact_half = re.compile('50*$').match |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 5810 | |
| 5811 | ##### PEP3101 support functions ############################################## |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 5812 | # The functions in this section have little to do with the Decimal |
| 5813 | # class, and could potentially be reused or adapted for other pure |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 5814 | # Python numeric classes that want to implement __format__ |
| 5815 | # |
| 5816 | # A format specifier for Decimal looks like: |
| 5817 | # |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 5818 | # [[fill]align][sign][0][minimumwidth][,][.precision][type] |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 5819 | |
| 5820 | _parse_format_specifier_regex = re.compile(r"""\A |
| 5821 | (?: |
| 5822 | (?P<fill>.)? |
| 5823 | (?P<align>[<>=^]) |
| 5824 | )? |
| 5825 | (?P<sign>[-+ ])? |
| 5826 | (?P<zeropad>0)? |
| 5827 | (?P<minimumwidth>(?!0)\d+)? |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 5828 | (?P<thousands_sep>,)? |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 5829 | (?:\.(?P<precision>0|(?!0)\d+))? |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 5830 | (?P<type>[eEfFgGn%])? |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 5831 | \Z |
| 5832 | """, re.VERBOSE) |
| 5833 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 5834 | del re |
| 5835 | |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 5836 | # The locale module is only needed for the 'n' format specifier. The |
| 5837 | # rest of the PEP 3101 code functions quite happily without it, so we |
| 5838 | # don't care too much if locale isn't present. |
| 5839 | try: |
| 5840 | import locale as _locale |
| 5841 | except ImportError: |
| 5842 | pass |
| 5843 | |
| 5844 | def _parse_format_specifier(format_spec, _localeconv=None): |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 5845 | """Parse and validate a format specifier. |
| 5846 | |
| 5847 | Turns a standard numeric format specifier into a dict, with the |
| 5848 | following entries: |
| 5849 | |
| 5850 | fill: fill character to pad field to minimum width |
| 5851 | align: alignment type, either '<', '>', '=' or '^' |
| 5852 | sign: either '+', '-' or ' ' |
| 5853 | minimumwidth: nonnegative integer giving minimum width |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 5854 | zeropad: boolean, indicating whether to pad with zeros |
| 5855 | thousands_sep: string to use as thousands separator, or '' |
| 5856 | grouping: grouping for thousands separators, in format |
| 5857 | used by localeconv |
| 5858 | decimal_point: string to use for decimal point |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 5859 | precision: nonnegative integer giving precision, or None |
| 5860 | type: one of the characters 'eEfFgG%', or None |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 5861 | unicode: boolean (always True for Python 3.x) |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 5862 | |
| 5863 | """ |
| 5864 | m = _parse_format_specifier_regex.match(format_spec) |
| 5865 | if m is None: |
| 5866 | raise ValueError("Invalid format specifier: " + format_spec) |
| 5867 | |
| 5868 | # get the dictionary |
| 5869 | format_dict = m.groupdict() |
| 5870 | |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 5871 | # zeropad; defaults for fill and alignment. If zero padding |
| 5872 | # is requested, the fill and align fields should be absent. |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 5873 | fill = format_dict['fill'] |
| 5874 | align = format_dict['align'] |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 5875 | format_dict['zeropad'] = (format_dict['zeropad'] is not None) |
| 5876 | if format_dict['zeropad']: |
| 5877 | if fill is not None: |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 5878 | raise ValueError("Fill character conflicts with '0'" |
| 5879 | " in format specifier: " + format_spec) |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 5880 | if align is not None: |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 5881 | raise ValueError("Alignment conflicts with '0' in " |
| 5882 | "format specifier: " + format_spec) |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 5883 | format_dict['fill'] = fill or ' ' |
Mark Dickinson | 5cfa804 | 2009-09-08 20:20:19 +0000 | [diff] [blame] | 5884 | # PEP 3101 originally specified that the default alignment should |
| 5885 | # be left; it was later agreed that right-aligned makes more sense |
| 5886 | # for numeric types. See http://bugs.python.org/issue6857. |
| 5887 | format_dict['align'] = align or '>' |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 5888 | |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 5889 | # default sign handling: '-' for negative, '' for positive |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 5890 | if format_dict['sign'] is None: |
| 5891 | format_dict['sign'] = '-' |
| 5892 | |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 5893 | # minimumwidth defaults to 0; precision remains None if not given |
| 5894 | format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0') |
| 5895 | if format_dict['precision'] is not None: |
| 5896 | format_dict['precision'] = int(format_dict['precision']) |
| 5897 | |
| 5898 | # if format type is 'g' or 'G' then a precision of 0 makes little |
| 5899 | # sense; convert it to 1. Same if format type is unspecified. |
| 5900 | if format_dict['precision'] == 0: |
Mark Dickinson | 491ea55 | 2009-09-07 16:17:41 +0000 | [diff] [blame] | 5901 | if format_dict['type'] is None or format_dict['type'] in 'gG': |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 5902 | format_dict['precision'] = 1 |
| 5903 | |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 5904 | # determine thousands separator, grouping, and decimal separator, and |
| 5905 | # add appropriate entries to format_dict |
| 5906 | if format_dict['type'] == 'n': |
| 5907 | # apart from separators, 'n' behaves just like 'g' |
| 5908 | format_dict['type'] = 'g' |
| 5909 | if _localeconv is None: |
| 5910 | _localeconv = _locale.localeconv() |
| 5911 | if format_dict['thousands_sep'] is not None: |
| 5912 | raise ValueError("Explicit thousands separator conflicts with " |
| 5913 | "'n' type in format specifier: " + format_spec) |
| 5914 | format_dict['thousands_sep'] = _localeconv['thousands_sep'] |
| 5915 | format_dict['grouping'] = _localeconv['grouping'] |
| 5916 | format_dict['decimal_point'] = _localeconv['decimal_point'] |
| 5917 | else: |
| 5918 | if format_dict['thousands_sep'] is None: |
| 5919 | format_dict['thousands_sep'] = '' |
| 5920 | format_dict['grouping'] = [3, 0] |
| 5921 | format_dict['decimal_point'] = '.' |
| 5922 | |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 5923 | # record whether return type should be str or unicode |
| 5924 | format_dict['unicode'] = isinstance(format_spec, unicode) |
| 5925 | |
| 5926 | return format_dict |
| 5927 | |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 5928 | def _format_align(sign, body, spec): |
| 5929 | """Given an unpadded, non-aligned numeric string 'body' and sign |
| 5930 | string 'sign', add padding and aligment conforming to the given |
| 5931 | format specifier dictionary 'spec' (as produced by |
| 5932 | parse_format_specifier). |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 5933 | |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 5934 | Also converts result to unicode if necessary. |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 5935 | |
| 5936 | """ |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 5937 | # how much extra space do we have to play with? |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 5938 | minimumwidth = spec['minimumwidth'] |
| 5939 | fill = spec['fill'] |
| 5940 | padding = fill*(minimumwidth - len(sign) - len(body)) |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 5941 | |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 5942 | align = spec['align'] |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 5943 | if align == '<': |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 5944 | result = sign + body + padding |
Mark Dickinson | b065e52 | 2009-03-17 18:01:03 +0000 | [diff] [blame] | 5945 | elif align == '>': |
| 5946 | result = padding + sign + body |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 5947 | elif align == '=': |
| 5948 | result = sign + padding + body |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 5949 | elif align == '^': |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 5950 | half = len(padding)//2 |
| 5951 | result = padding[:half] + sign + body + padding[half:] |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 5952 | else: |
| 5953 | raise ValueError('Unrecognised alignment field') |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 5954 | |
| 5955 | # make sure that result is unicode if necessary |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 5956 | if spec['unicode']: |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 5957 | result = unicode(result) |
| 5958 | |
| 5959 | return result |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 5960 | |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 5961 | def _group_lengths(grouping): |
| 5962 | """Convert a localeconv-style grouping into a (possibly infinite) |
| 5963 | iterable of integers representing group lengths. |
| 5964 | |
| 5965 | """ |
| 5966 | # The result from localeconv()['grouping'], and the input to this |
| 5967 | # function, should be a list of integers in one of the |
| 5968 | # following three forms: |
| 5969 | # |
| 5970 | # (1) an empty list, or |
| 5971 | # (2) nonempty list of positive integers + [0] |
| 5972 | # (3) list of positive integers + [locale.CHAR_MAX], or |
| 5973 | |
| 5974 | from itertools import chain, repeat |
| 5975 | if not grouping: |
| 5976 | return [] |
| 5977 | elif grouping[-1] == 0 and len(grouping) >= 2: |
| 5978 | return chain(grouping[:-1], repeat(grouping[-2])) |
| 5979 | elif grouping[-1] == _locale.CHAR_MAX: |
| 5980 | return grouping[:-1] |
| 5981 | else: |
| 5982 | raise ValueError('unrecognised format for grouping') |
| 5983 | |
| 5984 | def _insert_thousands_sep(digits, spec, min_width=1): |
| 5985 | """Insert thousands separators into a digit string. |
| 5986 | |
| 5987 | spec is a dictionary whose keys should include 'thousands_sep' and |
| 5988 | 'grouping'; typically it's the result of parsing the format |
| 5989 | specifier using _parse_format_specifier. |
| 5990 | |
| 5991 | The min_width keyword argument gives the minimum length of the |
| 5992 | result, which will be padded on the left with zeros if necessary. |
| 5993 | |
| 5994 | If necessary, the zero padding adds an extra '0' on the left to |
| 5995 | avoid a leading thousands separator. For example, inserting |
| 5996 | commas every three digits in '123456', with min_width=8, gives |
| 5997 | '0,123,456', even though that has length 9. |
| 5998 | |
| 5999 | """ |
| 6000 | |
| 6001 | sep = spec['thousands_sep'] |
| 6002 | grouping = spec['grouping'] |
| 6003 | |
| 6004 | groups = [] |
| 6005 | for l in _group_lengths(grouping): |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 6006 | if l <= 0: |
| 6007 | raise ValueError("group length should be positive") |
| 6008 | # max(..., 1) forces at least 1 digit to the left of a separator |
| 6009 | l = min(max(len(digits), min_width, 1), l) |
| 6010 | groups.append('0'*(l - len(digits)) + digits[-l:]) |
| 6011 | digits = digits[:-l] |
| 6012 | min_width -= l |
| 6013 | if not digits and min_width <= 0: |
| 6014 | break |
Mark Dickinson | b14514a | 2009-03-18 08:22:51 +0000 | [diff] [blame] | 6015 | min_width -= len(sep) |
Mark Dickinson | 277859d | 2009-03-17 23:03:46 +0000 | [diff] [blame] | 6016 | else: |
| 6017 | l = max(len(digits), min_width, 1) |
| 6018 | groups.append('0'*(l - len(digits)) + digits[-l:]) |
| 6019 | return sep.join(reversed(groups)) |
| 6020 | |
| 6021 | def _format_sign(is_negative, spec): |
| 6022 | """Determine sign character.""" |
| 6023 | |
| 6024 | if is_negative: |
| 6025 | return '-' |
| 6026 | elif spec['sign'] in ' +': |
| 6027 | return spec['sign'] |
| 6028 | else: |
| 6029 | return '' |
| 6030 | |
| 6031 | def _format_number(is_negative, intpart, fracpart, exp, spec): |
| 6032 | """Format a number, given the following data: |
| 6033 | |
| 6034 | is_negative: true if the number is negative, else false |
| 6035 | intpart: string of digits that must appear before the decimal point |
| 6036 | fracpart: string of digits that must come after the point |
| 6037 | exp: exponent, as an integer |
| 6038 | spec: dictionary resulting from parsing the format specifier |
| 6039 | |
| 6040 | This function uses the information in spec to: |
| 6041 | insert separators (decimal separator and thousands separators) |
| 6042 | format the sign |
| 6043 | format the exponent |
| 6044 | add trailing '%' for the '%' type |
| 6045 | zero-pad if necessary |
| 6046 | fill and align if necessary |
| 6047 | """ |
| 6048 | |
| 6049 | sign = _format_sign(is_negative, spec) |
| 6050 | |
| 6051 | if fracpart: |
| 6052 | fracpart = spec['decimal_point'] + fracpart |
| 6053 | |
| 6054 | if exp != 0 or spec['type'] in 'eE': |
| 6055 | echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']] |
| 6056 | fracpart += "{0}{1:+}".format(echar, exp) |
| 6057 | if spec['type'] == '%': |
| 6058 | fracpart += '%' |
| 6059 | |
| 6060 | if spec['zeropad']: |
| 6061 | min_width = spec['minimumwidth'] - len(fracpart) - len(sign) |
| 6062 | else: |
| 6063 | min_width = 0 |
| 6064 | intpart = _insert_thousands_sep(intpart, spec, min_width) |
| 6065 | |
| 6066 | return _format_align(sign, intpart+fracpart, spec) |
| 6067 | |
| 6068 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 6069 | ##### Useful Constants (internal use only) ################################ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 6070 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 6071 | # Reusable defaults |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 6072 | _Infinity = Decimal('Inf') |
| 6073 | _NegativeInfinity = Decimal('-Inf') |
Mark Dickinson | c5de096 | 2009-01-02 23:07:08 +0000 | [diff] [blame] | 6074 | _NaN = Decimal('NaN') |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 6075 | _Zero = Decimal(0) |
| 6076 | _One = Decimal(1) |
| 6077 | _NegativeOne = Decimal(-1) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 6078 | |
Raymond Hettinger | b7e835b | 2009-01-03 19:08:10 +0000 | [diff] [blame] | 6079 | # _SignedInfinity[sign] is infinity w/ that sign |
| 6080 | _SignedInfinity = (_Infinity, _NegativeInfinity) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 6081 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 6082 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 6083 | |
| 6084 | if __name__ == '__main__': |
| 6085 | import doctest, sys |
| 6086 | doctest.testmod(sys.modules[__name__]) |