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