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