Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1 | # Copyright (c) 2004 Python Software Foundation. |
| 2 | # All rights reserved. |
| 3 | |
| 4 | # Written by Eric Price <eprice at tjhsst.edu> |
| 5 | # and Facundo Batista <facundo at taniquetil.com.ar> |
| 6 | # and Raymond Hettinger <python at rcn.com> |
Fred Drake | 1f34eb1 | 2004-07-01 14:28:36 +0000 | [diff] [blame] | 7 | # and Aahz <aahz at pobox.com> |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 8 | # and Tim Peters |
| 9 | |
Raymond Hettinger | 27dbcf2 | 2004-08-19 22:39:55 +0000 | [diff] [blame] | 10 | # This module is currently Py2.3 compatible and should be kept that way |
| 11 | # unless a major compelling advantage arises. IOW, 2.3 compatibility is |
| 12 | # strongly preferred, but not guaranteed. |
| 13 | |
| 14 | # Also, this module should be kept in sync with the latest updates of |
| 15 | # the IBM specification as it evolves. Those updates will be treated |
| 16 | # as bug fixes (deviation from the spec is a compatibility, usability |
| 17 | # bug) and will be backported. At this point the spec is stabilizing |
| 18 | # and the updates are becoming fewer, smaller, and less significant. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 19 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 20 | """ |
| 21 | This is a Py2.3 implementation of decimal floating point arithmetic based on |
| 22 | the General Decimal Arithmetic Specification: |
| 23 | |
| 24 | www2.hursley.ibm.com/decimal/decarith.html |
| 25 | |
Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 26 | and IEEE standard 854-1987: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 27 | |
| 28 | www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html |
| 29 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 30 | Decimal floating point has finite precision with arbitrarily large bounds. |
| 31 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 32 | The purpose of this module is to support arithmetic using familiar |
| 33 | "schoolhouse" rules and to avoid some of the tricky representation |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 34 | issues associated with binary floating point. The package is especially |
| 35 | useful for financial applications or for contexts where users have |
| 36 | expectations that are at odds with binary floating point (for instance, |
| 37 | in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 38 | of the expected Decimal('0.00') returned by decimal floating point). |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 39 | |
| 40 | Here are some examples of using the decimal module: |
| 41 | |
| 42 | >>> from decimal import * |
Raymond Hettinger | bd7f76d | 2004-07-08 00:49:18 +0000 | [diff] [blame] | 43 | >>> setcontext(ExtendedContext) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 44 | >>> Decimal(0) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 45 | Decimal('0') |
| 46 | >>> Decimal('1') |
| 47 | Decimal('1') |
| 48 | >>> Decimal('-.0123') |
| 49 | Decimal('-0.0123') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 50 | >>> Decimal(123456) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 51 | Decimal('123456') |
| 52 | >>> Decimal('123.45e12345678901234567890') |
| 53 | Decimal('1.2345E+12345678901234567892') |
| 54 | >>> Decimal('1.33') + Decimal('1.27') |
| 55 | Decimal('2.60') |
| 56 | >>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41') |
| 57 | Decimal('-2.20') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 58 | >>> dig = Decimal(1) |
| 59 | >>> print dig / Decimal(3) |
| 60 | 0.333333333 |
| 61 | >>> getcontext().prec = 18 |
| 62 | >>> print dig / Decimal(3) |
| 63 | 0.333333333333333333 |
| 64 | >>> print dig.sqrt() |
| 65 | 1 |
| 66 | >>> print Decimal(3).sqrt() |
| 67 | 1.73205080756887729 |
| 68 | >>> print Decimal(3) ** 123 |
| 69 | 4.85192780976896427E+58 |
| 70 | >>> inf = Decimal(1) / Decimal(0) |
| 71 | >>> print inf |
| 72 | Infinity |
| 73 | >>> neginf = Decimal(-1) / Decimal(0) |
| 74 | >>> print neginf |
| 75 | -Infinity |
| 76 | >>> print neginf + inf |
| 77 | NaN |
| 78 | >>> print neginf * inf |
| 79 | -Infinity |
| 80 | >>> print dig / 0 |
| 81 | Infinity |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 82 | >>> getcontext().traps[DivisionByZero] = 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 83 | >>> print dig / 0 |
| 84 | Traceback (most recent call last): |
| 85 | ... |
| 86 | ... |
| 87 | ... |
| 88 | DivisionByZero: x / 0 |
| 89 | >>> c = Context() |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 90 | >>> c.traps[InvalidOperation] = 0 |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 91 | >>> print c.flags[InvalidOperation] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 92 | 0 |
| 93 | >>> c.divide(Decimal(0), Decimal(0)) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 94 | Decimal('NaN') |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 95 | >>> c.traps[InvalidOperation] = 1 |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 96 | >>> print c.flags[InvalidOperation] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 97 | 1 |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 98 | >>> c.flags[InvalidOperation] = 0 |
| 99 | >>> print c.flags[InvalidOperation] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 100 | 0 |
| 101 | >>> print c.divide(Decimal(0), Decimal(0)) |
| 102 | Traceback (most recent call last): |
| 103 | ... |
| 104 | ... |
| 105 | ... |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 106 | InvalidOperation: 0 / 0 |
| 107 | >>> print c.flags[InvalidOperation] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 108 | 1 |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 109 | >>> c.flags[InvalidOperation] = 0 |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 110 | >>> c.traps[InvalidOperation] = 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 111 | >>> print c.divide(Decimal(0), Decimal(0)) |
| 112 | NaN |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 113 | >>> print c.flags[InvalidOperation] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 114 | 1 |
| 115 | >>> |
| 116 | """ |
| 117 | |
| 118 | __all__ = [ |
| 119 | # Two major classes |
| 120 | 'Decimal', 'Context', |
| 121 | |
| 122 | # Contexts |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 123 | 'DefaultContext', 'BasicContext', 'ExtendedContext', |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 124 | |
| 125 | # Exceptions |
Raymond Hettinger | d87ac8f | 2004-07-09 10:52:54 +0000 | [diff] [blame] | 126 | 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero', |
| 127 | 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow', |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 128 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 129 | # Constants for use in setting up contexts |
| 130 | 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING', |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 131 | 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP', |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 132 | |
| 133 | # Functions for manipulating contexts |
Nick Coghlan | 8b6999b | 2006-08-31 12:00:43 +0000 | [diff] [blame] | 134 | 'setcontext', 'getcontext', 'localcontext' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 135 | ] |
| 136 | |
Raymond Hettinger | eb26084 | 2005-06-07 18:52:34 +0000 | [diff] [blame] | 137 | import copy as _copy |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 138 | |
Raymond Hettinger | 097a190 | 2008-01-11 02:24:13 +0000 | [diff] [blame] | 139 | try: |
| 140 | from collections import namedtuple as _namedtuple |
| 141 | DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent') |
| 142 | except ImportError: |
| 143 | DecimalTuple = lambda *args: args |
| 144 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 145 | # Rounding |
Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 146 | ROUND_DOWN = 'ROUND_DOWN' |
| 147 | ROUND_HALF_UP = 'ROUND_HALF_UP' |
| 148 | ROUND_HALF_EVEN = 'ROUND_HALF_EVEN' |
| 149 | ROUND_CEILING = 'ROUND_CEILING' |
| 150 | ROUND_FLOOR = 'ROUND_FLOOR' |
| 151 | ROUND_UP = 'ROUND_UP' |
| 152 | ROUND_HALF_DOWN = 'ROUND_HALF_DOWN' |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 153 | ROUND_05UP = 'ROUND_05UP' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 154 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 155 | # Errors |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 156 | |
| 157 | class DecimalException(ArithmeticError): |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 158 | """Base exception class. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 159 | |
| 160 | Used exceptions derive from this. |
| 161 | If an exception derives from another exception besides this (such as |
| 162 | Underflow (Inexact, Rounded, Subnormal) that indicates that it is only |
| 163 | called if the others are present. This isn't actually used for |
| 164 | anything, though. |
| 165 | |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 166 | handle -- Called when context._raise_error is called and the |
| 167 | trap_enabler is set. First argument is self, second is the |
| 168 | context. More arguments can be given, those being after |
| 169 | the explanation in _raise_error (For example, |
| 170 | context._raise_error(NewError, '(-x)!', self._sign) would |
| 171 | call NewError().handle(context, self._sign).) |
| 172 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 173 | To define a new exception, it should be sufficient to have it derive |
| 174 | from DecimalException. |
| 175 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 176 | def handle(self, context, *args): |
| 177 | pass |
| 178 | |
| 179 | |
| 180 | class Clamped(DecimalException): |
| 181 | """Exponent of a 0 changed to fit bounds. |
| 182 | |
| 183 | This occurs and signals clamped if the exponent of a result has been |
| 184 | altered in order to fit the constraints of a specific concrete |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 185 | representation. This may occur when the exponent of a zero result would |
| 186 | be outside the bounds of a representation, or when a large normal |
| 187 | number would have an encoded exponent that cannot be represented. In |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 188 | this latter case, the exponent is reduced to fit and the corresponding |
| 189 | number of zero digits are appended to the coefficient ("fold-down"). |
| 190 | """ |
| 191 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 192 | class InvalidOperation(DecimalException): |
| 193 | """An invalid operation was performed. |
| 194 | |
| 195 | Various bad things cause this: |
| 196 | |
| 197 | Something creates a signaling NaN |
| 198 | -INF + INF |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 199 | 0 * (+-)INF |
| 200 | (+-)INF / (+-)INF |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 201 | x % 0 |
| 202 | (+-)INF % x |
| 203 | x._rescale( non-integer ) |
| 204 | sqrt(-x) , x > 0 |
| 205 | 0 ** 0 |
| 206 | x ** (non-integer) |
| 207 | x ** (+-)INF |
| 208 | An operand is invalid |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 209 | |
| 210 | The result of the operation after these is a quiet positive NaN, |
| 211 | except when the cause is a signaling NaN, in which case the result is |
| 212 | also a quiet NaN, but with the original sign, and an optional |
| 213 | diagnostic information. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 214 | """ |
| 215 | def handle(self, context, *args): |
| 216 | if args: |
Facundo Batista | 0f5e7bf | 2007-12-19 12:53:01 +0000 | [diff] [blame] | 217 | ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True) |
| 218 | return ans._fix_nan(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 219 | return NaN |
| 220 | |
| 221 | class ConversionSyntax(InvalidOperation): |
| 222 | """Trying to convert badly formed string. |
| 223 | |
| 224 | This occurs and signals invalid-operation if an string is being |
| 225 | converted to a number and it does not conform to the numeric string |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 226 | syntax. The result is [0,qNaN]. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 227 | """ |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 228 | def handle(self, context, *args): |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 229 | return NaN |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 230 | |
| 231 | class DivisionByZero(DecimalException, ZeroDivisionError): |
| 232 | """Division by 0. |
| 233 | |
| 234 | This occurs and signals division-by-zero if division of a finite number |
| 235 | by zero was attempted (during a divide-integer or divide operation, or a |
| 236 | power operation with negative right-hand operand), and the dividend was |
| 237 | not zero. |
| 238 | |
| 239 | The result of the operation is [sign,inf], where sign is the exclusive |
| 240 | or of the signs of the operands for divide, or is 1 for an odd power of |
| 241 | -0, for power. |
| 242 | """ |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 243 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 244 | def handle(self, context, sign, *args): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 245 | return Infsign[sign] |
| 246 | |
| 247 | class DivisionImpossible(InvalidOperation): |
| 248 | """Cannot perform the division adequately. |
| 249 | |
| 250 | This occurs and signals invalid-operation if the integer result of a |
| 251 | divide-integer or remainder operation had too many digits (would be |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 252 | longer than precision). The result is [0,qNaN]. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 253 | """ |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 254 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 255 | def handle(self, context, *args): |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 256 | return NaN |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 257 | |
| 258 | class DivisionUndefined(InvalidOperation, ZeroDivisionError): |
| 259 | """Undefined result of division. |
| 260 | |
| 261 | This occurs and signals invalid-operation if division by zero was |
| 262 | attempted (during a divide-integer, divide, or remainder operation), and |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 263 | the dividend is also zero. The result is [0,qNaN]. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 264 | """ |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 265 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 266 | def handle(self, context, *args): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 267 | return NaN |
| 268 | |
| 269 | class Inexact(DecimalException): |
| 270 | """Had to round, losing information. |
| 271 | |
| 272 | This occurs and signals inexact whenever the result of an operation is |
| 273 | not exact (that is, it needed to be rounded and any discarded digits |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 274 | were non-zero), or if an overflow or underflow condition occurs. The |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 275 | result in all cases is unchanged. |
| 276 | |
| 277 | The inexact signal may be tested (or trapped) to determine if a given |
| 278 | operation (or sequence of operations) was inexact. |
| 279 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 280 | |
| 281 | class InvalidContext(InvalidOperation): |
| 282 | """Invalid context. Unknown rounding, for example. |
| 283 | |
| 284 | This occurs and signals invalid-operation if an invalid context was |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 285 | detected during an operation. This can occur if contexts are not checked |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 286 | on creation and either the precision exceeds the capability of the |
| 287 | underlying concrete representation or an unknown or unsupported rounding |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 288 | was specified. These aspects of the context need only be checked when |
| 289 | the values are required to be used. The result is [0,qNaN]. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 290 | """ |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 291 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 292 | def handle(self, context, *args): |
| 293 | return NaN |
| 294 | |
| 295 | class Rounded(DecimalException): |
| 296 | """Number got rounded (not necessarily changed during rounding). |
| 297 | |
| 298 | This occurs and signals rounded whenever the result of an operation is |
| 299 | rounded (that is, some zero or non-zero digits were discarded from the |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 300 | coefficient), or if an overflow or underflow condition occurs. The |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 301 | result in all cases is unchanged. |
| 302 | |
| 303 | The rounded signal may be tested (or trapped) to determine if a given |
| 304 | operation (or sequence of operations) caused a loss of precision. |
| 305 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 306 | |
| 307 | class Subnormal(DecimalException): |
| 308 | """Exponent < Emin before rounding. |
| 309 | |
| 310 | This occurs and signals subnormal whenever the result of a conversion or |
| 311 | operation is subnormal (that is, its adjusted exponent is less than |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 312 | Emin, before any rounding). The result in all cases is unchanged. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 313 | |
| 314 | The subnormal signal may be tested (or trapped) to determine if a given |
| 315 | or operation (or sequence of operations) yielded a subnormal result. |
| 316 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 317 | |
| 318 | class Overflow(Inexact, Rounded): |
| 319 | """Numerical overflow. |
| 320 | |
| 321 | This occurs and signals overflow if the adjusted exponent of a result |
| 322 | (from a conversion or from an operation that is not an attempt to divide |
| 323 | by zero), after rounding, would be greater than the largest value that |
| 324 | can be handled by the implementation (the value Emax). |
| 325 | |
| 326 | The result depends on the rounding mode: |
| 327 | |
| 328 | For round-half-up and round-half-even (and for round-half-down and |
| 329 | round-up, if implemented), the result of the operation is [sign,inf], |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 330 | where sign is the sign of the intermediate result. For round-down, the |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 331 | result is the largest finite number that can be represented in the |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 332 | current precision, with the sign of the intermediate result. For |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 333 | round-ceiling, the result is the same as for round-down if the sign of |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 334 | the intermediate result is 1, or is [0,inf] otherwise. For round-floor, |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 335 | the result is the same as for round-down if the sign of the intermediate |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 336 | result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 337 | will also be raised. |
Facundo Batista | 0f5e7bf | 2007-12-19 12:53:01 +0000 | [diff] [blame] | 338 | """ |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 339 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 340 | def handle(self, context, sign, *args): |
| 341 | if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN, |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 342 | ROUND_HALF_DOWN, ROUND_UP): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 343 | return Infsign[sign] |
| 344 | if sign == 0: |
| 345 | if context.rounding == ROUND_CEILING: |
| 346 | return Infsign[sign] |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 347 | return _dec_from_triple(sign, '9'*context.prec, |
| 348 | context.Emax-context.prec+1) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 349 | if sign == 1: |
| 350 | if context.rounding == ROUND_FLOOR: |
| 351 | return Infsign[sign] |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 352 | return _dec_from_triple(sign, '9'*context.prec, |
| 353 | context.Emax-context.prec+1) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 354 | |
| 355 | |
| 356 | class Underflow(Inexact, Rounded, Subnormal): |
| 357 | """Numerical underflow with result rounded to 0. |
| 358 | |
| 359 | This occurs and signals underflow if a result is inexact and the |
| 360 | adjusted exponent of the result would be smaller (more negative) than |
| 361 | the smallest value that can be handled by the implementation (the value |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 362 | Emin). That is, the result is both inexact and subnormal. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 363 | |
| 364 | The result after an underflow will be a subnormal number rounded, if |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 365 | necessary, so that its exponent is not less than Etiny. This may result |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 366 | in 0 with the sign of the intermediate result and an exponent of Etiny. |
| 367 | |
| 368 | In all cases, Inexact, Rounded, and Subnormal will also be raised. |
| 369 | """ |
| 370 | |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 371 | # List of public traps and flags |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 372 | _signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded, |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 373 | Underflow, InvalidOperation, Subnormal] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 374 | |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 375 | # Map conditions (per the spec) to signals |
| 376 | _condition_map = {ConversionSyntax:InvalidOperation, |
| 377 | DivisionImpossible:InvalidOperation, |
| 378 | DivisionUndefined:InvalidOperation, |
| 379 | InvalidContext:InvalidOperation} |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 380 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 381 | ##### Context Functions ################################################## |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 382 | |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 383 | # The getcontext() and setcontext() function manage access to a thread-local |
| 384 | # current context. Py2.4 offers direct support for thread locals. If that |
| 385 | # is not available, use threading.currentThread() which is slower but will |
Raymond Hettinger | 7e71fa5 | 2004-12-18 19:07:19 +0000 | [diff] [blame] | 386 | # work for older Pythons. If threads are not part of the build, create a |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 387 | # mock threading object with threading.local() returning the module namespace. |
Raymond Hettinger | 7e71fa5 | 2004-12-18 19:07:19 +0000 | [diff] [blame] | 388 | |
| 389 | try: |
| 390 | import threading |
| 391 | except ImportError: |
| 392 | # Python was compiled without threads; create a mock object instead |
| 393 | import sys |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 394 | class MockThreading(object): |
Raymond Hettinger | 7e71fa5 | 2004-12-18 19:07:19 +0000 | [diff] [blame] | 395 | def local(self, sys=sys): |
| 396 | return sys.modules[__name__] |
| 397 | threading = MockThreading() |
| 398 | del sys, MockThreading |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 399 | |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 400 | try: |
| 401 | threading.local |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 402 | |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 403 | except AttributeError: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 404 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 405 | # To fix reloading, force it to create a new context |
| 406 | # Old contexts have different exceptions in their dicts, making problems. |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 407 | if hasattr(threading.currentThread(), '__decimal_context__'): |
| 408 | del threading.currentThread().__decimal_context__ |
| 409 | |
| 410 | def setcontext(context): |
| 411 | """Set this thread's context to context.""" |
| 412 | if context in (DefaultContext, BasicContext, ExtendedContext): |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 413 | context = context.copy() |
Raymond Hettinger | 61992ef | 2004-08-06 23:42:16 +0000 | [diff] [blame] | 414 | context.clear_flags() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 415 | threading.currentThread().__decimal_context__ = context |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 416 | |
| 417 | def getcontext(): |
| 418 | """Returns this thread's context. |
| 419 | |
| 420 | If this thread does not yet have a context, returns |
| 421 | a new context and sets this thread's context. |
| 422 | New contexts are copies of DefaultContext. |
| 423 | """ |
| 424 | try: |
| 425 | return threading.currentThread().__decimal_context__ |
| 426 | except AttributeError: |
| 427 | context = Context() |
| 428 | threading.currentThread().__decimal_context__ = context |
| 429 | return context |
| 430 | |
| 431 | else: |
| 432 | |
| 433 | local = threading.local() |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 434 | if hasattr(local, '__decimal_context__'): |
| 435 | del local.__decimal_context__ |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 436 | |
| 437 | def getcontext(_local=local): |
| 438 | """Returns this thread's context. |
| 439 | |
| 440 | If this thread does not yet have a context, returns |
| 441 | a new context and sets this thread's context. |
| 442 | New contexts are copies of DefaultContext. |
| 443 | """ |
| 444 | try: |
| 445 | return _local.__decimal_context__ |
| 446 | except AttributeError: |
| 447 | context = Context() |
| 448 | _local.__decimal_context__ = context |
| 449 | return context |
| 450 | |
| 451 | def setcontext(context, _local=local): |
| 452 | """Set this thread's context to context.""" |
| 453 | if context in (DefaultContext, BasicContext, ExtendedContext): |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 454 | context = context.copy() |
Raymond Hettinger | 61992ef | 2004-08-06 23:42:16 +0000 | [diff] [blame] | 455 | context.clear_flags() |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 456 | _local.__decimal_context__ = context |
| 457 | |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 458 | del threading, local # Don't contaminate the namespace |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 459 | |
Nick Coghlan | 8b6999b | 2006-08-31 12:00:43 +0000 | [diff] [blame] | 460 | def localcontext(ctx=None): |
| 461 | """Return a context manager for a copy of the supplied context |
| 462 | |
| 463 | Uses a copy of the current context if no context is specified |
| 464 | The returned context manager creates a local decimal context |
| 465 | in a with statement: |
| 466 | def sin(x): |
| 467 | with localcontext() as ctx: |
| 468 | ctx.prec += 2 |
| 469 | # Rest of sin calculation algorithm |
| 470 | # uses a precision 2 greater than normal |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 471 | return +s # Convert result to normal precision |
Nick Coghlan | 8b6999b | 2006-08-31 12:00:43 +0000 | [diff] [blame] | 472 | |
| 473 | def sin(x): |
| 474 | with localcontext(ExtendedContext): |
| 475 | # Rest of sin calculation algorithm |
| 476 | # uses the Extended Context from the |
| 477 | # General Decimal Arithmetic Specification |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 478 | return +s # Convert result to normal context |
Nick Coghlan | 8b6999b | 2006-08-31 12:00:43 +0000 | [diff] [blame] | 479 | |
Facundo Batista | ee340e5 | 2008-05-02 17:39:00 +0000 | [diff] [blame] | 480 | >>> setcontext(DefaultContext) |
Nick Coghlan | 8b6999b | 2006-08-31 12:00:43 +0000 | [diff] [blame] | 481 | >>> print getcontext().prec |
| 482 | 28 |
| 483 | >>> with localcontext(): |
| 484 | ... ctx = getcontext() |
Raymond Hettinger | 495df47 | 2007-02-08 01:42:35 +0000 | [diff] [blame] | 485 | ... ctx.prec += 2 |
Nick Coghlan | 8b6999b | 2006-08-31 12:00:43 +0000 | [diff] [blame] | 486 | ... print ctx.prec |
| 487 | ... |
| 488 | 30 |
| 489 | >>> with localcontext(ExtendedContext): |
| 490 | ... print getcontext().prec |
| 491 | ... |
| 492 | 9 |
| 493 | >>> print getcontext().prec |
| 494 | 28 |
| 495 | """ |
Nick Coghlan | ced1218 | 2006-09-02 03:54:17 +0000 | [diff] [blame] | 496 | if ctx is None: ctx = getcontext() |
| 497 | return _ContextManager(ctx) |
Nick Coghlan | 8b6999b | 2006-08-31 12:00:43 +0000 | [diff] [blame] | 498 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 499 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 500 | ##### Decimal class ####################################################### |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 501 | |
| 502 | class Decimal(object): |
| 503 | """Floating point class for decimal arithmetic.""" |
| 504 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 505 | __slots__ = ('_exp','_int','_sign', '_is_special') |
| 506 | # Generally, the value of the Decimal instance is given by |
| 507 | # (-1)**_sign * _int * 10**_exp |
| 508 | # Special values are signified by _is_special == True |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 509 | |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 510 | # We're immutable, so use __new__ not __init__ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 511 | def __new__(cls, value="0", context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 512 | """Create a decimal point instance. |
| 513 | |
| 514 | >>> Decimal('3.14') # string input |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 515 | Decimal('3.14') |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 516 | >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 517 | Decimal('3.14') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 518 | >>> Decimal(314) # int or long |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 519 | Decimal('314') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 520 | >>> Decimal(Decimal(314)) # another decimal instance |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 521 | Decimal('314') |
Mark Dickinson | 59bc20b | 2008-01-12 01:56:00 +0000 | [diff] [blame] | 522 | >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 523 | Decimal('3.14') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 524 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 525 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 526 | # Note that the coefficient, self._int, is actually stored as |
| 527 | # a string rather than as a tuple of digits. This speeds up |
| 528 | # the "digits to integer" and "integer to digits" conversions |
| 529 | # that are used in almost every arithmetic operation on |
| 530 | # Decimals. This is an internal detail: the as_tuple function |
| 531 | # and the Decimal constructor still deal with tuples of |
| 532 | # digits. |
| 533 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 534 | self = object.__new__(cls) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 535 | |
Facundo Batista | 0d157a0 | 2007-11-30 17:15:25 +0000 | [diff] [blame] | 536 | # From a string |
| 537 | # REs insist on real strings, so we can too. |
| 538 | if isinstance(value, basestring): |
Mark Dickinson | 59bc20b | 2008-01-12 01:56:00 +0000 | [diff] [blame] | 539 | m = _parser(value.strip()) |
Facundo Batista | 0d157a0 | 2007-11-30 17:15:25 +0000 | [diff] [blame] | 540 | if m is None: |
| 541 | if context is None: |
| 542 | context = getcontext() |
| 543 | return context._raise_error(ConversionSyntax, |
| 544 | "Invalid literal for Decimal: %r" % value) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 545 | |
Facundo Batista | 0d157a0 | 2007-11-30 17:15:25 +0000 | [diff] [blame] | 546 | if m.group('sign') == "-": |
| 547 | self._sign = 1 |
| 548 | else: |
| 549 | self._sign = 0 |
| 550 | intpart = m.group('int') |
| 551 | if intpart is not None: |
| 552 | # finite number |
| 553 | fracpart = m.group('frac') |
| 554 | exp = int(m.group('exp') or '0') |
| 555 | if fracpart is not None: |
Mark Dickinson | 8e85ffa | 2008-03-25 18:47:59 +0000 | [diff] [blame] | 556 | self._int = str((intpart+fracpart).lstrip('0') or '0') |
Facundo Batista | 0d157a0 | 2007-11-30 17:15:25 +0000 | [diff] [blame] | 557 | self._exp = exp - len(fracpart) |
| 558 | else: |
Mark Dickinson | 8e85ffa | 2008-03-25 18:47:59 +0000 | [diff] [blame] | 559 | self._int = str(intpart.lstrip('0') or '0') |
Facundo Batista | 0d157a0 | 2007-11-30 17:15:25 +0000 | [diff] [blame] | 560 | self._exp = exp |
| 561 | self._is_special = False |
| 562 | else: |
| 563 | diag = m.group('diag') |
| 564 | if diag is not None: |
| 565 | # NaN |
Mark Dickinson | 8e85ffa | 2008-03-25 18:47:59 +0000 | [diff] [blame] | 566 | self._int = str(diag.lstrip('0')) |
Facundo Batista | 0d157a0 | 2007-11-30 17:15:25 +0000 | [diff] [blame] | 567 | if m.group('signal'): |
| 568 | self._exp = 'N' |
| 569 | else: |
| 570 | self._exp = 'n' |
| 571 | else: |
| 572 | # infinity |
| 573 | self._int = '0' |
| 574 | self._exp = 'F' |
| 575 | self._is_special = True |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 576 | return self |
| 577 | |
| 578 | # From an integer |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 579 | if isinstance(value, (int,long)): |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 580 | if value >= 0: |
| 581 | self._sign = 0 |
| 582 | else: |
| 583 | self._sign = 1 |
| 584 | self._exp = 0 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 585 | self._int = str(abs(value)) |
Facundo Batista | 0d157a0 | 2007-11-30 17:15:25 +0000 | [diff] [blame] | 586 | self._is_special = False |
| 587 | return self |
| 588 | |
| 589 | # From another decimal |
| 590 | if isinstance(value, Decimal): |
| 591 | self._exp = value._exp |
| 592 | self._sign = value._sign |
| 593 | self._int = value._int |
| 594 | self._is_special = value._is_special |
| 595 | return self |
| 596 | |
| 597 | # From an internal working value |
| 598 | if isinstance(value, _WorkRep): |
| 599 | self._sign = value.sign |
| 600 | self._int = str(value.int) |
| 601 | self._exp = int(value.exp) |
| 602 | self._is_special = False |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 603 | return self |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 604 | |
| 605 | # tuple/list conversion (possibly from as_tuple()) |
| 606 | if isinstance(value, (list,tuple)): |
| 607 | if len(value) != 3: |
Facundo Batista | 9b5e231 | 2007-10-19 19:25:57 +0000 | [diff] [blame] | 608 | raise ValueError('Invalid tuple size in creation of Decimal ' |
| 609 | 'from list or tuple. The list or tuple ' |
| 610 | 'should have exactly three elements.') |
| 611 | # process sign. The isinstance test rejects floats |
| 612 | if not (isinstance(value[0], (int, long)) and value[0] in (0,1)): |
| 613 | raise ValueError("Invalid sign. The first value in the tuple " |
| 614 | "should be an integer; either 0 for a " |
| 615 | "positive number or 1 for a negative number.") |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 616 | self._sign = value[0] |
Facundo Batista | 9b5e231 | 2007-10-19 19:25:57 +0000 | [diff] [blame] | 617 | if value[2] == 'F': |
| 618 | # infinity: value[1] is ignored |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 619 | self._int = '0' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 620 | self._exp = value[2] |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 621 | self._is_special = True |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 622 | else: |
Facundo Batista | 9b5e231 | 2007-10-19 19:25:57 +0000 | [diff] [blame] | 623 | # process and validate the digits in value[1] |
| 624 | digits = [] |
| 625 | for digit in value[1]: |
| 626 | if isinstance(digit, (int, long)) and 0 <= digit <= 9: |
| 627 | # skip leading zeros |
| 628 | if digits or digit != 0: |
| 629 | digits.append(digit) |
| 630 | else: |
| 631 | raise ValueError("The second value in the tuple must " |
| 632 | "be composed of integers in the range " |
| 633 | "0 through 9.") |
| 634 | if value[2] in ('n', 'N'): |
| 635 | # NaN: digits form the diagnostic |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 636 | self._int = ''.join(map(str, digits)) |
Facundo Batista | 9b5e231 | 2007-10-19 19:25:57 +0000 | [diff] [blame] | 637 | self._exp = value[2] |
| 638 | self._is_special = True |
| 639 | elif isinstance(value[2], (int, long)): |
| 640 | # finite number: digits give the coefficient |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 641 | self._int = ''.join(map(str, digits or [0])) |
Facundo Batista | 9b5e231 | 2007-10-19 19:25:57 +0000 | [diff] [blame] | 642 | self._exp = value[2] |
| 643 | self._is_special = False |
| 644 | else: |
| 645 | raise ValueError("The third value in the tuple must " |
| 646 | "be an integer, or one of the " |
| 647 | "strings 'F', 'n', 'N'.") |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 648 | return self |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 649 | |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 650 | if isinstance(value, float): |
| 651 | raise TypeError("Cannot convert float to Decimal. " + |
| 652 | "First convert the float to a string") |
| 653 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 654 | raise TypeError("Cannot convert %r to Decimal" % value) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 655 | |
| 656 | def _isnan(self): |
| 657 | """Returns whether the number is not actually one. |
| 658 | |
| 659 | 0 if a number |
Facundo Batista | 0f5e7bf | 2007-12-19 12:53:01 +0000 | [diff] [blame] | 660 | 1 if NaN |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 661 | 2 if sNaN |
| 662 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 663 | if self._is_special: |
| 664 | exp = self._exp |
| 665 | if exp == 'n': |
| 666 | return 1 |
| 667 | elif exp == 'N': |
| 668 | return 2 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 669 | return 0 |
| 670 | |
| 671 | def _isinfinity(self): |
| 672 | """Returns whether the number is infinite |
| 673 | |
| 674 | 0 if finite or not a number |
| 675 | 1 if +INF |
| 676 | -1 if -INF |
| 677 | """ |
| 678 | if self._exp == 'F': |
| 679 | if self._sign: |
| 680 | return -1 |
| 681 | return 1 |
| 682 | return 0 |
| 683 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 684 | def _check_nans(self, other=None, context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 685 | """Returns whether the number is not actually one. |
| 686 | |
| 687 | if self, other are sNaN, signal |
| 688 | if self, other are NaN return nan |
| 689 | return 0 |
| 690 | |
| 691 | Done before operations. |
| 692 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 693 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 694 | self_is_nan = self._isnan() |
| 695 | if other is None: |
| 696 | other_is_nan = False |
| 697 | else: |
| 698 | other_is_nan = other._isnan() |
| 699 | |
| 700 | if self_is_nan or other_is_nan: |
| 701 | if context is None: |
| 702 | context = getcontext() |
| 703 | |
| 704 | if self_is_nan == 2: |
| 705 | return context._raise_error(InvalidOperation, 'sNaN', |
Facundo Batista | 0f5e7bf | 2007-12-19 12:53:01 +0000 | [diff] [blame] | 706 | self) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 707 | if other_is_nan == 2: |
| 708 | return context._raise_error(InvalidOperation, 'sNaN', |
Facundo Batista | 0f5e7bf | 2007-12-19 12:53:01 +0000 | [diff] [blame] | 709 | other) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 710 | if self_is_nan: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 711 | return self._fix_nan(context) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 712 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 713 | return other._fix_nan(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 714 | return 0 |
| 715 | |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 716 | def _compare_check_nans(self, other, context): |
| 717 | """Version of _check_nans used for the signaling comparisons |
| 718 | compare_signal, __le__, __lt__, __ge__, __gt__. |
| 719 | |
| 720 | Signal InvalidOperation if either self or other is a (quiet |
| 721 | or signaling) NaN. Signaling NaNs take precedence over quiet |
| 722 | NaNs. |
| 723 | |
| 724 | Return 0 if neither operand is a NaN. |
| 725 | |
| 726 | """ |
| 727 | if context is None: |
| 728 | context = getcontext() |
| 729 | |
| 730 | if self._is_special or other._is_special: |
| 731 | if self.is_snan(): |
| 732 | return context._raise_error(InvalidOperation, |
| 733 | 'comparison involving sNaN', |
| 734 | self) |
| 735 | elif other.is_snan(): |
| 736 | return context._raise_error(InvalidOperation, |
| 737 | 'comparison involving sNaN', |
| 738 | other) |
| 739 | elif self.is_qnan(): |
| 740 | return context._raise_error(InvalidOperation, |
| 741 | 'comparison involving NaN', |
| 742 | self) |
| 743 | elif other.is_qnan(): |
| 744 | return context._raise_error(InvalidOperation, |
| 745 | 'comparison involving NaN', |
| 746 | other) |
| 747 | return 0 |
| 748 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 749 | def __nonzero__(self): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 750 | """Return True if self is nonzero; otherwise return False. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 751 | |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 752 | NaNs and infinities are considered nonzero. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 753 | """ |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 754 | return self._is_special or self._int != '0' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 755 | |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 756 | def _cmp(self, other): |
| 757 | """Compare the two non-NaN decimal instances self and other. |
| 758 | |
| 759 | Returns -1 if self < other, 0 if self == other and 1 |
| 760 | if self > other. This routine is for internal use only.""" |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 761 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 762 | if self._is_special or other._is_special: |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 763 | return cmp(self._isinfinity(), other._isinfinity()) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 764 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 765 | # check for zeros; note that cmp(0, -0) should return 0 |
| 766 | if not self: |
| 767 | if not other: |
| 768 | return 0 |
| 769 | else: |
| 770 | return -((-1)**other._sign) |
| 771 | if not other: |
| 772 | return (-1)**self._sign |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 773 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 774 | # If different signs, neg one is less |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 775 | if other._sign < self._sign: |
| 776 | return -1 |
| 777 | if self._sign < other._sign: |
| 778 | return 1 |
| 779 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 780 | self_adjusted = self.adjusted() |
| 781 | other_adjusted = other.adjusted() |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 782 | if self_adjusted == other_adjusted: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 783 | self_padded = self._int + '0'*(self._exp - other._exp) |
| 784 | other_padded = other._int + '0'*(other._exp - self._exp) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 785 | return cmp(self_padded, other_padded) * (-1)**self._sign |
| 786 | elif self_adjusted > other_adjusted: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 787 | return (-1)**self._sign |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 788 | else: # self_adjusted < other_adjusted |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 789 | return -((-1)**self._sign) |
| 790 | |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 791 | # Note: The Decimal standard doesn't cover rich comparisons for |
| 792 | # Decimals. In particular, the specification is silent on the |
| 793 | # subject of what should happen for a comparison involving a NaN. |
| 794 | # We take the following approach: |
| 795 | # |
| 796 | # == comparisons involving a NaN always return False |
| 797 | # != comparisons involving a NaN always return True |
| 798 | # <, >, <= and >= comparisons involving a (quiet or signaling) |
| 799 | # NaN signal InvalidOperation, and return False if the |
Mark Dickinson | 3a94ee0 | 2008-02-10 15:19:58 +0000 | [diff] [blame] | 800 | # InvalidOperation is not trapped. |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 801 | # |
| 802 | # This behavior is designed to conform as closely as possible to |
| 803 | # that specified by IEEE 754. |
| 804 | |
Raymond Hettinger | 0aeac10 | 2004-07-05 22:53:03 +0000 | [diff] [blame] | 805 | def __eq__(self, other): |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 806 | other = _convert_other(other) |
| 807 | if other is NotImplemented: |
| 808 | return other |
| 809 | if self.is_nan() or other.is_nan(): |
| 810 | return False |
| 811 | return self._cmp(other) == 0 |
Raymond Hettinger | 0aeac10 | 2004-07-05 22:53:03 +0000 | [diff] [blame] | 812 | |
| 813 | def __ne__(self, other): |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 814 | other = _convert_other(other) |
| 815 | if other is NotImplemented: |
| 816 | return other |
| 817 | if self.is_nan() or other.is_nan(): |
| 818 | return True |
| 819 | return self._cmp(other) != 0 |
| 820 | |
| 821 | def __lt__(self, other, context=None): |
| 822 | other = _convert_other(other) |
| 823 | if other is NotImplemented: |
| 824 | return other |
| 825 | ans = self._compare_check_nans(other, context) |
| 826 | if ans: |
| 827 | return False |
| 828 | return self._cmp(other) < 0 |
| 829 | |
| 830 | def __le__(self, other, context=None): |
| 831 | other = _convert_other(other) |
| 832 | if other is NotImplemented: |
| 833 | return other |
| 834 | ans = self._compare_check_nans(other, context) |
| 835 | if ans: |
| 836 | return False |
| 837 | return self._cmp(other) <= 0 |
| 838 | |
| 839 | def __gt__(self, other, context=None): |
| 840 | other = _convert_other(other) |
| 841 | if other is NotImplemented: |
| 842 | return other |
| 843 | ans = self._compare_check_nans(other, context) |
| 844 | if ans: |
| 845 | return False |
| 846 | return self._cmp(other) > 0 |
| 847 | |
| 848 | def __ge__(self, other, context=None): |
| 849 | other = _convert_other(other) |
| 850 | if other is NotImplemented: |
| 851 | return other |
| 852 | ans = self._compare_check_nans(other, context) |
| 853 | if ans: |
| 854 | return False |
| 855 | return self._cmp(other) >= 0 |
Raymond Hettinger | 0aeac10 | 2004-07-05 22:53:03 +0000 | [diff] [blame] | 856 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 857 | def compare(self, other, context=None): |
| 858 | """Compares one to another. |
| 859 | |
| 860 | -1 => a < b |
| 861 | 0 => a = b |
| 862 | 1 => a > b |
| 863 | NaN => one is NaN |
| 864 | Like __cmp__, but returns Decimal instances. |
| 865 | """ |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 866 | other = _convert_other(other, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 867 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 868 | # Compare(NaN, NaN) = NaN |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 869 | if (self._is_special or other and other._is_special): |
| 870 | ans = self._check_nans(other, context) |
| 871 | if ans: |
| 872 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 873 | |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 874 | return Decimal(self._cmp(other)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 875 | |
| 876 | def __hash__(self): |
| 877 | """x.__hash__() <==> hash(x)""" |
| 878 | # Decimal integers must hash the same as the ints |
Facundo Batista | 52b2579 | 2008-01-08 12:25:20 +0000 | [diff] [blame] | 879 | # |
| 880 | # The hash of a nonspecial noninteger Decimal must depend only |
| 881 | # on the value of that Decimal, and not on its representation. |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 882 | # For example: hash(Decimal('100E-1')) == hash(Decimal('10')). |
Raymond Hettinger | bea3f6f | 2005-03-15 04:59:17 +0000 | [diff] [blame] | 883 | if self._is_special: |
| 884 | if self._isnan(): |
| 885 | raise TypeError('Cannot hash a NaN value.') |
| 886 | return hash(str(self)) |
Facundo Batista | 8c20244 | 2007-09-19 17:53:25 +0000 | [diff] [blame] | 887 | if not self: |
| 888 | return 0 |
| 889 | if self._isinteger(): |
| 890 | op = _WorkRep(self.to_integral_value()) |
| 891 | # to make computation feasible for Decimals with large |
| 892 | # exponent, we use the fact that hash(n) == hash(m) for |
| 893 | # any two nonzero integers n and m such that (i) n and m |
| 894 | # have the same sign, and (ii) n is congruent to m modulo |
| 895 | # 2**64-1. So we can replace hash((-1)**s*c*10**e) with |
| 896 | # hash((-1)**s*c*pow(10, e, 2**64-1). |
| 897 | 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] | 898 | # The value of a nonzero nonspecial Decimal instance is |
| 899 | # faithfully represented by the triple consisting of its sign, |
| 900 | # its adjusted exponent, and its coefficient with trailing |
| 901 | # zeros removed. |
| 902 | return hash((self._sign, |
| 903 | self._exp+len(self._int), |
| 904 | self._int.rstrip('0'))) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 905 | |
| 906 | def as_tuple(self): |
| 907 | """Represents the number as a triple tuple. |
| 908 | |
| 909 | To show the internals exactly as they are. |
| 910 | """ |
Raymond Hettinger | 097a190 | 2008-01-11 02:24:13 +0000 | [diff] [blame] | 911 | return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 912 | |
| 913 | def __repr__(self): |
| 914 | """Represents the number as an instance of Decimal.""" |
| 915 | # Invariant: eval(repr(d)) == d |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 916 | return "Decimal('%s')" % str(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 917 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 918 | def __str__(self, eng=False, context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 919 | """Return string representation of the number in scientific notation. |
| 920 | |
| 921 | Captures all of the information in the underlying representation. |
| 922 | """ |
| 923 | |
Facundo Batista | 62edb71 | 2007-12-03 16:29:52 +0000 | [diff] [blame] | 924 | sign = ['', '-'][self._sign] |
Raymond Hettinger | e5a0a96 | 2005-06-20 09:49:42 +0000 | [diff] [blame] | 925 | if self._is_special: |
Facundo Batista | 62edb71 | 2007-12-03 16:29:52 +0000 | [diff] [blame] | 926 | if self._exp == 'F': |
| 927 | return sign + 'Infinity' |
| 928 | elif self._exp == 'n': |
| 929 | return sign + 'NaN' + self._int |
| 930 | else: # self._exp == 'N' |
| 931 | return sign + 'sNaN' + self._int |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 932 | |
Facundo Batista | 62edb71 | 2007-12-03 16:29:52 +0000 | [diff] [blame] | 933 | # number of digits of self._int to left of decimal point |
| 934 | leftdigits = self._exp + len(self._int) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 935 | |
Facundo Batista | 62edb71 | 2007-12-03 16:29:52 +0000 | [diff] [blame] | 936 | # dotplace is number of digits of self._int to the left of the |
| 937 | # decimal point in the mantissa of the output string (that is, |
| 938 | # after adjusting the exponent) |
| 939 | if self._exp <= 0 and leftdigits > -6: |
| 940 | # no exponent required |
| 941 | dotplace = leftdigits |
| 942 | elif not eng: |
| 943 | # usual scientific notation: 1 digit on left of the point |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 944 | dotplace = 1 |
Facundo Batista | 62edb71 | 2007-12-03 16:29:52 +0000 | [diff] [blame] | 945 | elif self._int == '0': |
| 946 | # engineering notation, zero |
| 947 | dotplace = (leftdigits + 1) % 3 - 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 948 | else: |
Facundo Batista | 62edb71 | 2007-12-03 16:29:52 +0000 | [diff] [blame] | 949 | # engineering notation, nonzero |
| 950 | dotplace = (leftdigits - 1) % 3 + 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 951 | |
Facundo Batista | 62edb71 | 2007-12-03 16:29:52 +0000 | [diff] [blame] | 952 | if dotplace <= 0: |
| 953 | intpart = '0' |
| 954 | fracpart = '.' + '0'*(-dotplace) + self._int |
| 955 | elif dotplace >= len(self._int): |
| 956 | intpart = self._int+'0'*(dotplace-len(self._int)) |
| 957 | fracpart = '' |
| 958 | else: |
| 959 | intpart = self._int[:dotplace] |
| 960 | fracpart = '.' + self._int[dotplace:] |
| 961 | if leftdigits == dotplace: |
| 962 | exp = '' |
| 963 | else: |
| 964 | if context is None: |
| 965 | context = getcontext() |
| 966 | exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace) |
| 967 | |
| 968 | return sign + intpart + fracpart + exp |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 969 | |
| 970 | def to_eng_string(self, context=None): |
| 971 | """Convert to engineering-type string. |
| 972 | |
| 973 | Engineering notation has an exponent which is a multiple of 3, so there |
| 974 | are up to 3 digits left of the decimal place. |
| 975 | |
| 976 | Same rules for when in exponential and when as a value as in __str__. |
| 977 | """ |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 978 | return self.__str__(eng=True, context=context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 979 | |
| 980 | def __neg__(self, context=None): |
| 981 | """Returns a copy with the sign switched. |
| 982 | |
| 983 | Rounds, if it has reason. |
| 984 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 985 | if self._is_special: |
| 986 | ans = self._check_nans(context=context) |
| 987 | if ans: |
| 988 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 989 | |
| 990 | if not self: |
| 991 | # -Decimal('0') is Decimal('0'), not Decimal('-0') |
Facundo Batista | 0f5e7bf | 2007-12-19 12:53:01 +0000 | [diff] [blame] | 992 | ans = self.copy_abs() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 993 | else: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 994 | ans = self.copy_negate() |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 995 | |
| 996 | if context is None: |
| 997 | context = getcontext() |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 998 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 999 | |
| 1000 | def __pos__(self, context=None): |
| 1001 | """Returns a copy, unless it is a sNaN. |
| 1002 | |
| 1003 | Rounds the number (if more then precision digits) |
| 1004 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1005 | if self._is_special: |
| 1006 | ans = self._check_nans(context=context) |
| 1007 | if ans: |
| 1008 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1009 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1010 | if not self: |
| 1011 | # + (-0) = 0 |
Facundo Batista | 0f5e7bf | 2007-12-19 12:53:01 +0000 | [diff] [blame] | 1012 | ans = self.copy_abs() |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1013 | else: |
| 1014 | ans = Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1015 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1016 | if context is None: |
| 1017 | context = getcontext() |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1018 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1019 | |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1020 | def __abs__(self, round=True, context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1021 | """Returns the absolute value of self. |
| 1022 | |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1023 | If the keyword argument 'round' is false, do not round. The |
| 1024 | expression self.__abs__(round=False) is equivalent to |
| 1025 | self.copy_abs(). |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1026 | """ |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1027 | if not round: |
| 1028 | return self.copy_abs() |
| 1029 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1030 | if self._is_special: |
| 1031 | ans = self._check_nans(context=context) |
| 1032 | if ans: |
| 1033 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1034 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1035 | if self._sign: |
| 1036 | ans = self.__neg__(context=context) |
| 1037 | else: |
| 1038 | ans = self.__pos__(context=context) |
| 1039 | |
| 1040 | return ans |
| 1041 | |
| 1042 | def __add__(self, other, context=None): |
| 1043 | """Returns self + other. |
| 1044 | |
| 1045 | -INF + INF (or the reverse) cause InvalidOperation errors. |
| 1046 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1047 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1048 | if other is NotImplemented: |
| 1049 | return other |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1050 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1051 | if context is None: |
| 1052 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1053 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1054 | if self._is_special or other._is_special: |
| 1055 | ans = self._check_nans(other, context) |
| 1056 | if ans: |
| 1057 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1058 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1059 | if self._isinfinity(): |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 1060 | # If both INF, same sign => same as both, opposite => error. |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1061 | if self._sign != other._sign and other._isinfinity(): |
| 1062 | return context._raise_error(InvalidOperation, '-INF + INF') |
| 1063 | return Decimal(self) |
| 1064 | if other._isinfinity(): |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 1065 | return Decimal(other) # Can't both be infinity here |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1066 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1067 | exp = min(self._exp, other._exp) |
| 1068 | negativezero = 0 |
| 1069 | if context.rounding == ROUND_FLOOR and self._sign != other._sign: |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 1070 | # 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] | 1071 | negativezero = 1 |
| 1072 | |
| 1073 | if not self and not other: |
| 1074 | sign = min(self._sign, other._sign) |
| 1075 | if negativezero: |
| 1076 | sign = 1 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1077 | ans = _dec_from_triple(sign, '0', exp) |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1078 | ans = ans._fix(context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1079 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1080 | if not self: |
Facundo Batista | 99b5548 | 2004-10-26 23:38:46 +0000 | [diff] [blame] | 1081 | exp = max(exp, other._exp - context.prec-1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1082 | ans = other._rescale(exp, context.rounding) |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1083 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1084 | return ans |
| 1085 | if not other: |
Facundo Batista | 99b5548 | 2004-10-26 23:38:46 +0000 | [diff] [blame] | 1086 | exp = max(exp, self._exp - context.prec-1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1087 | ans = self._rescale(exp, context.rounding) |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1088 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1089 | return ans |
| 1090 | |
| 1091 | op1 = _WorkRep(self) |
| 1092 | op2 = _WorkRep(other) |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1093 | op1, op2 = _normalize(op1, op2, context.prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1094 | |
| 1095 | result = _WorkRep() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1096 | if op1.sign != op2.sign: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1097 | # Equal and opposite |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1098 | if op1.int == op2.int: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1099 | ans = _dec_from_triple(negativezero, '0', exp) |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1100 | ans = ans._fix(context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1101 | return ans |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1102 | if op1.int < op2.int: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1103 | op1, op2 = op2, op1 |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 1104 | # OK, now abs(op1) > abs(op2) |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1105 | if op1.sign == 1: |
| 1106 | result.sign = 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1107 | op1.sign, op2.sign = op2.sign, op1.sign |
| 1108 | else: |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1109 | result.sign = 0 |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 1110 | # So we know the sign, and op1 > 0. |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1111 | elif op1.sign == 1: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1112 | result.sign = 1 |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1113 | op1.sign, op2.sign = (0, 0) |
| 1114 | else: |
| 1115 | result.sign = 0 |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 1116 | # Now, op1 > abs(op2) > 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1117 | |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1118 | if op2.sign == 0: |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1119 | result.int = op1.int + op2.int |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1120 | else: |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1121 | result.int = op1.int - op2.int |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1122 | |
| 1123 | result.exp = op1.exp |
| 1124 | ans = Decimal(result) |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1125 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1126 | return ans |
| 1127 | |
| 1128 | __radd__ = __add__ |
| 1129 | |
| 1130 | def __sub__(self, other, context=None): |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1131 | """Return self - other""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1132 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1133 | if other is NotImplemented: |
| 1134 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1135 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1136 | if self._is_special or other._is_special: |
| 1137 | ans = self._check_nans(other, context=context) |
| 1138 | if ans: |
| 1139 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1140 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1141 | # self - other is computed as self + other.copy_negate() |
| 1142 | return self.__add__(other.copy_negate(), context=context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1143 | |
| 1144 | def __rsub__(self, other, context=None): |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1145 | """Return other - self""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1146 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1147 | if other is NotImplemented: |
| 1148 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1149 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1150 | return other.__sub__(self, context=context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1151 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1152 | def __mul__(self, other, context=None): |
| 1153 | """Return self * other. |
| 1154 | |
| 1155 | (+-) INF * 0 (or its reverse) raise InvalidOperation. |
| 1156 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1157 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1158 | if other is NotImplemented: |
| 1159 | return other |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1160 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1161 | if context is None: |
| 1162 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1163 | |
Raymond Hettinger | d87ac8f | 2004-07-09 10:52:54 +0000 | [diff] [blame] | 1164 | resultsign = self._sign ^ other._sign |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1165 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1166 | if self._is_special or other._is_special: |
| 1167 | ans = self._check_nans(other, context) |
| 1168 | if ans: |
| 1169 | return ans |
| 1170 | |
| 1171 | if self._isinfinity(): |
| 1172 | if not other: |
| 1173 | return context._raise_error(InvalidOperation, '(+-)INF * 0') |
| 1174 | return Infsign[resultsign] |
| 1175 | |
| 1176 | if other._isinfinity(): |
| 1177 | if not self: |
| 1178 | return context._raise_error(InvalidOperation, '0 * (+-)INF') |
| 1179 | return Infsign[resultsign] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1180 | |
| 1181 | resultexp = self._exp + other._exp |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1182 | |
| 1183 | # Special case for multiplying by zero |
| 1184 | if not self or not other: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1185 | ans = _dec_from_triple(resultsign, '0', resultexp) |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1186 | # Fixing in case the exponent is out of bounds |
| 1187 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1188 | return ans |
| 1189 | |
| 1190 | # Special case for multiplying by power of 10 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1191 | if self._int == '1': |
| 1192 | ans = _dec_from_triple(resultsign, other._int, resultexp) |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1193 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1194 | return ans |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1195 | if other._int == '1': |
| 1196 | ans = _dec_from_triple(resultsign, self._int, resultexp) |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1197 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1198 | return ans |
| 1199 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1200 | op1 = _WorkRep(self) |
| 1201 | op2 = _WorkRep(other) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1202 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1203 | ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp) |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1204 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1205 | |
| 1206 | return ans |
| 1207 | __rmul__ = __mul__ |
| 1208 | |
Mark Dickinson | 8aca9d0 | 2008-05-04 02:05:06 +0000 | [diff] [blame] | 1209 | def __truediv__(self, other, context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1210 | """Return self / other.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1211 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1212 | if other is NotImplemented: |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1213 | return NotImplemented |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1214 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1215 | if context is None: |
| 1216 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1217 | |
Raymond Hettinger | d87ac8f | 2004-07-09 10:52:54 +0000 | [diff] [blame] | 1218 | sign = self._sign ^ other._sign |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1219 | |
| 1220 | if self._is_special or other._is_special: |
| 1221 | ans = self._check_nans(other, context) |
| 1222 | if ans: |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1223 | return ans |
| 1224 | |
| 1225 | if self._isinfinity() and other._isinfinity(): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1226 | return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1227 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1228 | if self._isinfinity(): |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1229 | return Infsign[sign] |
| 1230 | |
| 1231 | if other._isinfinity(): |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1232 | context._raise_error(Clamped, 'Division by infinity') |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1233 | return _dec_from_triple(sign, '0', context.Etiny()) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1234 | |
| 1235 | # Special cases for zeroes |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1236 | if not other: |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1237 | if not self: |
| 1238 | return context._raise_error(DivisionUndefined, '0 / 0') |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1239 | return context._raise_error(DivisionByZero, 'x / 0', sign) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1240 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1241 | if not self: |
| 1242 | exp = self._exp - other._exp |
| 1243 | coeff = 0 |
| 1244 | else: |
| 1245 | # OK, so neither = 0, INF or NaN |
| 1246 | shift = len(other._int) - len(self._int) + context.prec + 1 |
| 1247 | exp = self._exp - other._exp - shift |
| 1248 | op1 = _WorkRep(self) |
| 1249 | op2 = _WorkRep(other) |
| 1250 | if shift >= 0: |
| 1251 | coeff, remainder = divmod(op1.int * 10**shift, op2.int) |
| 1252 | else: |
| 1253 | coeff, remainder = divmod(op1.int, op2.int * 10**-shift) |
| 1254 | if remainder: |
| 1255 | # result is not exact; adjust to ensure correct rounding |
| 1256 | if coeff % 5 == 0: |
| 1257 | coeff += 1 |
| 1258 | else: |
| 1259 | # result is exact; get as close to ideal exponent as possible |
| 1260 | ideal_exp = self._exp - other._exp |
| 1261 | while exp < ideal_exp and coeff % 10 == 0: |
| 1262 | coeff //= 10 |
| 1263 | exp += 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1264 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1265 | ans = _dec_from_triple(sign, str(coeff), exp) |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1266 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1267 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1268 | def _divide(self, other, context): |
| 1269 | """Return (self // other, self % other), to context.prec precision. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1270 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1271 | Assumes that neither self nor other is a NaN, that self is not |
| 1272 | infinite and that other is nonzero. |
| 1273 | """ |
| 1274 | sign = self._sign ^ other._sign |
| 1275 | if other._isinfinity(): |
| 1276 | ideal_exp = self._exp |
| 1277 | else: |
| 1278 | ideal_exp = min(self._exp, other._exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1279 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1280 | expdiff = self.adjusted() - other.adjusted() |
| 1281 | if not self or other._isinfinity() or expdiff <= -2: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1282 | return (_dec_from_triple(sign, '0', 0), |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1283 | self._rescale(ideal_exp, context.rounding)) |
| 1284 | if expdiff <= context.prec: |
| 1285 | op1 = _WorkRep(self) |
| 1286 | op2 = _WorkRep(other) |
| 1287 | if op1.exp >= op2.exp: |
| 1288 | op1.int *= 10**(op1.exp - op2.exp) |
| 1289 | else: |
| 1290 | op2.int *= 10**(op2.exp - op1.exp) |
| 1291 | q, r = divmod(op1.int, op2.int) |
| 1292 | if q < 10**context.prec: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1293 | return (_dec_from_triple(sign, str(q), 0), |
| 1294 | _dec_from_triple(self._sign, str(r), ideal_exp)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1295 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1296 | # Here the quotient is too large to be representable |
| 1297 | ans = context._raise_error(DivisionImpossible, |
| 1298 | 'quotient too large in //, % or divmod') |
| 1299 | return ans, ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1300 | |
Mark Dickinson | 8aca9d0 | 2008-05-04 02:05:06 +0000 | [diff] [blame] | 1301 | def __rtruediv__(self, other, context=None): |
| 1302 | """Swaps self/other and returns __truediv__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1303 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1304 | if other is NotImplemented: |
| 1305 | return other |
Mark Dickinson | 8aca9d0 | 2008-05-04 02:05:06 +0000 | [diff] [blame] | 1306 | return other.__truediv__(self, context=context) |
| 1307 | |
| 1308 | __div__ = __truediv__ |
| 1309 | __rdiv__ = __rtruediv__ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1310 | |
| 1311 | def __divmod__(self, other, context=None): |
| 1312 | """ |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1313 | Return (self // other, self % other) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1314 | """ |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1315 | other = _convert_other(other) |
| 1316 | if other is NotImplemented: |
| 1317 | return other |
| 1318 | |
| 1319 | if context is None: |
| 1320 | context = getcontext() |
| 1321 | |
| 1322 | ans = self._check_nans(other, context) |
| 1323 | if ans: |
| 1324 | return (ans, ans) |
| 1325 | |
| 1326 | sign = self._sign ^ other._sign |
| 1327 | if self._isinfinity(): |
| 1328 | if other._isinfinity(): |
| 1329 | ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)') |
| 1330 | return ans, ans |
| 1331 | else: |
| 1332 | return (Infsign[sign], |
| 1333 | context._raise_error(InvalidOperation, 'INF % x')) |
| 1334 | |
| 1335 | if not other: |
| 1336 | if not self: |
| 1337 | ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)') |
| 1338 | return ans, ans |
| 1339 | else: |
| 1340 | return (context._raise_error(DivisionByZero, 'x // 0', sign), |
| 1341 | context._raise_error(InvalidOperation, 'x % 0')) |
| 1342 | |
| 1343 | quotient, remainder = self._divide(other, context) |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1344 | remainder = remainder._fix(context) |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1345 | return quotient, remainder |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1346 | |
| 1347 | def __rdivmod__(self, other, context=None): |
| 1348 | """Swaps self/other and returns __divmod__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1349 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1350 | if other is NotImplemented: |
| 1351 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1352 | return other.__divmod__(self, context=context) |
| 1353 | |
| 1354 | def __mod__(self, other, context=None): |
| 1355 | """ |
| 1356 | self % other |
| 1357 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1358 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1359 | if other is NotImplemented: |
| 1360 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1361 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1362 | if context is None: |
| 1363 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1364 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1365 | ans = self._check_nans(other, context) |
| 1366 | if ans: |
| 1367 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1368 | |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1369 | if self._isinfinity(): |
| 1370 | return context._raise_error(InvalidOperation, 'INF % x') |
| 1371 | elif not other: |
| 1372 | if self: |
| 1373 | return context._raise_error(InvalidOperation, 'x % 0') |
| 1374 | else: |
| 1375 | return context._raise_error(DivisionUndefined, '0 % 0') |
| 1376 | |
| 1377 | remainder = self._divide(other, context)[1] |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 1378 | remainder = remainder._fix(context) |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1379 | return remainder |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1380 | |
| 1381 | def __rmod__(self, other, context=None): |
| 1382 | """Swaps self/other and returns __mod__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1383 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1384 | if other is NotImplemented: |
| 1385 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1386 | return other.__mod__(self, context=context) |
| 1387 | |
| 1388 | def remainder_near(self, other, context=None): |
| 1389 | """ |
| 1390 | Remainder nearest to 0- abs(remainder-near) <= other/2 |
| 1391 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1392 | if context is None: |
| 1393 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1394 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1395 | other = _convert_other(other, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1396 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1397 | ans = self._check_nans(other, context) |
| 1398 | if ans: |
| 1399 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1400 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1401 | # self == +/-infinity -> InvalidOperation |
| 1402 | if self._isinfinity(): |
| 1403 | return context._raise_error(InvalidOperation, |
| 1404 | 'remainder_near(infinity, x)') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1405 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1406 | # other == 0 -> either InvalidOperation or DivisionUndefined |
| 1407 | if not other: |
| 1408 | if self: |
| 1409 | return context._raise_error(InvalidOperation, |
| 1410 | 'remainder_near(x, 0)') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1411 | else: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1412 | return context._raise_error(DivisionUndefined, |
| 1413 | 'remainder_near(0, 0)') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1414 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1415 | # other = +/-infinity -> remainder = self |
| 1416 | if other._isinfinity(): |
| 1417 | ans = Decimal(self) |
| 1418 | return ans._fix(context) |
| 1419 | |
| 1420 | # self = 0 -> remainder = self, with ideal exponent |
| 1421 | ideal_exponent = min(self._exp, other._exp) |
| 1422 | if not self: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1423 | ans = _dec_from_triple(self._sign, '0', ideal_exponent) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1424 | return ans._fix(context) |
| 1425 | |
| 1426 | # catch most cases of large or small quotient |
| 1427 | expdiff = self.adjusted() - other.adjusted() |
| 1428 | if expdiff >= context.prec + 1: |
| 1429 | # expdiff >= prec+1 => abs(self/other) > 10**prec |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1430 | return context._raise_error(DivisionImpossible) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1431 | if expdiff <= -2: |
| 1432 | # expdiff <= -2 => abs(self/other) < 0.1 |
| 1433 | ans = self._rescale(ideal_exponent, context.rounding) |
| 1434 | return ans._fix(context) |
| 1435 | |
| 1436 | # adjust both arguments to have the same exponent, then divide |
| 1437 | op1 = _WorkRep(self) |
| 1438 | op2 = _WorkRep(other) |
| 1439 | if op1.exp >= op2.exp: |
| 1440 | op1.int *= 10**(op1.exp - op2.exp) |
| 1441 | else: |
| 1442 | op2.int *= 10**(op2.exp - op1.exp) |
| 1443 | q, r = divmod(op1.int, op2.int) |
| 1444 | # remainder is r*10**ideal_exponent; other is +/-op2.int * |
| 1445 | # 10**ideal_exponent. Apply correction to ensure that |
| 1446 | # abs(remainder) <= abs(other)/2 |
| 1447 | if 2*r + (q&1) > op2.int: |
| 1448 | r -= op2.int |
| 1449 | q += 1 |
| 1450 | |
| 1451 | if q >= 10**context.prec: |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1452 | return context._raise_error(DivisionImpossible) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1453 | |
| 1454 | # result has same sign as self unless r is negative |
| 1455 | sign = self._sign |
| 1456 | if r < 0: |
| 1457 | sign = 1-sign |
| 1458 | r = -r |
| 1459 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1460 | ans = _dec_from_triple(sign, str(r), ideal_exponent) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1461 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1462 | |
| 1463 | def __floordiv__(self, other, context=None): |
| 1464 | """self // other""" |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 1465 | other = _convert_other(other) |
| 1466 | if other is NotImplemented: |
| 1467 | return other |
| 1468 | |
| 1469 | if context is None: |
| 1470 | context = getcontext() |
| 1471 | |
| 1472 | ans = self._check_nans(other, context) |
| 1473 | if ans: |
| 1474 | return ans |
| 1475 | |
| 1476 | if self._isinfinity(): |
| 1477 | if other._isinfinity(): |
| 1478 | return context._raise_error(InvalidOperation, 'INF // INF') |
| 1479 | else: |
| 1480 | return Infsign[self._sign ^ other._sign] |
| 1481 | |
| 1482 | if not other: |
| 1483 | if self: |
| 1484 | return context._raise_error(DivisionByZero, 'x // 0', |
| 1485 | self._sign ^ other._sign) |
| 1486 | else: |
| 1487 | return context._raise_error(DivisionUndefined, '0 // 0') |
| 1488 | |
| 1489 | return self._divide(other, context)[0] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1490 | |
| 1491 | def __rfloordiv__(self, other, context=None): |
| 1492 | """Swaps self/other and returns __floordiv__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1493 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1494 | if other is NotImplemented: |
| 1495 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1496 | return other.__floordiv__(self, context=context) |
| 1497 | |
| 1498 | def __float__(self): |
| 1499 | """Float representation.""" |
| 1500 | return float(str(self)) |
| 1501 | |
| 1502 | def __int__(self): |
Brett Cannon | 46b0802 | 2005-03-01 03:12:26 +0000 | [diff] [blame] | 1503 | """Converts self to an int, truncating if necessary.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1504 | if self._is_special: |
| 1505 | if self._isnan(): |
| 1506 | context = getcontext() |
| 1507 | return context._raise_error(InvalidContext) |
| 1508 | elif self._isinfinity(): |
Mark Dickinson | 8aca9d0 | 2008-05-04 02:05:06 +0000 | [diff] [blame] | 1509 | raise OverflowError("Cannot convert infinity to int") |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1510 | s = (-1)**self._sign |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1511 | if self._exp >= 0: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1512 | return s*int(self._int)*10**self._exp |
Raymond Hettinger | 605ed02 | 2004-11-24 07:28:48 +0000 | [diff] [blame] | 1513 | else: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1514 | return s*int(self._int[:self._exp] or '0') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1515 | |
Raymond Hettinger | 5a05364 | 2008-01-24 19:05:29 +0000 | [diff] [blame] | 1516 | __trunc__ = __int__ |
| 1517 | |
Raymond Hettinger | 116f72f | 2008-02-12 01:18:03 +0000 | [diff] [blame] | 1518 | @property |
| 1519 | def real(self): |
| 1520 | return self |
| 1521 | |
| 1522 | @property |
| 1523 | def imag(self): |
| 1524 | return Decimal(0) |
| 1525 | |
| 1526 | def conjugate(self): |
| 1527 | return self |
| 1528 | |
| 1529 | def __complex__(self): |
| 1530 | return complex(float(self)) |
| 1531 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1532 | def __long__(self): |
| 1533 | """Converts to a long. |
| 1534 | |
| 1535 | Equivalent to long(int(self)) |
| 1536 | """ |
| 1537 | return long(self.__int__()) |
| 1538 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1539 | def _fix_nan(self, context): |
| 1540 | """Decapitate the payload of a NaN to fit the context""" |
| 1541 | payload = self._int |
| 1542 | |
| 1543 | # maximum length of payload is precision if _clamp=0, |
| 1544 | # precision-1 if _clamp=1. |
| 1545 | max_payload_len = context.prec - context._clamp |
| 1546 | if len(payload) > max_payload_len: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1547 | payload = payload[len(payload)-max_payload_len:].lstrip('0') |
| 1548 | return _dec_from_triple(self._sign, payload, self._exp, True) |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 1549 | return Decimal(self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1550 | |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1551 | def _fix(self, context): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1552 | """Round if it is necessary to keep self within prec precision. |
| 1553 | |
| 1554 | Rounds and fixes the exponent. Does not raise on a sNaN. |
| 1555 | |
| 1556 | Arguments: |
| 1557 | self - Decimal instance |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1558 | context - context used. |
| 1559 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1560 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1561 | if self._is_special: |
| 1562 | if self._isnan(): |
| 1563 | # decapitate payload if necessary |
| 1564 | return self._fix_nan(context) |
| 1565 | else: |
| 1566 | # self is +/-Infinity; return unaltered |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 1567 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1568 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1569 | # if self is zero then exponent should be between Etiny and |
| 1570 | # Emax if _clamp==0, and between Etiny and Etop if _clamp==1. |
| 1571 | Etiny = context.Etiny() |
| 1572 | Etop = context.Etop() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1573 | if not self: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1574 | exp_max = [context.Emax, Etop][context._clamp] |
| 1575 | new_exp = min(max(self._exp, Etiny), exp_max) |
| 1576 | if new_exp != self._exp: |
| 1577 | context._raise_error(Clamped) |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1578 | return _dec_from_triple(self._sign, '0', new_exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1579 | else: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 1580 | return Decimal(self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1581 | |
| 1582 | # exp_min is the smallest allowable exponent of the result, |
| 1583 | # equal to max(self.adjusted()-context.prec+1, Etiny) |
| 1584 | exp_min = len(self._int) + self._exp - context.prec |
| 1585 | if exp_min > Etop: |
| 1586 | # overflow: exp_min > Etop iff self.adjusted() > Emax |
| 1587 | context._raise_error(Inexact) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1588 | context._raise_error(Rounded) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1589 | return context._raise_error(Overflow, 'above Emax', self._sign) |
| 1590 | self_is_subnormal = exp_min < Etiny |
| 1591 | if self_is_subnormal: |
| 1592 | context._raise_error(Subnormal) |
| 1593 | exp_min = Etiny |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1594 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1595 | # round if self has too many digits |
| 1596 | if self._exp < exp_min: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1597 | context._raise_error(Rounded) |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1598 | digits = len(self._int) + self._exp - exp_min |
| 1599 | if digits < 0: |
| 1600 | self = _dec_from_triple(self._sign, '1', exp_min-1) |
| 1601 | digits = 0 |
| 1602 | this_function = getattr(self, self._pick_rounding_function[context.rounding]) |
| 1603 | changed = this_function(digits) |
| 1604 | coeff = self._int[:digits] or '0' |
| 1605 | if changed == 1: |
| 1606 | coeff = str(int(coeff)+1) |
| 1607 | ans = _dec_from_triple(self._sign, coeff, exp_min) |
| 1608 | |
| 1609 | if changed: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1610 | context._raise_error(Inexact) |
| 1611 | if self_is_subnormal: |
| 1612 | context._raise_error(Underflow) |
| 1613 | if not ans: |
| 1614 | # raise Clamped on underflow to 0 |
| 1615 | context._raise_error(Clamped) |
| 1616 | elif len(ans._int) == context.prec+1: |
| 1617 | # we get here only if rescaling rounds the |
| 1618 | # cofficient up to exactly 10**context.prec |
| 1619 | if ans._exp < Etop: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1620 | ans = _dec_from_triple(ans._sign, |
| 1621 | ans._int[:-1], ans._exp+1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1622 | else: |
| 1623 | # Inexact and Rounded have already been raised |
| 1624 | ans = context._raise_error(Overflow, 'above Emax', |
| 1625 | self._sign) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1626 | return ans |
| 1627 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1628 | # fold down if _clamp == 1 and self has too few digits |
| 1629 | if context._clamp == 1 and self._exp > Etop: |
| 1630 | context._raise_error(Clamped) |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1631 | self_padded = self._int + '0'*(self._exp - Etop) |
| 1632 | return _dec_from_triple(self._sign, self_padded, Etop) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1633 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1634 | # here self was representable to begin with; return unchanged |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 1635 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1636 | |
| 1637 | _pick_rounding_function = {} |
| 1638 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1639 | # for each of the rounding functions below: |
| 1640 | # self is a finite, nonzero Decimal |
| 1641 | # prec is an integer satisfying 0 <= prec < len(self._int) |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1642 | # |
| 1643 | # each function returns either -1, 0, or 1, as follows: |
| 1644 | # 1 indicates that self should be rounded up (away from zero) |
| 1645 | # 0 indicates that self should be truncated, and that all the |
| 1646 | # digits to be truncated are zeros (so the value is unchanged) |
| 1647 | # -1 indicates that there are nonzero digits to be truncated |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1648 | |
| 1649 | def _round_down(self, prec): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1650 | """Also known as round-towards-0, truncate.""" |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1651 | if _all_zeros(self._int, prec): |
| 1652 | return 0 |
| 1653 | else: |
| 1654 | return -1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1655 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1656 | def _round_up(self, prec): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1657 | """Rounds away from 0.""" |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1658 | return -self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1659 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1660 | def _round_half_up(self, prec): |
| 1661 | """Rounds 5 up (away from 0)""" |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1662 | if self._int[prec] in '56789': |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1663 | return 1 |
| 1664 | elif _all_zeros(self._int, prec): |
| 1665 | return 0 |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1666 | else: |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1667 | return -1 |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1668 | |
| 1669 | def _round_half_down(self, prec): |
| 1670 | """Round 5 down""" |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1671 | if _exact_half(self._int, prec): |
| 1672 | return -1 |
| 1673 | else: |
| 1674 | return self._round_half_up(prec) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1675 | |
| 1676 | def _round_half_even(self, prec): |
| 1677 | """Round 5 to even, rest to nearest.""" |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1678 | if _exact_half(self._int, prec) and \ |
| 1679 | (prec == 0 or self._int[prec-1] in '02468'): |
| 1680 | return -1 |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1681 | else: |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1682 | return self._round_half_up(prec) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1683 | |
| 1684 | def _round_ceiling(self, prec): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1685 | """Rounds up (not away from 0 if negative.)""" |
| 1686 | if self._sign: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1687 | return self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1688 | else: |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1689 | return -self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1690 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1691 | def _round_floor(self, prec): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1692 | """Rounds down (not towards 0 if negative)""" |
| 1693 | if not self._sign: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1694 | return self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1695 | else: |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1696 | return -self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1697 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1698 | def _round_05up(self, prec): |
| 1699 | """Round down unless digit prec-1 is 0 or 5.""" |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1700 | if prec and self._int[prec-1] not in '05': |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1701 | return self._round_down(prec) |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 1702 | else: |
| 1703 | return -self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1704 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1705 | def fma(self, other, third, context=None): |
| 1706 | """Fused multiply-add. |
| 1707 | |
| 1708 | Returns self*other+third with no rounding of the intermediate |
| 1709 | product self*other. |
| 1710 | |
| 1711 | self and other are multiplied together, with no rounding of |
| 1712 | the result. The third operand is then added to the result, |
| 1713 | and a single final rounding is performed. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1714 | """ |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1715 | |
| 1716 | other = _convert_other(other, raiseit=True) |
Facundo Batista | 58f6f2e | 2007-12-04 16:31:53 +0000 | [diff] [blame] | 1717 | |
| 1718 | # compute product; raise InvalidOperation if either operand is |
| 1719 | # a signaling NaN or if the product is zero times infinity. |
| 1720 | if self._is_special or other._is_special: |
| 1721 | if context is None: |
| 1722 | context = getcontext() |
| 1723 | if self._exp == 'N': |
Facundo Batista | 0f5e7bf | 2007-12-19 12:53:01 +0000 | [diff] [blame] | 1724 | return context._raise_error(InvalidOperation, 'sNaN', self) |
Facundo Batista | 58f6f2e | 2007-12-04 16:31:53 +0000 | [diff] [blame] | 1725 | if other._exp == 'N': |
Facundo Batista | 0f5e7bf | 2007-12-19 12:53:01 +0000 | [diff] [blame] | 1726 | return context._raise_error(InvalidOperation, 'sNaN', other) |
Facundo Batista | 58f6f2e | 2007-12-04 16:31:53 +0000 | [diff] [blame] | 1727 | if self._exp == 'n': |
| 1728 | product = self |
| 1729 | elif other._exp == 'n': |
| 1730 | product = other |
| 1731 | elif self._exp == 'F': |
| 1732 | if not other: |
| 1733 | return context._raise_error(InvalidOperation, |
| 1734 | 'INF * 0 in fma') |
| 1735 | product = Infsign[self._sign ^ other._sign] |
| 1736 | elif other._exp == 'F': |
| 1737 | if not self: |
| 1738 | return context._raise_error(InvalidOperation, |
| 1739 | '0 * INF in fma') |
| 1740 | product = Infsign[self._sign ^ other._sign] |
| 1741 | else: |
| 1742 | product = _dec_from_triple(self._sign ^ other._sign, |
| 1743 | str(int(self._int) * int(other._int)), |
| 1744 | self._exp + other._exp) |
| 1745 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1746 | third = _convert_other(third, raiseit=True) |
Facundo Batista | 58f6f2e | 2007-12-04 16:31:53 +0000 | [diff] [blame] | 1747 | return product.__add__(third, context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1748 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1749 | def _power_modulo(self, other, modulo, context=None): |
| 1750 | """Three argument version of __pow__""" |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1751 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1752 | # if can't convert other and modulo to Decimal, raise |
| 1753 | # TypeError; there's no point returning NotImplemented (no |
| 1754 | # equivalent of __rpow__ for three argument pow) |
| 1755 | other = _convert_other(other, raiseit=True) |
| 1756 | modulo = _convert_other(modulo, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1757 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1758 | if context is None: |
| 1759 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1760 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1761 | # deal with NaNs: if there are any sNaNs then first one wins, |
| 1762 | # (i.e. behaviour for NaNs is identical to that of fma) |
| 1763 | self_is_nan = self._isnan() |
| 1764 | other_is_nan = other._isnan() |
| 1765 | modulo_is_nan = modulo._isnan() |
| 1766 | if self_is_nan or other_is_nan or modulo_is_nan: |
| 1767 | if self_is_nan == 2: |
| 1768 | return context._raise_error(InvalidOperation, 'sNaN', |
Facundo Batista | 0f5e7bf | 2007-12-19 12:53:01 +0000 | [diff] [blame] | 1769 | self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1770 | if other_is_nan == 2: |
| 1771 | return context._raise_error(InvalidOperation, 'sNaN', |
Facundo Batista | 0f5e7bf | 2007-12-19 12:53:01 +0000 | [diff] [blame] | 1772 | other) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1773 | if modulo_is_nan == 2: |
| 1774 | return context._raise_error(InvalidOperation, 'sNaN', |
Facundo Batista | 0f5e7bf | 2007-12-19 12:53:01 +0000 | [diff] [blame] | 1775 | modulo) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1776 | if self_is_nan: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 1777 | return self._fix_nan(context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1778 | if other_is_nan: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 1779 | return other._fix_nan(context) |
| 1780 | return modulo._fix_nan(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1781 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1782 | # check inputs: we apply same restrictions as Python's pow() |
| 1783 | if not (self._isinteger() and |
| 1784 | other._isinteger() and |
| 1785 | modulo._isinteger()): |
| 1786 | return context._raise_error(InvalidOperation, |
| 1787 | 'pow() 3rd argument not allowed ' |
| 1788 | 'unless all arguments are integers') |
| 1789 | if other < 0: |
| 1790 | return context._raise_error(InvalidOperation, |
| 1791 | 'pow() 2nd argument cannot be ' |
| 1792 | 'negative when 3rd argument specified') |
| 1793 | if not modulo: |
| 1794 | return context._raise_error(InvalidOperation, |
| 1795 | 'pow() 3rd argument cannot be 0') |
| 1796 | |
| 1797 | # additional restriction for decimal: the modulus must be less |
| 1798 | # than 10**prec in absolute value |
| 1799 | if modulo.adjusted() >= context.prec: |
| 1800 | return context._raise_error(InvalidOperation, |
| 1801 | 'insufficient precision: pow() 3rd ' |
| 1802 | 'argument must not have more than ' |
| 1803 | 'precision digits') |
| 1804 | |
| 1805 | # define 0**0 == NaN, for consistency with two-argument pow |
| 1806 | # (even though it hurts!) |
| 1807 | if not other and not self: |
| 1808 | return context._raise_error(InvalidOperation, |
| 1809 | 'at least one of pow() 1st argument ' |
| 1810 | 'and 2nd argument must be nonzero ;' |
| 1811 | '0**0 is not defined') |
| 1812 | |
| 1813 | # compute sign of result |
| 1814 | if other._iseven(): |
| 1815 | sign = 0 |
| 1816 | else: |
| 1817 | sign = self._sign |
| 1818 | |
| 1819 | # convert modulo to a Python integer, and self and other to |
| 1820 | # Decimal integers (i.e. force their exponents to be >= 0) |
| 1821 | modulo = abs(int(modulo)) |
| 1822 | base = _WorkRep(self.to_integral_value()) |
| 1823 | exponent = _WorkRep(other.to_integral_value()) |
| 1824 | |
| 1825 | # compute result using integer pow() |
| 1826 | base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo |
| 1827 | for i in xrange(exponent.exp): |
| 1828 | base = pow(base, 10, modulo) |
| 1829 | base = pow(base, exponent.int, modulo) |
| 1830 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1831 | return _dec_from_triple(sign, str(base), 0) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1832 | |
| 1833 | def _power_exact(self, other, p): |
| 1834 | """Attempt to compute self**other exactly. |
| 1835 | |
| 1836 | Given Decimals self and other and an integer p, attempt to |
| 1837 | compute an exact result for the power self**other, with p |
| 1838 | digits of precision. Return None if self**other is not |
| 1839 | exactly representable in p digits. |
| 1840 | |
| 1841 | Assumes that elimination of special cases has already been |
| 1842 | performed: self and other must both be nonspecial; self must |
| 1843 | be positive and not numerically equal to 1; other must be |
| 1844 | nonzero. For efficiency, other._exp should not be too large, |
| 1845 | so that 10**abs(other._exp) is a feasible calculation.""" |
| 1846 | |
| 1847 | # In the comments below, we write x for the value of self and |
| 1848 | # y for the value of other. Write x = xc*10**xe and y = |
| 1849 | # yc*10**ye. |
| 1850 | |
| 1851 | # The main purpose of this method is to identify the *failure* |
| 1852 | # of x**y to be exactly representable with as little effort as |
| 1853 | # possible. So we look for cheap and easy tests that |
| 1854 | # eliminate the possibility of x**y being exact. Only if all |
| 1855 | # these tests are passed do we go on to actually compute x**y. |
| 1856 | |
| 1857 | # Here's the main idea. First normalize both x and y. We |
| 1858 | # express y as a rational m/n, with m and n relatively prime |
| 1859 | # and n>0. Then for x**y to be exactly representable (at |
| 1860 | # *any* precision), xc must be the nth power of a positive |
| 1861 | # integer and xe must be divisible by n. If m is negative |
| 1862 | # then additionally xc must be a power of either 2 or 5, hence |
| 1863 | # a power of 2**n or 5**n. |
| 1864 | # |
| 1865 | # There's a limit to how small |y| can be: if y=m/n as above |
| 1866 | # then: |
| 1867 | # |
| 1868 | # (1) if xc != 1 then for the result to be representable we |
| 1869 | # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So |
| 1870 | # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <= |
| 1871 | # 2**(1/|y|), hence xc**|y| < 2 and the result is not |
| 1872 | # representable. |
| 1873 | # |
| 1874 | # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if |
| 1875 | # |y| < 1/|xe| then the result is not representable. |
| 1876 | # |
| 1877 | # Note that since x is not equal to 1, at least one of (1) and |
| 1878 | # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) < |
| 1879 | # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye. |
| 1880 | # |
| 1881 | # There's also a limit to how large y can be, at least if it's |
| 1882 | # positive: the normalized result will have coefficient xc**y, |
| 1883 | # so if it's representable then xc**y < 10**p, and y < |
| 1884 | # p/log10(xc). Hence if y*log10(xc) >= p then the result is |
| 1885 | # not exactly representable. |
| 1886 | |
| 1887 | # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye, |
| 1888 | # so |y| < 1/xe and the result is not representable. |
| 1889 | # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y| |
| 1890 | # < 1/nbits(xc). |
| 1891 | |
| 1892 | x = _WorkRep(self) |
| 1893 | xc, xe = x.int, x.exp |
| 1894 | while xc % 10 == 0: |
| 1895 | xc //= 10 |
| 1896 | xe += 1 |
| 1897 | |
| 1898 | y = _WorkRep(other) |
| 1899 | yc, ye = y.int, y.exp |
| 1900 | while yc % 10 == 0: |
| 1901 | yc //= 10 |
| 1902 | ye += 1 |
| 1903 | |
| 1904 | # case where xc == 1: result is 10**(xe*y), with xe*y |
| 1905 | # required to be an integer |
| 1906 | if xc == 1: |
| 1907 | if ye >= 0: |
| 1908 | exponent = xe*yc*10**ye |
| 1909 | else: |
| 1910 | exponent, remainder = divmod(xe*yc, 10**-ye) |
| 1911 | if remainder: |
| 1912 | return None |
| 1913 | if y.sign == 1: |
| 1914 | exponent = -exponent |
| 1915 | # if other is a nonnegative integer, use ideal exponent |
| 1916 | if other._isinteger() and other._sign == 0: |
| 1917 | ideal_exponent = self._exp*int(other) |
| 1918 | zeros = min(exponent-ideal_exponent, p-1) |
| 1919 | else: |
| 1920 | zeros = 0 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1921 | return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1922 | |
| 1923 | # case where y is negative: xc must be either a power |
| 1924 | # of 2 or a power of 5. |
| 1925 | if y.sign == 1: |
| 1926 | last_digit = xc % 10 |
| 1927 | if last_digit in (2,4,6,8): |
| 1928 | # quick test for power of 2 |
| 1929 | if xc & -xc != xc: |
| 1930 | return None |
| 1931 | # now xc is a power of 2; e is its exponent |
| 1932 | e = _nbits(xc)-1 |
| 1933 | # find e*y and xe*y; both must be integers |
| 1934 | if ye >= 0: |
| 1935 | y_as_int = yc*10**ye |
| 1936 | e = e*y_as_int |
| 1937 | xe = xe*y_as_int |
| 1938 | else: |
| 1939 | ten_pow = 10**-ye |
| 1940 | e, remainder = divmod(e*yc, ten_pow) |
| 1941 | if remainder: |
| 1942 | return None |
| 1943 | xe, remainder = divmod(xe*yc, ten_pow) |
| 1944 | if remainder: |
| 1945 | return None |
| 1946 | |
| 1947 | if e*65 >= p*93: # 93/65 > log(10)/log(5) |
| 1948 | return None |
| 1949 | xc = 5**e |
| 1950 | |
| 1951 | elif last_digit == 5: |
| 1952 | # e >= log_5(xc) if xc is a power of 5; we have |
| 1953 | # equality all the way up to xc=5**2658 |
| 1954 | e = _nbits(xc)*28//65 |
| 1955 | xc, remainder = divmod(5**e, xc) |
| 1956 | if remainder: |
| 1957 | return None |
| 1958 | while xc % 5 == 0: |
| 1959 | xc //= 5 |
| 1960 | e -= 1 |
| 1961 | if ye >= 0: |
| 1962 | y_as_integer = yc*10**ye |
| 1963 | e = e*y_as_integer |
| 1964 | xe = xe*y_as_integer |
| 1965 | else: |
| 1966 | ten_pow = 10**-ye |
| 1967 | e, remainder = divmod(e*yc, ten_pow) |
| 1968 | if remainder: |
| 1969 | return None |
| 1970 | xe, remainder = divmod(xe*yc, ten_pow) |
| 1971 | if remainder: |
| 1972 | return None |
| 1973 | if e*3 >= p*10: # 10/3 > log(10)/log(2) |
| 1974 | return None |
| 1975 | xc = 2**e |
| 1976 | else: |
| 1977 | return None |
| 1978 | |
| 1979 | if xc >= 10**p: |
| 1980 | return None |
| 1981 | xe = -e-xe |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 1982 | return _dec_from_triple(0, str(xc), xe) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1983 | |
| 1984 | # now y is positive; find m and n such that y = m/n |
| 1985 | if ye >= 0: |
| 1986 | m, n = yc*10**ye, 1 |
| 1987 | else: |
| 1988 | if xe != 0 and len(str(abs(yc*xe))) <= -ye: |
| 1989 | return None |
| 1990 | xc_bits = _nbits(xc) |
| 1991 | if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye: |
| 1992 | return None |
| 1993 | m, n = yc, 10**(-ye) |
| 1994 | while m % 2 == n % 2 == 0: |
| 1995 | m //= 2 |
| 1996 | n //= 2 |
| 1997 | while m % 5 == n % 5 == 0: |
| 1998 | m //= 5 |
| 1999 | n //= 5 |
| 2000 | |
| 2001 | # compute nth root of xc*10**xe |
| 2002 | if n > 1: |
| 2003 | # if 1 < xc < 2**n then xc isn't an nth power |
| 2004 | if xc != 1 and xc_bits <= n: |
| 2005 | return None |
| 2006 | |
| 2007 | xe, rem = divmod(xe, n) |
| 2008 | if rem != 0: |
| 2009 | return None |
| 2010 | |
| 2011 | # compute nth root of xc using Newton's method |
| 2012 | a = 1L << -(-_nbits(xc)//n) # initial estimate |
| 2013 | while True: |
| 2014 | q, r = divmod(xc, a**(n-1)) |
| 2015 | if a <= q: |
| 2016 | break |
| 2017 | else: |
| 2018 | a = (a*(n-1) + q)//n |
| 2019 | if not (a == q and r == 0): |
| 2020 | return None |
| 2021 | xc = a |
| 2022 | |
| 2023 | # now xc*10**xe is the nth root of the original xc*10**xe |
| 2024 | # compute mth power of xc*10**xe |
| 2025 | |
| 2026 | # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m > |
| 2027 | # 10**p and the result is not representable. |
| 2028 | if xc > 1 and m > p*100//_log10_lb(xc): |
| 2029 | return None |
| 2030 | xc = xc**m |
| 2031 | xe *= m |
| 2032 | if xc > 10**p: |
| 2033 | return None |
| 2034 | |
| 2035 | # by this point the result *is* exactly representable |
| 2036 | # adjust the exponent to get as close as possible to the ideal |
| 2037 | # exponent, if necessary |
| 2038 | str_xc = str(xc) |
| 2039 | if other._isinteger() and other._sign == 0: |
| 2040 | ideal_exponent = self._exp*int(other) |
| 2041 | zeros = min(xe-ideal_exponent, p-len(str_xc)) |
| 2042 | else: |
| 2043 | zeros = 0 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2044 | return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2045 | |
| 2046 | def __pow__(self, other, modulo=None, context=None): |
| 2047 | """Return self ** other [ % modulo]. |
| 2048 | |
| 2049 | With two arguments, compute self**other. |
| 2050 | |
| 2051 | With three arguments, compute (self**other) % modulo. For the |
| 2052 | three argument form, the following restrictions on the |
| 2053 | arguments hold: |
| 2054 | |
| 2055 | - all three arguments must be integral |
| 2056 | - other must be nonnegative |
| 2057 | - either self or other (or both) must be nonzero |
| 2058 | - modulo must be nonzero and must have at most p digits, |
| 2059 | where p is the context precision. |
| 2060 | |
| 2061 | If any of these restrictions is violated the InvalidOperation |
| 2062 | flag is raised. |
| 2063 | |
| 2064 | The result of pow(self, other, modulo) is identical to the |
| 2065 | result that would be obtained by computing (self**other) % |
| 2066 | modulo with unbounded precision, but is computed more |
| 2067 | efficiently. It is always exact. |
| 2068 | """ |
| 2069 | |
| 2070 | if modulo is not None: |
| 2071 | return self._power_modulo(other, modulo, context) |
| 2072 | |
| 2073 | other = _convert_other(other) |
| 2074 | if other is NotImplemented: |
| 2075 | return other |
| 2076 | |
| 2077 | if context is None: |
| 2078 | context = getcontext() |
| 2079 | |
| 2080 | # either argument is a NaN => result is NaN |
| 2081 | ans = self._check_nans(other, context) |
| 2082 | if ans: |
| 2083 | return ans |
| 2084 | |
| 2085 | # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity) |
| 2086 | if not other: |
| 2087 | if not self: |
| 2088 | return context._raise_error(InvalidOperation, '0 ** 0') |
| 2089 | else: |
| 2090 | return Dec_p1 |
| 2091 | |
| 2092 | # result has sign 1 iff self._sign is 1 and other is an odd integer |
| 2093 | result_sign = 0 |
| 2094 | if self._sign == 1: |
| 2095 | if other._isinteger(): |
| 2096 | if not other._iseven(): |
| 2097 | result_sign = 1 |
| 2098 | else: |
| 2099 | # -ve**noninteger = NaN |
| 2100 | # (-0)**noninteger = 0**noninteger |
| 2101 | if self: |
| 2102 | return context._raise_error(InvalidOperation, |
| 2103 | 'x ** y with x negative and y not an integer') |
| 2104 | # negate self, without doing any unwanted rounding |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2105 | self = self.copy_negate() |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2106 | |
| 2107 | # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity |
| 2108 | if not self: |
| 2109 | if other._sign == 0: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2110 | return _dec_from_triple(result_sign, '0', 0) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2111 | else: |
| 2112 | return Infsign[result_sign] |
| 2113 | |
| 2114 | # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2115 | if self._isinfinity(): |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2116 | if other._sign == 0: |
| 2117 | return Infsign[result_sign] |
| 2118 | else: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2119 | return _dec_from_triple(result_sign, '0', 0) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2120 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2121 | # 1**other = 1, but the choice of exponent and the flags |
| 2122 | # depend on the exponent of self, and on whether other is a |
| 2123 | # positive integer, a negative integer, or neither |
| 2124 | if self == Dec_p1: |
| 2125 | if other._isinteger(): |
| 2126 | # exp = max(self._exp*max(int(other), 0), |
| 2127 | # 1-context.prec) but evaluating int(other) directly |
| 2128 | # is dangerous until we know other is small (other |
| 2129 | # could be 1e999999999) |
| 2130 | if other._sign == 1: |
| 2131 | multiplier = 0 |
| 2132 | elif other > context.prec: |
| 2133 | multiplier = context.prec |
| 2134 | else: |
| 2135 | multiplier = int(other) |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 2136 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2137 | exp = self._exp * multiplier |
| 2138 | if exp < 1-context.prec: |
| 2139 | exp = 1-context.prec |
| 2140 | context._raise_error(Rounded) |
| 2141 | else: |
| 2142 | context._raise_error(Inexact) |
| 2143 | context._raise_error(Rounded) |
| 2144 | exp = 1-context.prec |
| 2145 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2146 | return _dec_from_triple(result_sign, '1'+'0'*-exp, exp) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2147 | |
| 2148 | # compute adjusted exponent of self |
| 2149 | self_adj = self.adjusted() |
| 2150 | |
| 2151 | # self ** infinity is infinity if self > 1, 0 if self < 1 |
| 2152 | # self ** -infinity is infinity if self < 1, 0 if self > 1 |
| 2153 | if other._isinfinity(): |
| 2154 | if (other._sign == 0) == (self_adj < 0): |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2155 | return _dec_from_triple(result_sign, '0', 0) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2156 | else: |
| 2157 | return Infsign[result_sign] |
| 2158 | |
| 2159 | # from here on, the result always goes through the call |
| 2160 | # to _fix at the end of this function. |
| 2161 | ans = None |
| 2162 | |
| 2163 | # crude test to catch cases of extreme overflow/underflow. If |
| 2164 | # log10(self)*other >= 10**bound and bound >= len(str(Emax)) |
| 2165 | # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence |
| 2166 | # self**other >= 10**(Emax+1), so overflow occurs. The test |
| 2167 | # for underflow is similar. |
| 2168 | bound = self._log10_exp_bound() + other.adjusted() |
| 2169 | if (self_adj >= 0) == (other._sign == 0): |
| 2170 | # self > 1 and other +ve, or self < 1 and other -ve |
| 2171 | # possibility of overflow |
| 2172 | if bound >= len(str(context.Emax)): |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2173 | ans = _dec_from_triple(result_sign, '1', context.Emax+1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2174 | else: |
| 2175 | # self > 1 and other -ve, or self < 1 and other +ve |
| 2176 | # possibility of underflow to 0 |
| 2177 | Etiny = context.Etiny() |
| 2178 | if bound >= len(str(-Etiny)): |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2179 | ans = _dec_from_triple(result_sign, '1', Etiny-1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2180 | |
| 2181 | # try for an exact result with precision +1 |
| 2182 | if ans is None: |
| 2183 | ans = self._power_exact(other, context.prec + 1) |
| 2184 | if ans is not None and result_sign == 1: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2185 | ans = _dec_from_triple(1, ans._int, ans._exp) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2186 | |
| 2187 | # usual case: inexact result, x**y computed directly as exp(y*log(x)) |
| 2188 | if ans is None: |
| 2189 | p = context.prec |
| 2190 | x = _WorkRep(self) |
| 2191 | xc, xe = x.int, x.exp |
| 2192 | y = _WorkRep(other) |
| 2193 | yc, ye = y.int, y.exp |
| 2194 | if y.sign == 1: |
| 2195 | yc = -yc |
| 2196 | |
| 2197 | # compute correctly rounded result: start with precision +3, |
| 2198 | # then increase precision until result is unambiguously roundable |
| 2199 | extra = 3 |
| 2200 | while True: |
| 2201 | coeff, exp = _dpower(xc, xe, yc, ye, p+extra) |
| 2202 | if coeff % (5*10**(len(str(coeff))-p-1)): |
| 2203 | break |
| 2204 | extra += 3 |
| 2205 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2206 | ans = _dec_from_triple(result_sign, str(coeff), exp) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2207 | |
| 2208 | # the specification says that for non-integer other we need to |
| 2209 | # raise Inexact, even when the result is actually exact. In |
| 2210 | # the same way, we need to raise Underflow here if the result |
| 2211 | # is subnormal. (The call to _fix will take care of raising |
| 2212 | # Rounded and Subnormal, as usual.) |
| 2213 | if not other._isinteger(): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2214 | context._raise_error(Inexact) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2215 | # pad with zeros up to length context.prec+1 if necessary |
| 2216 | if len(ans._int) <= context.prec: |
| 2217 | expdiff = context.prec+1 - len(ans._int) |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2218 | ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff, |
| 2219 | ans._exp-expdiff) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2220 | if ans.adjusted() < context.Emin: |
| 2221 | context._raise_error(Underflow) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2222 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2223 | # unlike exp, ln and log10, the power function respects the |
| 2224 | # rounding mode; no need to use ROUND_HALF_EVEN here |
| 2225 | ans = ans._fix(context) |
| 2226 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2227 | |
| 2228 | def __rpow__(self, other, context=None): |
| 2229 | """Swaps self/other and returns __pow__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2230 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 2231 | if other is NotImplemented: |
| 2232 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2233 | return other.__pow__(self, context=context) |
| 2234 | |
| 2235 | def normalize(self, context=None): |
| 2236 | """Normalize- strip trailing 0s, change anything equal to 0 to 0e0""" |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2237 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2238 | if context is None: |
| 2239 | context = getcontext() |
| 2240 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2241 | if self._is_special: |
| 2242 | ans = self._check_nans(context=context) |
| 2243 | if ans: |
| 2244 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2245 | |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 2246 | dup = self._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2247 | if dup._isinfinity(): |
| 2248 | return dup |
| 2249 | |
| 2250 | if not dup: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2251 | return _dec_from_triple(dup._sign, '0', 0) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2252 | exp_max = [context.Emax, context.Etop()][context._clamp] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2253 | end = len(dup._int) |
| 2254 | exp = dup._exp |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2255 | while dup._int[end-1] == '0' and exp < exp_max: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2256 | exp += 1 |
| 2257 | end -= 1 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2258 | return _dec_from_triple(dup._sign, dup._int[:end], exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2259 | |
Facundo Batista | bd2fe83 | 2007-09-13 18:42:09 +0000 | [diff] [blame] | 2260 | def quantize(self, exp, rounding=None, context=None, watchexp=True): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2261 | """Quantize self so its exponent is the same as that of exp. |
| 2262 | |
| 2263 | Similar to self._rescale(exp._exp) but with error checking. |
| 2264 | """ |
Facundo Batista | bd2fe83 | 2007-09-13 18:42:09 +0000 | [diff] [blame] | 2265 | exp = _convert_other(exp, raiseit=True) |
| 2266 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2267 | if context is None: |
| 2268 | context = getcontext() |
| 2269 | if rounding is None: |
| 2270 | rounding = context.rounding |
| 2271 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2272 | if self._is_special or exp._is_special: |
| 2273 | ans = self._check_nans(exp, context) |
| 2274 | if ans: |
| 2275 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2276 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2277 | if exp._isinfinity() or self._isinfinity(): |
| 2278 | if exp._isinfinity() and self._isinfinity(): |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2279 | return Decimal(self) # if both are inf, it is OK |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2280 | return context._raise_error(InvalidOperation, |
| 2281 | 'quantize with one INF') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2282 | |
Facundo Batista | bd2fe83 | 2007-09-13 18:42:09 +0000 | [diff] [blame] | 2283 | # if we're not watching exponents, do a simple rescale |
| 2284 | if not watchexp: |
| 2285 | ans = self._rescale(exp._exp, rounding) |
| 2286 | # raise Inexact and Rounded where appropriate |
| 2287 | if ans._exp > self._exp: |
| 2288 | context._raise_error(Rounded) |
| 2289 | if ans != self: |
| 2290 | context._raise_error(Inexact) |
| 2291 | return ans |
| 2292 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2293 | # exp._exp should be between Etiny and Emax |
| 2294 | if not (context.Etiny() <= exp._exp <= context.Emax): |
| 2295 | return context._raise_error(InvalidOperation, |
| 2296 | 'target exponent out of bounds in quantize') |
| 2297 | |
| 2298 | if not self: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2299 | ans = _dec_from_triple(self._sign, '0', exp._exp) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2300 | return ans._fix(context) |
| 2301 | |
| 2302 | self_adjusted = self.adjusted() |
| 2303 | if self_adjusted > context.Emax: |
| 2304 | return context._raise_error(InvalidOperation, |
| 2305 | 'exponent of quantize result too large for current context') |
| 2306 | if self_adjusted - exp._exp + 1 > context.prec: |
| 2307 | return context._raise_error(InvalidOperation, |
| 2308 | 'quantize result has too many digits for current context') |
| 2309 | |
| 2310 | ans = self._rescale(exp._exp, rounding) |
| 2311 | if ans.adjusted() > context.Emax: |
| 2312 | return context._raise_error(InvalidOperation, |
| 2313 | 'exponent of quantize result too large for current context') |
| 2314 | if len(ans._int) > context.prec: |
| 2315 | return context._raise_error(InvalidOperation, |
| 2316 | 'quantize result has too many digits for current context') |
| 2317 | |
| 2318 | # raise appropriate flags |
| 2319 | if ans._exp > self._exp: |
| 2320 | context._raise_error(Rounded) |
| 2321 | if ans != self: |
| 2322 | context._raise_error(Inexact) |
| 2323 | if ans and ans.adjusted() < context.Emin: |
| 2324 | context._raise_error(Subnormal) |
| 2325 | |
| 2326 | # call to fix takes care of any necessary folddown |
| 2327 | ans = ans._fix(context) |
| 2328 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2329 | |
| 2330 | def same_quantum(self, other): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2331 | """Return True if self and other have the same exponent; otherwise |
| 2332 | return False. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2333 | |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2334 | If either operand is a special value, the following rules are used: |
| 2335 | * return True if both operands are infinities |
| 2336 | * return True if both operands are NaNs |
| 2337 | * otherwise, return False. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2338 | """ |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2339 | other = _convert_other(other, raiseit=True) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2340 | if self._is_special or other._is_special: |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2341 | return (self.is_nan() and other.is_nan() or |
| 2342 | self.is_infinite() and other.is_infinite()) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2343 | return self._exp == other._exp |
| 2344 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2345 | def _rescale(self, exp, rounding): |
| 2346 | """Rescale self so that the exponent is exp, either by padding with zeros |
| 2347 | or by truncating digits, using the given rounding mode. |
| 2348 | |
| 2349 | Specials are returned without change. This operation is |
| 2350 | quiet: it raises no flags, and uses no information from the |
| 2351 | context. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2352 | |
| 2353 | exp = exp to scale to (an integer) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2354 | rounding = rounding mode |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2355 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2356 | if self._is_special: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2357 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2358 | if not self: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2359 | return _dec_from_triple(self._sign, '0', exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2360 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2361 | if self._exp >= exp: |
| 2362 | # pad answer with zeros if necessary |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2363 | return _dec_from_triple(self._sign, |
| 2364 | self._int + '0'*(self._exp - exp), exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2365 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2366 | # too many digits; round and lose data. If self.adjusted() < |
| 2367 | # exp-1, replace self by 10**(exp-1) before rounding |
| 2368 | digits = len(self._int) + self._exp - exp |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2369 | if digits < 0: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2370 | self = _dec_from_triple(self._sign, '1', exp-1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2371 | digits = 0 |
| 2372 | this_function = getattr(self, self._pick_rounding_function[rounding]) |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 2373 | changed = this_function(digits) |
| 2374 | coeff = self._int[:digits] or '0' |
| 2375 | if changed == 1: |
| 2376 | coeff = str(int(coeff)+1) |
| 2377 | return _dec_from_triple(self._sign, coeff, exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2378 | |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 2379 | def _round(self, places, rounding): |
| 2380 | """Round a nonzero, nonspecial Decimal to a fixed number of |
| 2381 | significant figures, using the given rounding mode. |
| 2382 | |
| 2383 | Infinities, NaNs and zeros are returned unaltered. |
| 2384 | |
| 2385 | This operation is quiet: it raises no flags, and uses no |
| 2386 | information from the context. |
| 2387 | |
| 2388 | """ |
| 2389 | if places <= 0: |
| 2390 | raise ValueError("argument should be at least 1 in _round") |
| 2391 | if self._is_special or not self: |
| 2392 | return Decimal(self) |
| 2393 | ans = self._rescale(self.adjusted()+1-places, rounding) |
| 2394 | # it can happen that the rescale alters the adjusted exponent; |
| 2395 | # for example when rounding 99.97 to 3 significant figures. |
| 2396 | # When this happens we end up with an extra 0 at the end of |
| 2397 | # the number; a second rescale fixes this. |
| 2398 | if ans.adjusted() != self.adjusted(): |
| 2399 | ans = ans._rescale(ans.adjusted()+1-places, rounding) |
| 2400 | return ans |
| 2401 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2402 | def to_integral_exact(self, rounding=None, context=None): |
| 2403 | """Rounds to a nearby integer. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2404 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2405 | If no rounding mode is specified, take the rounding mode from |
| 2406 | the context. This method raises the Rounded and Inexact flags |
| 2407 | when appropriate. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2408 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2409 | See also: to_integral_value, which does exactly the same as |
| 2410 | this method except that it doesn't raise Inexact or Rounded. |
| 2411 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2412 | if self._is_special: |
| 2413 | ans = self._check_nans(context=context) |
| 2414 | if ans: |
| 2415 | return ans |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2416 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2417 | if self._exp >= 0: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2418 | return Decimal(self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2419 | if not self: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2420 | return _dec_from_triple(self._sign, '0', 0) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2421 | if context is None: |
| 2422 | context = getcontext() |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2423 | if rounding is None: |
| 2424 | rounding = context.rounding |
| 2425 | context._raise_error(Rounded) |
| 2426 | ans = self._rescale(0, rounding) |
| 2427 | if ans != self: |
| 2428 | context._raise_error(Inexact) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2429 | return ans |
| 2430 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2431 | def to_integral_value(self, rounding=None, context=None): |
| 2432 | """Rounds to the nearest integer, without raising inexact, rounded.""" |
| 2433 | if context is None: |
| 2434 | context = getcontext() |
| 2435 | if rounding is None: |
| 2436 | rounding = context.rounding |
| 2437 | if self._is_special: |
| 2438 | ans = self._check_nans(context=context) |
| 2439 | if ans: |
| 2440 | return ans |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2441 | return Decimal(self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2442 | if self._exp >= 0: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2443 | return Decimal(self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2444 | else: |
| 2445 | return self._rescale(0, rounding) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2446 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2447 | # the method name changed, but we provide also the old one, for compatibility |
| 2448 | to_integral = to_integral_value |
| 2449 | |
| 2450 | def sqrt(self, context=None): |
| 2451 | """Return the square root of self.""" |
Mark Dickinson | 3b24ccb | 2008-03-25 14:33:23 +0000 | [diff] [blame] | 2452 | if context is None: |
| 2453 | context = getcontext() |
| 2454 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2455 | if self._is_special: |
| 2456 | ans = self._check_nans(context=context) |
| 2457 | if ans: |
| 2458 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2459 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2460 | if self._isinfinity() and self._sign == 0: |
| 2461 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2462 | |
| 2463 | if not self: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2464 | # exponent = self._exp // 2. sqrt(-0) = -0 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2465 | ans = _dec_from_triple(self._sign, '0', self._exp // 2) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2466 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2467 | |
| 2468 | if self._sign == 1: |
| 2469 | return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0') |
| 2470 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2471 | # At this point self represents a positive number. Let p be |
| 2472 | # the desired precision and express self in the form c*100**e |
| 2473 | # with c a positive real number and e an integer, c and e |
| 2474 | # being chosen so that 100**(p-1) <= c < 100**p. Then the |
| 2475 | # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1) |
| 2476 | # <= sqrt(c) < 10**p, so the closest representable Decimal at |
| 2477 | # precision p is n*10**e where n = round_half_even(sqrt(c)), |
| 2478 | # the closest integer to sqrt(c) with the even integer chosen |
| 2479 | # in the case of a tie. |
| 2480 | # |
| 2481 | # To ensure correct rounding in all cases, we use the |
| 2482 | # following trick: we compute the square root to an extra |
| 2483 | # place (precision p+1 instead of precision p), rounding down. |
| 2484 | # Then, if the result is inexact and its last digit is 0 or 5, |
| 2485 | # we increase the last digit to 1 or 6 respectively; if it's |
| 2486 | # exact we leave the last digit alone. Now the final round to |
| 2487 | # p places (or fewer in the case of underflow) will round |
| 2488 | # correctly and raise the appropriate flags. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2489 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2490 | # use an extra digit of precision |
| 2491 | prec = context.prec+1 |
| 2492 | |
| 2493 | # write argument in the form c*100**e where e = self._exp//2 |
| 2494 | # is the 'ideal' exponent, to be used if the square root is |
| 2495 | # exactly representable. l is the number of 'digits' of c in |
| 2496 | # base 100, so that 100**(l-1) <= c < 100**l. |
| 2497 | op = _WorkRep(self) |
| 2498 | e = op.exp >> 1 |
| 2499 | if op.exp & 1: |
| 2500 | c = op.int * 10 |
| 2501 | l = (len(self._int) >> 1) + 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2502 | else: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2503 | c = op.int |
| 2504 | l = len(self._int)+1 >> 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2505 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2506 | # rescale so that c has exactly prec base 100 'digits' |
| 2507 | shift = prec-l |
| 2508 | if shift >= 0: |
| 2509 | c *= 100**shift |
| 2510 | exact = True |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2511 | else: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2512 | c, remainder = divmod(c, 100**-shift) |
| 2513 | exact = not remainder |
| 2514 | e -= shift |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 2515 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2516 | # find n = floor(sqrt(c)) using Newton's method |
| 2517 | n = 10**prec |
| 2518 | while True: |
| 2519 | q = c//n |
| 2520 | if n <= q: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2521 | break |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2522 | else: |
| 2523 | n = n + q >> 1 |
| 2524 | exact = exact and n*n == c |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2525 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2526 | if exact: |
| 2527 | # result is exact; rescale to use ideal exponent e |
| 2528 | if shift >= 0: |
| 2529 | # assert n % 10**shift == 0 |
| 2530 | n //= 10**shift |
| 2531 | else: |
| 2532 | n *= 10**-shift |
| 2533 | e += shift |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2534 | else: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2535 | # result is not exact; fix last digit as described above |
| 2536 | if n % 5 == 0: |
| 2537 | n += 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2538 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2539 | ans = _dec_from_triple(0, str(n), e) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2540 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2541 | # round, and fit to current context |
| 2542 | context = context._shallow_copy() |
| 2543 | rounding = context._set_rounding(ROUND_HALF_EVEN) |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 2544 | ans = ans._fix(context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2545 | context.rounding = rounding |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2546 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2547 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2548 | |
| 2549 | def max(self, other, context=None): |
| 2550 | """Returns the larger value. |
| 2551 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2552 | Like max(self, other) except if one is not a number, returns |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2553 | NaN (and signals if one is sNaN). Also rounds. |
| 2554 | """ |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2555 | other = _convert_other(other, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2556 | |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2557 | if context is None: |
| 2558 | context = getcontext() |
| 2559 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2560 | if self._is_special or other._is_special: |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 2561 | # 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] | 2562 | # number is always returned |
| 2563 | sn = self._isnan() |
| 2564 | on = other._isnan() |
| 2565 | if sn or on: |
| 2566 | if on == 1 and sn != 2: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2567 | return self._fix_nan(context) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2568 | if sn == 1 and on != 2: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2569 | return other._fix_nan(context) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2570 | return self._check_nans(other, context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2571 | |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 2572 | c = self._cmp(other) |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2573 | if c == 0: |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 2574 | # If both operands are finite and equal in numerical value |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2575 | # then an ordering is applied: |
| 2576 | # |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 2577 | # If the signs differ then max returns the operand with the |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2578 | # positive sign and min returns the operand with the negative sign |
| 2579 | # |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 2580 | # 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] | 2581 | # the result. This is exactly the ordering used in compare_total. |
| 2582 | c = self.compare_total(other) |
| 2583 | |
| 2584 | if c == -1: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2585 | ans = other |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2586 | else: |
| 2587 | ans = self |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2588 | |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 2589 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2590 | |
| 2591 | def min(self, other, context=None): |
| 2592 | """Returns the smaller value. |
| 2593 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 2594 | Like min(self, other) except if one is not a number, returns |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2595 | NaN (and signals if one is sNaN). Also rounds. |
| 2596 | """ |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2597 | other = _convert_other(other, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2598 | |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2599 | if context is None: |
| 2600 | context = getcontext() |
| 2601 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2602 | if self._is_special or other._is_special: |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 2603 | # 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] | 2604 | # number is always returned |
| 2605 | sn = self._isnan() |
| 2606 | on = other._isnan() |
| 2607 | if sn or on: |
| 2608 | if on == 1 and sn != 2: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2609 | return self._fix_nan(context) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2610 | if sn == 1 and on != 2: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 2611 | return other._fix_nan(context) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2612 | return self._check_nans(other, context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2613 | |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 2614 | c = self._cmp(other) |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2615 | if c == 0: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2616 | c = self.compare_total(other) |
| 2617 | |
| 2618 | if c == -1: |
| 2619 | ans = self |
| 2620 | else: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2621 | ans = other |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2622 | |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 2623 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2624 | |
| 2625 | def _isinteger(self): |
| 2626 | """Returns whether self is an integer""" |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2627 | if self._is_special: |
| 2628 | return False |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2629 | if self._exp >= 0: |
| 2630 | return True |
| 2631 | rest = self._int[self._exp:] |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2632 | return rest == '0'*len(rest) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2633 | |
| 2634 | def _iseven(self): |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2635 | """Returns True if self is even. Assumes self is an integer.""" |
| 2636 | if not self or self._exp > 0: |
| 2637 | return True |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2638 | return self._int[-1+self._exp] in '02468' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2639 | |
| 2640 | def adjusted(self): |
| 2641 | """Return the adjusted exponent of self""" |
| 2642 | try: |
| 2643 | return self._exp + len(self._int) - 1 |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 2644 | # If NaN or Infinity, self._exp is string |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2645 | except TypeError: |
| 2646 | return 0 |
| 2647 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2648 | def canonical(self, context=None): |
| 2649 | """Returns the same Decimal object. |
| 2650 | |
| 2651 | As we do not have different encodings for the same number, the |
| 2652 | received object already is in its canonical form. |
| 2653 | """ |
| 2654 | return self |
| 2655 | |
| 2656 | def compare_signal(self, other, context=None): |
| 2657 | """Compares self to the other operand numerically. |
| 2658 | |
| 2659 | It's pretty much like compare(), but all NaNs signal, with signaling |
| 2660 | NaNs taking precedence over quiet NaNs. |
| 2661 | """ |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 2662 | other = _convert_other(other, raiseit = True) |
| 2663 | ans = self._compare_check_nans(other, context) |
| 2664 | if ans: |
| 2665 | return ans |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2666 | return self.compare(other, context=context) |
| 2667 | |
| 2668 | def compare_total(self, other): |
| 2669 | """Compares self to other using the abstract representations. |
| 2670 | |
| 2671 | This is not like the standard compare, which use their numerical |
| 2672 | value. Note that a total ordering is defined for all possible abstract |
| 2673 | representations. |
| 2674 | """ |
| 2675 | # if one is negative and the other is positive, it's easy |
| 2676 | if self._sign and not other._sign: |
| 2677 | return Dec_n1 |
| 2678 | if not self._sign and other._sign: |
| 2679 | return Dec_p1 |
| 2680 | sign = self._sign |
| 2681 | |
| 2682 | # let's handle both NaN types |
| 2683 | self_nan = self._isnan() |
| 2684 | other_nan = other._isnan() |
| 2685 | if self_nan or other_nan: |
| 2686 | if self_nan == other_nan: |
| 2687 | if self._int < other._int: |
| 2688 | if sign: |
| 2689 | return Dec_p1 |
| 2690 | else: |
| 2691 | return Dec_n1 |
| 2692 | if self._int > other._int: |
| 2693 | if sign: |
| 2694 | return Dec_n1 |
| 2695 | else: |
| 2696 | return Dec_p1 |
| 2697 | return Dec_0 |
| 2698 | |
| 2699 | if sign: |
| 2700 | if self_nan == 1: |
| 2701 | return Dec_n1 |
| 2702 | if other_nan == 1: |
| 2703 | return Dec_p1 |
| 2704 | if self_nan == 2: |
| 2705 | return Dec_n1 |
| 2706 | if other_nan == 2: |
| 2707 | return Dec_p1 |
| 2708 | else: |
| 2709 | if self_nan == 1: |
| 2710 | return Dec_p1 |
| 2711 | if other_nan == 1: |
| 2712 | return Dec_n1 |
| 2713 | if self_nan == 2: |
| 2714 | return Dec_p1 |
| 2715 | if other_nan == 2: |
| 2716 | return Dec_n1 |
| 2717 | |
| 2718 | if self < other: |
| 2719 | return Dec_n1 |
| 2720 | if self > other: |
| 2721 | return Dec_p1 |
| 2722 | |
| 2723 | if self._exp < other._exp: |
| 2724 | if sign: |
| 2725 | return Dec_p1 |
| 2726 | else: |
| 2727 | return Dec_n1 |
| 2728 | if self._exp > other._exp: |
| 2729 | if sign: |
| 2730 | return Dec_n1 |
| 2731 | else: |
| 2732 | return Dec_p1 |
| 2733 | return Dec_0 |
| 2734 | |
| 2735 | |
| 2736 | def compare_total_mag(self, other): |
| 2737 | """Compares self to other using abstract repr., ignoring sign. |
| 2738 | |
| 2739 | Like compare_total, but with operand's sign ignored and assumed to be 0. |
| 2740 | """ |
| 2741 | s = self.copy_abs() |
| 2742 | o = other.copy_abs() |
| 2743 | return s.compare_total(o) |
| 2744 | |
| 2745 | def copy_abs(self): |
| 2746 | """Returns a copy with the sign set to 0. """ |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2747 | return _dec_from_triple(0, self._int, self._exp, self._is_special) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2748 | |
| 2749 | def copy_negate(self): |
| 2750 | """Returns a copy with the sign inverted.""" |
| 2751 | if self._sign: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2752 | return _dec_from_triple(0, self._int, self._exp, self._is_special) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2753 | else: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2754 | return _dec_from_triple(1, self._int, self._exp, self._is_special) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2755 | |
| 2756 | def copy_sign(self, other): |
| 2757 | """Returns self with the sign of other.""" |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2758 | return _dec_from_triple(other._sign, self._int, |
| 2759 | self._exp, self._is_special) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2760 | |
| 2761 | def exp(self, context=None): |
| 2762 | """Returns e ** self.""" |
| 2763 | |
| 2764 | if context is None: |
| 2765 | context = getcontext() |
| 2766 | |
| 2767 | # exp(NaN) = NaN |
| 2768 | ans = self._check_nans(context=context) |
| 2769 | if ans: |
| 2770 | return ans |
| 2771 | |
| 2772 | # exp(-Infinity) = 0 |
| 2773 | if self._isinfinity() == -1: |
| 2774 | return Dec_0 |
| 2775 | |
| 2776 | # exp(0) = 1 |
| 2777 | if not self: |
| 2778 | return Dec_p1 |
| 2779 | |
| 2780 | # exp(Infinity) = Infinity |
| 2781 | if self._isinfinity() == 1: |
| 2782 | return Decimal(self) |
| 2783 | |
| 2784 | # the result is now guaranteed to be inexact (the true |
| 2785 | # mathematical result is transcendental). There's no need to |
| 2786 | # raise Rounded and Inexact here---they'll always be raised as |
| 2787 | # a result of the call to _fix. |
| 2788 | p = context.prec |
| 2789 | adj = self.adjusted() |
| 2790 | |
| 2791 | # we only need to do any computation for quite a small range |
| 2792 | # of adjusted exponents---for example, -29 <= adj <= 10 for |
| 2793 | # the default context. For smaller exponent the result is |
| 2794 | # indistinguishable from 1 at the given precision, while for |
| 2795 | # larger exponent the result either overflows or underflows. |
| 2796 | if self._sign == 0 and adj > len(str((context.Emax+1)*3)): |
| 2797 | # overflow |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2798 | ans = _dec_from_triple(0, '1', context.Emax+1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2799 | elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)): |
| 2800 | # underflow to 0 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2801 | ans = _dec_from_triple(0, '1', context.Etiny()-1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2802 | elif self._sign == 0 and adj < -p: |
| 2803 | # p+1 digits; final round will raise correct flags |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2804 | ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2805 | elif self._sign == 1 and adj < -p-1: |
| 2806 | # p+1 digits; final round will raise correct flags |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2807 | ans = _dec_from_triple(0, '9'*(p+1), -p-1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2808 | # general case |
| 2809 | else: |
| 2810 | op = _WorkRep(self) |
| 2811 | c, e = op.int, op.exp |
| 2812 | if op.sign == 1: |
| 2813 | c = -c |
| 2814 | |
| 2815 | # compute correctly rounded result: increase precision by |
| 2816 | # 3 digits at a time until we get an unambiguously |
| 2817 | # roundable result |
| 2818 | extra = 3 |
| 2819 | while True: |
| 2820 | coeff, exp = _dexp(c, e, p+extra) |
| 2821 | if coeff % (5*10**(len(str(coeff))-p-1)): |
| 2822 | break |
| 2823 | extra += 3 |
| 2824 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2825 | ans = _dec_from_triple(0, str(coeff), exp) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2826 | |
| 2827 | # at this stage, ans should round correctly with *any* |
| 2828 | # rounding mode, not just with ROUND_HALF_EVEN |
| 2829 | context = context._shallow_copy() |
| 2830 | rounding = context._set_rounding(ROUND_HALF_EVEN) |
| 2831 | ans = ans._fix(context) |
| 2832 | context.rounding = rounding |
| 2833 | |
| 2834 | return ans |
| 2835 | |
| 2836 | def is_canonical(self): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2837 | """Return True if self is canonical; otherwise return False. |
| 2838 | |
| 2839 | Currently, the encoding of a Decimal instance is always |
| 2840 | canonical, so this method returns True for any Decimal. |
| 2841 | """ |
| 2842 | return True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2843 | |
| 2844 | def is_finite(self): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2845 | """Return True if self is finite; otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2846 | |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2847 | A Decimal instance is considered finite if it is neither |
| 2848 | infinite nor a NaN. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2849 | """ |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2850 | return not self._is_special |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2851 | |
| 2852 | def is_infinite(self): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2853 | """Return True if self is infinite; otherwise return False.""" |
| 2854 | return self._exp == 'F' |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2855 | |
| 2856 | def is_nan(self): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2857 | """Return True if self is a qNaN or sNaN; otherwise return False.""" |
| 2858 | return self._exp in ('n', 'N') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2859 | |
| 2860 | def is_normal(self, context=None): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2861 | """Return True if self is a normal number; otherwise return False.""" |
| 2862 | if self._is_special or not self: |
| 2863 | return False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2864 | if context is None: |
| 2865 | context = getcontext() |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2866 | return context.Emin <= self.adjusted() <= context.Emax |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2867 | |
| 2868 | def is_qnan(self): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2869 | """Return True if self is a quiet NaN; otherwise return False.""" |
| 2870 | return self._exp == 'n' |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2871 | |
| 2872 | def is_signed(self): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2873 | """Return True if self is negative; otherwise return False.""" |
| 2874 | return self._sign == 1 |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2875 | |
| 2876 | def is_snan(self): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2877 | """Return True if self is a signaling NaN; otherwise return False.""" |
| 2878 | return self._exp == 'N' |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2879 | |
| 2880 | def is_subnormal(self, context=None): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2881 | """Return True if self is subnormal; otherwise return False.""" |
| 2882 | if self._is_special or not self: |
| 2883 | return False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2884 | if context is None: |
| 2885 | context = getcontext() |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2886 | return self.adjusted() < context.Emin |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2887 | |
| 2888 | def is_zero(self): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 2889 | """Return True if self is a zero; otherwise return False.""" |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2890 | return not self._is_special and self._int == '0' |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2891 | |
| 2892 | def _ln_exp_bound(self): |
| 2893 | """Compute a lower bound for the adjusted exponent of self.ln(). |
| 2894 | In other words, compute r such that self.ln() >= 10**r. Assumes |
| 2895 | that self is finite and positive and that self != 1. |
| 2896 | """ |
| 2897 | |
| 2898 | # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1 |
| 2899 | adj = self._exp + len(self._int) - 1 |
| 2900 | if adj >= 1: |
| 2901 | # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10) |
| 2902 | return len(str(adj*23//10)) - 1 |
| 2903 | if adj <= -2: |
| 2904 | # argument <= 0.1 |
| 2905 | return len(str((-1-adj)*23//10)) - 1 |
| 2906 | op = _WorkRep(self) |
| 2907 | c, e = op.int, op.exp |
| 2908 | if adj == 0: |
| 2909 | # 1 < self < 10 |
| 2910 | num = str(c-10**-e) |
| 2911 | den = str(c) |
| 2912 | return len(num) - len(den) - (num < den) |
| 2913 | # adj == -1, 0.1 <= self < 1 |
| 2914 | return e + len(str(10**-e - c)) - 1 |
| 2915 | |
| 2916 | |
| 2917 | def ln(self, context=None): |
| 2918 | """Returns the natural (base e) logarithm of self.""" |
| 2919 | |
| 2920 | if context is None: |
| 2921 | context = getcontext() |
| 2922 | |
| 2923 | # ln(NaN) = NaN |
| 2924 | ans = self._check_nans(context=context) |
| 2925 | if ans: |
| 2926 | return ans |
| 2927 | |
| 2928 | # ln(0.0) == -Infinity |
| 2929 | if not self: |
| 2930 | return negInf |
| 2931 | |
| 2932 | # ln(Infinity) = Infinity |
| 2933 | if self._isinfinity() == 1: |
| 2934 | return Inf |
| 2935 | |
| 2936 | # ln(1.0) == 0.0 |
| 2937 | if self == Dec_p1: |
| 2938 | return Dec_0 |
| 2939 | |
| 2940 | # ln(negative) raises InvalidOperation |
| 2941 | if self._sign == 1: |
| 2942 | return context._raise_error(InvalidOperation, |
| 2943 | 'ln of a negative value') |
| 2944 | |
| 2945 | # result is irrational, so necessarily inexact |
| 2946 | op = _WorkRep(self) |
| 2947 | c, e = op.int, op.exp |
| 2948 | p = context.prec |
| 2949 | |
| 2950 | # correctly rounded result: repeatedly increase precision by 3 |
| 2951 | # until we get an unambiguously roundable result |
| 2952 | places = p - self._ln_exp_bound() + 2 # at least p+3 places |
| 2953 | while True: |
| 2954 | coeff = _dlog(c, e, places) |
| 2955 | # assert len(str(abs(coeff)))-p >= 1 |
| 2956 | if coeff % (5*10**(len(str(abs(coeff)))-p-1)): |
| 2957 | break |
| 2958 | places += 3 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 2959 | ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 2960 | |
| 2961 | context = context._shallow_copy() |
| 2962 | rounding = context._set_rounding(ROUND_HALF_EVEN) |
| 2963 | ans = ans._fix(context) |
| 2964 | context.rounding = rounding |
| 2965 | return ans |
| 2966 | |
| 2967 | def _log10_exp_bound(self): |
| 2968 | """Compute a lower bound for the adjusted exponent of self.log10(). |
| 2969 | In other words, find r such that self.log10() >= 10**r. |
| 2970 | Assumes that self is finite and positive and that self != 1. |
| 2971 | """ |
| 2972 | |
| 2973 | # For x >= 10 or x < 0.1 we only need a bound on the integer |
| 2974 | # part of log10(self), and this comes directly from the |
| 2975 | # exponent of x. For 0.1 <= x <= 10 we use the inequalities |
| 2976 | # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| > |
| 2977 | # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0 |
| 2978 | |
| 2979 | adj = self._exp + len(self._int) - 1 |
| 2980 | if adj >= 1: |
| 2981 | # self >= 10 |
| 2982 | return len(str(adj))-1 |
| 2983 | if adj <= -2: |
| 2984 | # self < 0.1 |
| 2985 | return len(str(-1-adj))-1 |
| 2986 | op = _WorkRep(self) |
| 2987 | c, e = op.int, op.exp |
| 2988 | if adj == 0: |
| 2989 | # 1 < self < 10 |
| 2990 | num = str(c-10**-e) |
| 2991 | den = str(231*c) |
| 2992 | return len(num) - len(den) - (num < den) + 2 |
| 2993 | # adj == -1, 0.1 <= self < 1 |
| 2994 | num = str(10**-e-c) |
| 2995 | return len(num) + e - (num < "231") - 1 |
| 2996 | |
| 2997 | def log10(self, context=None): |
| 2998 | """Returns the base 10 logarithm of self.""" |
| 2999 | |
| 3000 | if context is None: |
| 3001 | context = getcontext() |
| 3002 | |
| 3003 | # log10(NaN) = NaN |
| 3004 | ans = self._check_nans(context=context) |
| 3005 | if ans: |
| 3006 | return ans |
| 3007 | |
| 3008 | # log10(0.0) == -Infinity |
| 3009 | if not self: |
| 3010 | return negInf |
| 3011 | |
| 3012 | # log10(Infinity) = Infinity |
| 3013 | if self._isinfinity() == 1: |
| 3014 | return Inf |
| 3015 | |
| 3016 | # log10(negative or -Infinity) raises InvalidOperation |
| 3017 | if self._sign == 1: |
| 3018 | return context._raise_error(InvalidOperation, |
| 3019 | 'log10 of a negative value') |
| 3020 | |
| 3021 | # log10(10**n) = n |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3022 | 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] | 3023 | # answer may need rounding |
| 3024 | ans = Decimal(self._exp + len(self._int) - 1) |
| 3025 | else: |
| 3026 | # result is irrational, so necessarily inexact |
| 3027 | op = _WorkRep(self) |
| 3028 | c, e = op.int, op.exp |
| 3029 | p = context.prec |
| 3030 | |
| 3031 | # correctly rounded result: repeatedly increase precision |
| 3032 | # until result is unambiguously roundable |
| 3033 | places = p-self._log10_exp_bound()+2 |
| 3034 | while True: |
| 3035 | coeff = _dlog10(c, e, places) |
| 3036 | # assert len(str(abs(coeff)))-p >= 1 |
| 3037 | if coeff % (5*10**(len(str(abs(coeff)))-p-1)): |
| 3038 | break |
| 3039 | places += 3 |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3040 | ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3041 | |
| 3042 | context = context._shallow_copy() |
| 3043 | rounding = context._set_rounding(ROUND_HALF_EVEN) |
| 3044 | ans = ans._fix(context) |
| 3045 | context.rounding = rounding |
| 3046 | return ans |
| 3047 | |
| 3048 | def logb(self, context=None): |
| 3049 | """ Returns the exponent of the magnitude of self's MSD. |
| 3050 | |
| 3051 | The result is the integer which is the exponent of the magnitude |
| 3052 | of the most significant digit of self (as though it were truncated |
| 3053 | to a single digit while maintaining the value of that digit and |
| 3054 | without limiting the resulting exponent). |
| 3055 | """ |
| 3056 | # logb(NaN) = NaN |
| 3057 | ans = self._check_nans(context=context) |
| 3058 | if ans: |
| 3059 | return ans |
| 3060 | |
| 3061 | if context is None: |
| 3062 | context = getcontext() |
| 3063 | |
| 3064 | # logb(+/-Inf) = +Inf |
| 3065 | if self._isinfinity(): |
| 3066 | return Inf |
| 3067 | |
| 3068 | # logb(0) = -Inf, DivisionByZero |
| 3069 | if not self: |
Facundo Batista | cce8df2 | 2007-09-18 16:53:18 +0000 | [diff] [blame] | 3070 | return context._raise_error(DivisionByZero, 'logb(0)', 1) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3071 | |
| 3072 | # otherwise, simply return the adjusted exponent of self, as a |
| 3073 | # Decimal. Note that no attempt is made to fit the result |
| 3074 | # into the current context. |
| 3075 | return Decimal(self.adjusted()) |
| 3076 | |
| 3077 | def _islogical(self): |
| 3078 | """Return True if self is a logical operand. |
| 3079 | |
Andrew M. Kuchling | c8acc88 | 2008-01-16 00:32:03 +0000 | [diff] [blame] | 3080 | For being logical, it must be a finite number with a sign of 0, |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3081 | an exponent of 0, and a coefficient whose digits must all be |
| 3082 | either 0 or 1. |
| 3083 | """ |
| 3084 | if self._sign != 0 or self._exp != 0: |
| 3085 | return False |
| 3086 | for dig in self._int: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3087 | if dig not in '01': |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3088 | return False |
| 3089 | return True |
| 3090 | |
| 3091 | def _fill_logical(self, context, opa, opb): |
| 3092 | dif = context.prec - len(opa) |
| 3093 | if dif > 0: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3094 | opa = '0'*dif + opa |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3095 | elif dif < 0: |
| 3096 | opa = opa[-context.prec:] |
| 3097 | dif = context.prec - len(opb) |
| 3098 | if dif > 0: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3099 | opb = '0'*dif + opb |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3100 | elif dif < 0: |
| 3101 | opb = opb[-context.prec:] |
| 3102 | return opa, opb |
| 3103 | |
| 3104 | def logical_and(self, other, context=None): |
| 3105 | """Applies an 'and' operation between self and other's digits.""" |
| 3106 | if context is None: |
| 3107 | context = getcontext() |
| 3108 | if not self._islogical() or not other._islogical(): |
| 3109 | return context._raise_error(InvalidOperation) |
| 3110 | |
| 3111 | # fill to context.prec |
| 3112 | (opa, opb) = self._fill_logical(context, self._int, other._int) |
| 3113 | |
| 3114 | # make the operation, and clean starting zeroes |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3115 | result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)]) |
| 3116 | return _dec_from_triple(0, result.lstrip('0') or '0', 0) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3117 | |
| 3118 | def logical_invert(self, context=None): |
| 3119 | """Invert all its digits.""" |
| 3120 | if context is None: |
| 3121 | context = getcontext() |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3122 | return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0), |
| 3123 | context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3124 | |
| 3125 | def logical_or(self, other, context=None): |
| 3126 | """Applies an 'or' operation between self and other's digits.""" |
| 3127 | if context is None: |
| 3128 | context = getcontext() |
| 3129 | if not self._islogical() or not other._islogical(): |
| 3130 | return context._raise_error(InvalidOperation) |
| 3131 | |
| 3132 | # fill to context.prec |
| 3133 | (opa, opb) = self._fill_logical(context, self._int, other._int) |
| 3134 | |
| 3135 | # make the operation, and clean starting zeroes |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3136 | result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb)) |
| 3137 | return _dec_from_triple(0, result.lstrip('0') or '0', 0) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3138 | |
| 3139 | def logical_xor(self, other, context=None): |
| 3140 | """Applies an 'xor' operation between self and other's digits.""" |
| 3141 | if context is None: |
| 3142 | context = getcontext() |
| 3143 | if not self._islogical() or not other._islogical(): |
| 3144 | return context._raise_error(InvalidOperation) |
| 3145 | |
| 3146 | # fill to context.prec |
| 3147 | (opa, opb) = self._fill_logical(context, self._int, other._int) |
| 3148 | |
| 3149 | # make the operation, and clean starting zeroes |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3150 | result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb)) |
| 3151 | return _dec_from_triple(0, result.lstrip('0') or '0', 0) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3152 | |
| 3153 | def max_mag(self, other, context=None): |
| 3154 | """Compares the values numerically with their sign ignored.""" |
| 3155 | other = _convert_other(other, raiseit=True) |
| 3156 | |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 3157 | if context is None: |
| 3158 | context = getcontext() |
| 3159 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3160 | if self._is_special or other._is_special: |
| 3161 | # If one operand is a quiet NaN and the other is number, then the |
| 3162 | # number is always returned |
| 3163 | sn = self._isnan() |
| 3164 | on = other._isnan() |
| 3165 | if sn or on: |
| 3166 | if on == 1 and sn != 2: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 3167 | return self._fix_nan(context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3168 | if sn == 1 and on != 2: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 3169 | return other._fix_nan(context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3170 | return self._check_nans(other, context) |
| 3171 | |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 3172 | c = self.copy_abs()._cmp(other.copy_abs()) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3173 | if c == 0: |
| 3174 | c = self.compare_total(other) |
| 3175 | |
| 3176 | if c == -1: |
| 3177 | ans = other |
| 3178 | else: |
| 3179 | ans = self |
| 3180 | |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 3181 | return ans._fix(context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3182 | |
| 3183 | def min_mag(self, other, context=None): |
| 3184 | """Compares the values numerically with their sign ignored.""" |
| 3185 | other = _convert_other(other, raiseit=True) |
| 3186 | |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 3187 | if context is None: |
| 3188 | context = getcontext() |
| 3189 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3190 | if self._is_special or other._is_special: |
| 3191 | # If one operand is a quiet NaN and the other is number, then the |
| 3192 | # number is always returned |
| 3193 | sn = self._isnan() |
| 3194 | on = other._isnan() |
| 3195 | if sn or on: |
| 3196 | if on == 1 and sn != 2: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 3197 | return self._fix_nan(context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3198 | if sn == 1 and on != 2: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 3199 | return other._fix_nan(context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3200 | return self._check_nans(other, context) |
| 3201 | |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 3202 | c = self.copy_abs()._cmp(other.copy_abs()) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3203 | if c == 0: |
| 3204 | c = self.compare_total(other) |
| 3205 | |
| 3206 | if c == -1: |
| 3207 | ans = self |
| 3208 | else: |
| 3209 | ans = other |
| 3210 | |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 3211 | return ans._fix(context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3212 | |
| 3213 | def next_minus(self, context=None): |
| 3214 | """Returns the largest representable number smaller than itself.""" |
| 3215 | if context is None: |
| 3216 | context = getcontext() |
| 3217 | |
| 3218 | ans = self._check_nans(context=context) |
| 3219 | if ans: |
| 3220 | return ans |
| 3221 | |
| 3222 | if self._isinfinity() == -1: |
| 3223 | return negInf |
| 3224 | if self._isinfinity() == 1: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3225 | return _dec_from_triple(0, '9'*context.prec, context.Etop()) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3226 | |
| 3227 | context = context.copy() |
| 3228 | context._set_rounding(ROUND_FLOOR) |
| 3229 | context._ignore_all_flags() |
| 3230 | new_self = self._fix(context) |
| 3231 | if new_self != self: |
| 3232 | return new_self |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3233 | return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1), |
| 3234 | context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3235 | |
| 3236 | def next_plus(self, context=None): |
| 3237 | """Returns the smallest representable number larger than itself.""" |
| 3238 | if context is None: |
| 3239 | context = getcontext() |
| 3240 | |
| 3241 | ans = self._check_nans(context=context) |
| 3242 | if ans: |
| 3243 | return ans |
| 3244 | |
| 3245 | if self._isinfinity() == 1: |
| 3246 | return Inf |
| 3247 | if self._isinfinity() == -1: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3248 | return _dec_from_triple(1, '9'*context.prec, context.Etop()) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3249 | |
| 3250 | context = context.copy() |
| 3251 | context._set_rounding(ROUND_CEILING) |
| 3252 | context._ignore_all_flags() |
| 3253 | new_self = self._fix(context) |
| 3254 | if new_self != self: |
| 3255 | return new_self |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3256 | return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1), |
| 3257 | context) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3258 | |
| 3259 | def next_toward(self, other, context=None): |
| 3260 | """Returns the number closest to self, in the direction towards other. |
| 3261 | |
| 3262 | The result is the closest representable number to self |
| 3263 | (excluding self) that is in the direction towards other, |
| 3264 | unless both have the same value. If the two operands are |
| 3265 | numerically equal, then the result is a copy of self with the |
| 3266 | sign set to be the same as the sign of other. |
| 3267 | """ |
| 3268 | other = _convert_other(other, raiseit=True) |
| 3269 | |
| 3270 | if context is None: |
| 3271 | context = getcontext() |
| 3272 | |
| 3273 | ans = self._check_nans(other, context) |
| 3274 | if ans: |
| 3275 | return ans |
| 3276 | |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 3277 | comparison = self._cmp(other) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3278 | if comparison == 0: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3279 | return self.copy_sign(other) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3280 | |
| 3281 | if comparison == -1: |
| 3282 | ans = self.next_plus(context) |
| 3283 | else: # comparison == 1 |
| 3284 | ans = self.next_minus(context) |
| 3285 | |
| 3286 | # decide which flags to raise using value of ans |
| 3287 | if ans._isinfinity(): |
| 3288 | context._raise_error(Overflow, |
| 3289 | 'Infinite result from next_toward', |
| 3290 | ans._sign) |
| 3291 | context._raise_error(Rounded) |
| 3292 | context._raise_error(Inexact) |
| 3293 | elif ans.adjusted() < context.Emin: |
| 3294 | context._raise_error(Underflow) |
| 3295 | context._raise_error(Subnormal) |
| 3296 | context._raise_error(Rounded) |
| 3297 | context._raise_error(Inexact) |
| 3298 | # if precision == 1 then we don't raise Clamped for a |
| 3299 | # result 0E-Etiny. |
| 3300 | if not ans: |
| 3301 | context._raise_error(Clamped) |
| 3302 | |
| 3303 | return ans |
| 3304 | |
| 3305 | def number_class(self, context=None): |
| 3306 | """Returns an indication of the class of self. |
| 3307 | |
| 3308 | The class is one of the following strings: |
Facundo Batista | 0f5e7bf | 2007-12-19 12:53:01 +0000 | [diff] [blame] | 3309 | sNaN |
| 3310 | NaN |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3311 | -Infinity |
| 3312 | -Normal |
| 3313 | -Subnormal |
| 3314 | -Zero |
| 3315 | +Zero |
| 3316 | +Subnormal |
| 3317 | +Normal |
| 3318 | +Infinity |
| 3319 | """ |
| 3320 | if self.is_snan(): |
| 3321 | return "sNaN" |
| 3322 | if self.is_qnan(): |
| 3323 | return "NaN" |
| 3324 | inf = self._isinfinity() |
| 3325 | if inf == 1: |
| 3326 | return "+Infinity" |
| 3327 | if inf == -1: |
| 3328 | return "-Infinity" |
| 3329 | if self.is_zero(): |
| 3330 | if self._sign: |
| 3331 | return "-Zero" |
| 3332 | else: |
| 3333 | return "+Zero" |
| 3334 | if context is None: |
| 3335 | context = getcontext() |
| 3336 | if self.is_subnormal(context=context): |
| 3337 | if self._sign: |
| 3338 | return "-Subnormal" |
| 3339 | else: |
| 3340 | return "+Subnormal" |
| 3341 | # just a normal, regular, boring number, :) |
| 3342 | if self._sign: |
| 3343 | return "-Normal" |
| 3344 | else: |
| 3345 | return "+Normal" |
| 3346 | |
| 3347 | def radix(self): |
| 3348 | """Just returns 10, as this is Decimal, :)""" |
| 3349 | return Decimal(10) |
| 3350 | |
| 3351 | def rotate(self, other, context=None): |
| 3352 | """Returns a rotated copy of self, value-of-other times.""" |
| 3353 | if context is None: |
| 3354 | context = getcontext() |
| 3355 | |
| 3356 | ans = self._check_nans(other, context) |
| 3357 | if ans: |
| 3358 | return ans |
| 3359 | |
| 3360 | if other._exp != 0: |
| 3361 | return context._raise_error(InvalidOperation) |
| 3362 | if not (-context.prec <= int(other) <= context.prec): |
| 3363 | return context._raise_error(InvalidOperation) |
| 3364 | |
| 3365 | if self._isinfinity(): |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 3366 | return Decimal(self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3367 | |
| 3368 | # get values, pad if necessary |
| 3369 | torot = int(other) |
| 3370 | rotdig = self._int |
| 3371 | topad = context.prec - len(rotdig) |
| 3372 | if topad: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3373 | rotdig = '0'*topad + rotdig |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3374 | |
| 3375 | # let's rotate! |
| 3376 | rotated = rotdig[torot:] + rotdig[:torot] |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3377 | return _dec_from_triple(self._sign, |
| 3378 | rotated.lstrip('0') or '0', self._exp) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3379 | |
| 3380 | def scaleb (self, other, context=None): |
| 3381 | """Returns self operand after adding the second value to its exp.""" |
| 3382 | if context is None: |
| 3383 | context = getcontext() |
| 3384 | |
| 3385 | ans = self._check_nans(other, context) |
| 3386 | if ans: |
| 3387 | return ans |
| 3388 | |
| 3389 | if other._exp != 0: |
| 3390 | return context._raise_error(InvalidOperation) |
| 3391 | liminf = -2 * (context.Emax + context.prec) |
| 3392 | limsup = 2 * (context.Emax + context.prec) |
| 3393 | if not (liminf <= int(other) <= limsup): |
| 3394 | return context._raise_error(InvalidOperation) |
| 3395 | |
| 3396 | if self._isinfinity(): |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 3397 | return Decimal(self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3398 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3399 | d = _dec_from_triple(self._sign, self._int, self._exp + int(other)) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3400 | d = d._fix(context) |
| 3401 | return d |
| 3402 | |
| 3403 | def shift(self, other, context=None): |
| 3404 | """Returns a shifted copy of self, value-of-other times.""" |
| 3405 | if context is None: |
| 3406 | context = getcontext() |
| 3407 | |
| 3408 | ans = self._check_nans(other, context) |
| 3409 | if ans: |
| 3410 | return ans |
| 3411 | |
| 3412 | if other._exp != 0: |
| 3413 | return context._raise_error(InvalidOperation) |
| 3414 | if not (-context.prec <= int(other) <= context.prec): |
| 3415 | return context._raise_error(InvalidOperation) |
| 3416 | |
| 3417 | if self._isinfinity(): |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 3418 | return Decimal(self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3419 | |
| 3420 | # get values, pad if necessary |
| 3421 | torot = int(other) |
| 3422 | if not torot: |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 3423 | return Decimal(self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3424 | rotdig = self._int |
| 3425 | topad = context.prec - len(rotdig) |
| 3426 | if topad: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3427 | rotdig = '0'*topad + rotdig |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3428 | |
| 3429 | # let's shift! |
| 3430 | if torot < 0: |
| 3431 | rotated = rotdig[:torot] |
| 3432 | else: |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3433 | rotated = rotdig + '0'*torot |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3434 | rotated = rotated[-context.prec:] |
| 3435 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3436 | return _dec_from_triple(self._sign, |
| 3437 | rotated.lstrip('0') or '0', self._exp) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3438 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3439 | # Support for pickling, copy, and deepcopy |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3440 | def __reduce__(self): |
| 3441 | return (self.__class__, (str(self),)) |
| 3442 | |
| 3443 | def __copy__(self): |
| 3444 | if type(self) == Decimal: |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 3445 | return self # I'm immutable; therefore I am my own clone |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3446 | return self.__class__(str(self)) |
| 3447 | |
| 3448 | def __deepcopy__(self, memo): |
| 3449 | if type(self) == Decimal: |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 3450 | return self # My components are also immutable |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3451 | return self.__class__(str(self)) |
| 3452 | |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 3453 | # PEP 3101 support. See also _parse_format_specifier and _format_align |
| 3454 | def __format__(self, specifier, context=None): |
Mark Dickinson | f4da777 | 2008-02-29 03:29:17 +0000 | [diff] [blame] | 3455 | """Format a Decimal instance according to the given specifier. |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 3456 | |
| 3457 | The specifier should be a standard format specifier, with the |
| 3458 | form described in PEP 3101. Formatting types 'e', 'E', 'f', |
| 3459 | 'F', 'g', 'G', and '%' are supported. If the formatting type |
| 3460 | is omitted it defaults to 'g' or 'G', depending on the value |
| 3461 | of context.capitals. |
| 3462 | |
| 3463 | At this time the 'n' format specifier type (which is supposed |
| 3464 | to use the current locale) is not supported. |
| 3465 | """ |
| 3466 | |
| 3467 | # Note: PEP 3101 says that if the type is not present then |
| 3468 | # there should be at least one digit after the decimal point. |
| 3469 | # We take the liberty of ignoring this requirement for |
| 3470 | # Decimal---it's presumably there to make sure that |
| 3471 | # format(float, '') behaves similarly to str(float). |
| 3472 | if context is None: |
| 3473 | context = getcontext() |
| 3474 | |
| 3475 | spec = _parse_format_specifier(specifier) |
| 3476 | |
| 3477 | # special values don't care about the type or precision... |
| 3478 | if self._is_special: |
| 3479 | return _format_align(str(self), spec) |
| 3480 | |
| 3481 | # a type of None defaults to 'g' or 'G', depending on context |
| 3482 | # if type is '%', adjust exponent of self accordingly |
| 3483 | if spec['type'] is None: |
| 3484 | spec['type'] = ['g', 'G'][context.capitals] |
| 3485 | elif spec['type'] == '%': |
| 3486 | self = _dec_from_triple(self._sign, self._int, self._exp+2) |
| 3487 | |
| 3488 | # round if necessary, taking rounding mode from the context |
| 3489 | rounding = context.rounding |
| 3490 | precision = spec['precision'] |
| 3491 | if precision is not None: |
| 3492 | if spec['type'] in 'eE': |
| 3493 | self = self._round(precision+1, rounding) |
| 3494 | elif spec['type'] in 'gG': |
| 3495 | if len(self._int) > precision: |
| 3496 | self = self._round(precision, rounding) |
| 3497 | elif spec['type'] in 'fF%': |
| 3498 | self = self._rescale(-precision, rounding) |
| 3499 | # special case: zeros with a positive exponent can't be |
| 3500 | # represented in fixed point; rescale them to 0e0. |
| 3501 | elif not self and self._exp > 0 and spec['type'] in 'fF%': |
| 3502 | self = self._rescale(0, rounding) |
| 3503 | |
| 3504 | # figure out placement of the decimal point |
| 3505 | leftdigits = self._exp + len(self._int) |
| 3506 | if spec['type'] in 'fF%': |
| 3507 | dotplace = leftdigits |
| 3508 | elif spec['type'] in 'eE': |
| 3509 | if not self and precision is not None: |
| 3510 | dotplace = 1 - precision |
| 3511 | else: |
| 3512 | dotplace = 1 |
| 3513 | elif spec['type'] in 'gG': |
| 3514 | if self._exp <= 0 and leftdigits > -6: |
| 3515 | dotplace = leftdigits |
| 3516 | else: |
| 3517 | dotplace = 1 |
| 3518 | |
| 3519 | # figure out main part of numeric string... |
| 3520 | if dotplace <= 0: |
| 3521 | num = '0.' + '0'*(-dotplace) + self._int |
| 3522 | elif dotplace >= len(self._int): |
| 3523 | # make sure we're not padding a '0' with extra zeros on the right |
| 3524 | assert dotplace==len(self._int) or self._int != '0' |
| 3525 | num = self._int + '0'*(dotplace-len(self._int)) |
| 3526 | else: |
| 3527 | num = self._int[:dotplace] + '.' + self._int[dotplace:] |
| 3528 | |
| 3529 | # ...then the trailing exponent, or trailing '%' |
| 3530 | if leftdigits != dotplace or spec['type'] in 'eE': |
| 3531 | echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']] |
| 3532 | num = num + "{0}{1:+}".format(echar, leftdigits-dotplace) |
| 3533 | elif spec['type'] == '%': |
| 3534 | num = num + '%' |
| 3535 | |
| 3536 | # add sign |
| 3537 | if self._sign == 1: |
| 3538 | num = '-' + num |
| 3539 | return _format_align(num, spec) |
| 3540 | |
| 3541 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 3542 | def _dec_from_triple(sign, coefficient, exponent, special=False): |
| 3543 | """Create a decimal instance directly, without any validation, |
| 3544 | normalization (e.g. removal of leading zeros) or argument |
| 3545 | conversion. |
| 3546 | |
| 3547 | This function is for *internal use only*. |
| 3548 | """ |
| 3549 | |
| 3550 | self = object.__new__(Decimal) |
| 3551 | self._sign = sign |
| 3552 | self._int = coefficient |
| 3553 | self._exp = exponent |
| 3554 | self._is_special = special |
| 3555 | |
| 3556 | return self |
| 3557 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3558 | ##### Context class ####################################################### |
Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 3559 | |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 3560 | |
| 3561 | # get rounding method function: |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3562 | rounding_functions = [name for name in Decimal.__dict__.keys() |
| 3563 | if name.startswith('_round_')] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3564 | for name in rounding_functions: |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3565 | # 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] | 3566 | globalname = name[1:].upper() |
| 3567 | val = globals()[globalname] |
| 3568 | Decimal._pick_rounding_function[val] = name |
| 3569 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3570 | del name, val, globalname, rounding_functions |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3571 | |
Nick Coghlan | ced1218 | 2006-09-02 03:54:17 +0000 | [diff] [blame] | 3572 | class _ContextManager(object): |
Nick Coghlan | 8b6999b | 2006-08-31 12:00:43 +0000 | [diff] [blame] | 3573 | """Context manager class to support localcontext(). |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 3574 | |
Nick Coghlan | ced1218 | 2006-09-02 03:54:17 +0000 | [diff] [blame] | 3575 | Sets a copy of the supplied context in __enter__() and restores |
Nick Coghlan | 8b6999b | 2006-08-31 12:00:43 +0000 | [diff] [blame] | 3576 | the previous decimal context in __exit__() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 3577 | """ |
| 3578 | def __init__(self, new_context): |
Nick Coghlan | ced1218 | 2006-09-02 03:54:17 +0000 | [diff] [blame] | 3579 | self.new_context = new_context.copy() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 3580 | def __enter__(self): |
| 3581 | self.saved_context = getcontext() |
| 3582 | setcontext(self.new_context) |
| 3583 | return self.new_context |
| 3584 | def __exit__(self, t, v, tb): |
| 3585 | setcontext(self.saved_context) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 3586 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3587 | class Context(object): |
| 3588 | """Contains the context for a Decimal instance. |
| 3589 | |
| 3590 | Contains: |
| 3591 | prec - precision (for use in rounding, division, square roots..) |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3592 | rounding - rounding type (how you round) |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3593 | traps - If traps[exception] = 1, then the exception is |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3594 | raised when it is caused. Otherwise, a value is |
| 3595 | substituted in. |
Mark Dickinson | 1840c1a | 2008-05-03 18:23:14 +0000 | [diff] [blame] | 3596 | flags - When an exception is caused, flags[exception] is set. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3597 | (Whether or not the trap_enabler is set) |
| 3598 | Should be reset by user of Decimal instance. |
Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 3599 | Emin - Minimum exponent |
| 3600 | Emax - Maximum exponent |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3601 | capitals - If 1, 1*10^1 is printed as 1E+1. |
| 3602 | If 0, printed as 1e1 |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 3603 | _clamp - If 1, change exponents if too high (Default 0) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3604 | """ |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3605 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3606 | def __init__(self, prec=None, rounding=None, |
Raymond Hettinger | abf8a56 | 2004-10-12 09:12:16 +0000 | [diff] [blame] | 3607 | traps=None, flags=None, |
Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 3608 | Emin=None, Emax=None, |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 3609 | capitals=None, _clamp=0, |
Raymond Hettinger | abf8a56 | 2004-10-12 09:12:16 +0000 | [diff] [blame] | 3610 | _ignored_flags=None): |
| 3611 | if flags is None: |
| 3612 | flags = [] |
| 3613 | if _ignored_flags is None: |
| 3614 | _ignored_flags = [] |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3615 | if not isinstance(flags, dict): |
Mark Dickinson | 71f3b85 | 2008-05-04 02:25:46 +0000 | [diff] [blame] | 3616 | flags = dict([(s, int(s in flags)) for s in _signals]) |
Raymond Hettinger | b91af52 | 2004-07-14 16:35:30 +0000 | [diff] [blame] | 3617 | del s |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3618 | if traps is not None and not isinstance(traps, dict): |
Mark Dickinson | 71f3b85 | 2008-05-04 02:25:46 +0000 | [diff] [blame] | 3619 | traps = dict([(s, int(s in traps)) for s in _signals]) |
Raymond Hettinger | b91af52 | 2004-07-14 16:35:30 +0000 | [diff] [blame] | 3620 | del s |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3621 | for name, val in locals().items(): |
| 3622 | if val is None: |
Raymond Hettinger | eb26084 | 2005-06-07 18:52:34 +0000 | [diff] [blame] | 3623 | setattr(self, name, _copy.copy(getattr(DefaultContext, name))) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3624 | else: |
| 3625 | setattr(self, name, val) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3626 | del self.self |
| 3627 | |
Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 3628 | def __repr__(self): |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3629 | """Show the current context.""" |
Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 3630 | s = [] |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3631 | s.append('Context(prec=%(prec)d, rounding=%(rounding)s, ' |
| 3632 | 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d' |
| 3633 | % vars(self)) |
| 3634 | names = [f.__name__ for f, v in self.flags.items() if v] |
| 3635 | s.append('flags=[' + ', '.join(names) + ']') |
| 3636 | names = [t.__name__ for t, v in self.traps.items() if v] |
| 3637 | s.append('traps=[' + ', '.join(names) + ']') |
Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 3638 | return ', '.join(s) + ')' |
| 3639 | |
Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 3640 | def clear_flags(self): |
| 3641 | """Reset all flags to zero""" |
| 3642 | for flag in self.flags: |
Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 3643 | self.flags[flag] = 0 |
Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 3644 | |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 3645 | def _shallow_copy(self): |
| 3646 | """Returns a shallow copy from self.""" |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 3647 | nc = Context(self.prec, self.rounding, self.traps, |
| 3648 | self.flags, self.Emin, self.Emax, |
| 3649 | self.capitals, self._clamp, self._ignored_flags) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3650 | return nc |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 3651 | |
| 3652 | def copy(self): |
| 3653 | """Returns a deep copy from self.""" |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3654 | nc = Context(self.prec, self.rounding, self.traps.copy(), |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 3655 | self.flags.copy(), self.Emin, self.Emax, |
| 3656 | self.capitals, self._clamp, self._ignored_flags) |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 3657 | return nc |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3658 | __copy__ = copy |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3659 | |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 3660 | def _raise_error(self, condition, explanation = None, *args): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3661 | """Handles an error |
| 3662 | |
| 3663 | If the flag is in _ignored_flags, returns the default response. |
Mark Dickinson | 1840c1a | 2008-05-03 18:23:14 +0000 | [diff] [blame] | 3664 | Otherwise, it sets the flag, then, if the corresponding |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3665 | trap_enabler is set, it reaises the exception. Otherwise, it returns |
Mark Dickinson | 1840c1a | 2008-05-03 18:23:14 +0000 | [diff] [blame] | 3666 | the default value after setting the flag. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3667 | """ |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 3668 | error = _condition_map.get(condition, condition) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3669 | if error in self._ignored_flags: |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3670 | # Don't touch the flag |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3671 | return error().handle(self, *args) |
| 3672 | |
Mark Dickinson | 1840c1a | 2008-05-03 18:23:14 +0000 | [diff] [blame] | 3673 | self.flags[error] = 1 |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3674 | if not self.traps[error]: |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3675 | # The errors define how to handle themselves. |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 3676 | return condition().handle(self, *args) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3677 | |
| 3678 | # Errors should only be risked on copies of the context |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3679 | # self._ignored_flags = [] |
Mark Dickinson | 8aca9d0 | 2008-05-04 02:05:06 +0000 | [diff] [blame] | 3680 | raise error(explanation) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3681 | |
| 3682 | def _ignore_all_flags(self): |
| 3683 | """Ignore all flags, if they are raised""" |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 3684 | return self._ignore_flags(*_signals) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3685 | |
| 3686 | def _ignore_flags(self, *flags): |
| 3687 | """Ignore the flags, if they are raised""" |
| 3688 | # Do not mutate-- This way, copies of a context leave the original |
| 3689 | # alone. |
| 3690 | self._ignored_flags = (self._ignored_flags + list(flags)) |
| 3691 | return list(flags) |
| 3692 | |
| 3693 | def _regard_flags(self, *flags): |
| 3694 | """Stop ignoring the flags, if they are raised""" |
| 3695 | if flags and isinstance(flags[0], (tuple,list)): |
| 3696 | flags = flags[0] |
| 3697 | for flag in flags: |
| 3698 | self._ignored_flags.remove(flag) |
| 3699 | |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 3700 | def __hash__(self): |
| 3701 | """A Context cannot be hashed.""" |
| 3702 | # We inherit object.__hash__, so we must deny this explicitly |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3703 | raise TypeError("Cannot hash a Context.") |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 3704 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3705 | def Etiny(self): |
| 3706 | """Returns Etiny (= Emin - prec + 1)""" |
| 3707 | return int(self.Emin - self.prec + 1) |
| 3708 | |
| 3709 | def Etop(self): |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 3710 | """Returns maximum exponent (= Emax - prec + 1)""" |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3711 | return int(self.Emax - self.prec + 1) |
| 3712 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3713 | def _set_rounding(self, type): |
| 3714 | """Sets the rounding type. |
| 3715 | |
| 3716 | Sets the rounding type, and returns the current (previous) |
| 3717 | rounding type. Often used like: |
| 3718 | |
| 3719 | context = context.copy() |
| 3720 | # so you don't change the calling context |
| 3721 | # if an error occurs in the middle. |
| 3722 | rounding = context._set_rounding(ROUND_UP) |
| 3723 | val = self.__sub__(other, context=context) |
| 3724 | context._set_rounding(rounding) |
| 3725 | |
| 3726 | This will make it round up for that operation. |
| 3727 | """ |
| 3728 | rounding = self.rounding |
| 3729 | self.rounding= type |
| 3730 | return rounding |
| 3731 | |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 3732 | def create_decimal(self, num='0'): |
Mark Dickinson | 59bc20b | 2008-01-12 01:56:00 +0000 | [diff] [blame] | 3733 | """Creates a new Decimal instance but using self as context. |
| 3734 | |
| 3735 | This method implements the to-number operation of the |
| 3736 | IBM Decimal specification.""" |
| 3737 | |
| 3738 | if isinstance(num, basestring) and num != num.strip(): |
| 3739 | return self._raise_error(ConversionSyntax, |
| 3740 | "no trailing or leading whitespace is " |
| 3741 | "permitted.") |
| 3742 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3743 | d = Decimal(num, context=self) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3744 | if d._isnan() and len(d._int) > self.prec - self._clamp: |
| 3745 | return self._raise_error(ConversionSyntax, |
| 3746 | "diagnostic info too long in NaN") |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 3747 | return d._fix(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3748 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 3749 | # Methods |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3750 | def abs(self, a): |
| 3751 | """Returns the absolute value of the operand. |
| 3752 | |
| 3753 | 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] | 3754 | operation on the operand. Otherwise, the result is the same as using |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3755 | the plus operation on the operand. |
| 3756 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3757 | >>> ExtendedContext.abs(Decimal('2.1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3758 | Decimal('2.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3759 | >>> ExtendedContext.abs(Decimal('-100')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3760 | Decimal('100') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3761 | >>> ExtendedContext.abs(Decimal('101.5')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3762 | Decimal('101.5') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3763 | >>> ExtendedContext.abs(Decimal('-101.5')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3764 | Decimal('101.5') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3765 | """ |
| 3766 | return a.__abs__(context=self) |
| 3767 | |
| 3768 | def add(self, a, b): |
| 3769 | """Return the sum of the two operands. |
| 3770 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3771 | >>> ExtendedContext.add(Decimal('12'), Decimal('7.00')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3772 | Decimal('19.00') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3773 | >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3774 | Decimal('1.02E+4') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3775 | """ |
| 3776 | return a.__add__(b, context=self) |
| 3777 | |
| 3778 | def _apply(self, a): |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 3779 | return str(a._fix(self)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3780 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3781 | def canonical(self, a): |
| 3782 | """Returns the same Decimal object. |
| 3783 | |
| 3784 | As we do not have different encodings for the same number, the |
| 3785 | received object already is in its canonical form. |
| 3786 | |
| 3787 | >>> ExtendedContext.canonical(Decimal('2.50')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3788 | Decimal('2.50') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3789 | """ |
| 3790 | return a.canonical(context=self) |
| 3791 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3792 | def compare(self, a, b): |
| 3793 | """Compares values numerically. |
| 3794 | |
| 3795 | If the signs of the operands differ, a value representing each operand |
| 3796 | ('-1' if the operand is less than zero, '0' if the operand is zero or |
| 3797 | negative zero, or '1' if the operand is greater than zero) is used in |
| 3798 | place of that operand for the comparison instead of the actual |
| 3799 | operand. |
| 3800 | |
| 3801 | The comparison is then effected by subtracting the second operand from |
| 3802 | the first and then returning a value according to the result of the |
| 3803 | subtraction: '-1' if the result is less than zero, '0' if the result is |
| 3804 | zero or negative zero, or '1' if the result is greater than zero. |
| 3805 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3806 | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3807 | Decimal('-1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3808 | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3809 | Decimal('0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3810 | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3811 | Decimal('0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3812 | >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3813 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3814 | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3815 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3816 | >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3817 | Decimal('-1') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3818 | """ |
| 3819 | return a.compare(b, context=self) |
| 3820 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3821 | def compare_signal(self, a, b): |
| 3822 | """Compares the values of the two operands numerically. |
| 3823 | |
| 3824 | It's pretty much like compare(), but all NaNs signal, with signaling |
| 3825 | NaNs taking precedence over quiet NaNs. |
| 3826 | |
| 3827 | >>> c = ExtendedContext |
| 3828 | >>> c.compare_signal(Decimal('2.1'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3829 | Decimal('-1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3830 | >>> c.compare_signal(Decimal('2.1'), Decimal('2.1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3831 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3832 | >>> c.flags[InvalidOperation] = 0 |
| 3833 | >>> print c.flags[InvalidOperation] |
| 3834 | 0 |
| 3835 | >>> c.compare_signal(Decimal('NaN'), Decimal('2.1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3836 | Decimal('NaN') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3837 | >>> print c.flags[InvalidOperation] |
| 3838 | 1 |
| 3839 | >>> c.flags[InvalidOperation] = 0 |
| 3840 | >>> print c.flags[InvalidOperation] |
| 3841 | 0 |
| 3842 | >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3843 | Decimal('NaN') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3844 | >>> print c.flags[InvalidOperation] |
| 3845 | 1 |
| 3846 | """ |
| 3847 | return a.compare_signal(b, context=self) |
| 3848 | |
| 3849 | def compare_total(self, a, b): |
| 3850 | """Compares two operands using their abstract representation. |
| 3851 | |
| 3852 | This is not like the standard compare, which use their numerical |
| 3853 | value. Note that a total ordering is defined for all possible abstract |
| 3854 | representations. |
| 3855 | |
| 3856 | >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3857 | Decimal('-1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3858 | >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3859 | Decimal('-1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3860 | >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3861 | Decimal('-1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3862 | >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3863 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3864 | >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3865 | Decimal('1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3866 | >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3867 | Decimal('-1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3868 | """ |
| 3869 | return a.compare_total(b) |
| 3870 | |
| 3871 | def compare_total_mag(self, a, b): |
| 3872 | """Compares two operands using their abstract representation ignoring sign. |
| 3873 | |
| 3874 | Like compare_total, but with operand's sign ignored and assumed to be 0. |
| 3875 | """ |
| 3876 | return a.compare_total_mag(b) |
| 3877 | |
| 3878 | def copy_abs(self, a): |
| 3879 | """Returns a copy of the operand with the sign set to 0. |
| 3880 | |
| 3881 | >>> ExtendedContext.copy_abs(Decimal('2.1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3882 | Decimal('2.1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3883 | >>> ExtendedContext.copy_abs(Decimal('-100')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3884 | Decimal('100') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3885 | """ |
| 3886 | return a.copy_abs() |
| 3887 | |
| 3888 | def copy_decimal(self, a): |
| 3889 | """Returns a copy of the decimal objet. |
| 3890 | |
| 3891 | >>> ExtendedContext.copy_decimal(Decimal('2.1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3892 | Decimal('2.1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3893 | >>> ExtendedContext.copy_decimal(Decimal('-1.00')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3894 | Decimal('-1.00') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3895 | """ |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 3896 | return Decimal(a) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3897 | |
| 3898 | def copy_negate(self, a): |
| 3899 | """Returns a copy of the operand with the sign inverted. |
| 3900 | |
| 3901 | >>> ExtendedContext.copy_negate(Decimal('101.5')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3902 | Decimal('-101.5') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3903 | >>> ExtendedContext.copy_negate(Decimal('-101.5')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3904 | Decimal('101.5') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3905 | """ |
| 3906 | return a.copy_negate() |
| 3907 | |
| 3908 | def copy_sign(self, a, b): |
| 3909 | """Copies the second operand's sign to the first one. |
| 3910 | |
| 3911 | In detail, it returns a copy of the first operand with the sign |
| 3912 | equal to the sign of the second operand. |
| 3913 | |
| 3914 | >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3915 | Decimal('1.50') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3916 | >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3917 | Decimal('1.50') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3918 | >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3919 | Decimal('-1.50') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3920 | >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3921 | Decimal('-1.50') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3922 | """ |
| 3923 | return a.copy_sign(b) |
| 3924 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3925 | def divide(self, a, b): |
| 3926 | """Decimal division in a specified context. |
| 3927 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3928 | >>> ExtendedContext.divide(Decimal('1'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3929 | Decimal('0.333333333') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3930 | >>> ExtendedContext.divide(Decimal('2'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3931 | Decimal('0.666666667') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3932 | >>> ExtendedContext.divide(Decimal('5'), Decimal('2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3933 | Decimal('2.5') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3934 | >>> ExtendedContext.divide(Decimal('1'), Decimal('10')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3935 | Decimal('0.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3936 | >>> ExtendedContext.divide(Decimal('12'), Decimal('12')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3937 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3938 | >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3939 | Decimal('4.00') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3940 | >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3941 | Decimal('1.20') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3942 | >>> ExtendedContext.divide(Decimal('1000'), Decimal('100')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3943 | Decimal('10') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3944 | >>> ExtendedContext.divide(Decimal('1000'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3945 | Decimal('1000') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3946 | >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3947 | Decimal('1.20E+6') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3948 | """ |
| 3949 | return a.__div__(b, context=self) |
| 3950 | |
| 3951 | def divide_int(self, a, b): |
| 3952 | """Divides two numbers and returns the integer part of the result. |
| 3953 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3954 | >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3955 | Decimal('0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3956 | >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3957 | Decimal('3') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3958 | >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3959 | Decimal('3') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3960 | """ |
| 3961 | return a.__floordiv__(b, context=self) |
| 3962 | |
| 3963 | def divmod(self, a, b): |
| 3964 | return a.__divmod__(b, context=self) |
| 3965 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3966 | def exp(self, a): |
| 3967 | """Returns e ** a. |
| 3968 | |
| 3969 | >>> c = ExtendedContext.copy() |
| 3970 | >>> c.Emin = -999 |
| 3971 | >>> c.Emax = 999 |
| 3972 | >>> c.exp(Decimal('-Infinity')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3973 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3974 | >>> c.exp(Decimal('-1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3975 | Decimal('0.367879441') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3976 | >>> c.exp(Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3977 | Decimal('1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3978 | >>> c.exp(Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3979 | Decimal('2.71828183') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3980 | >>> c.exp(Decimal('0.693147181')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3981 | Decimal('2.00000000') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3982 | >>> c.exp(Decimal('+Infinity')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3983 | Decimal('Infinity') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3984 | """ |
| 3985 | return a.exp(context=self) |
| 3986 | |
| 3987 | def fma(self, a, b, c): |
| 3988 | """Returns a multiplied by b, plus c. |
| 3989 | |
| 3990 | The first two operands are multiplied together, using multiply, |
| 3991 | the third operand is then added to the result of that |
| 3992 | multiplication, using add, all with only one final rounding. |
| 3993 | |
| 3994 | >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3995 | Decimal('22') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3996 | >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3997 | Decimal('-8') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 3998 | >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 3999 | Decimal('1.38435736E+12') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4000 | """ |
| 4001 | return a.fma(b, c, context=self) |
| 4002 | |
| 4003 | def is_canonical(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4004 | """Return True if the operand is canonical; otherwise return False. |
| 4005 | |
| 4006 | Currently, the encoding of a Decimal instance is always |
| 4007 | canonical, so this method returns True for any Decimal. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4008 | |
| 4009 | >>> ExtendedContext.is_canonical(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4010 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4011 | """ |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4012 | return a.is_canonical() |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4013 | |
| 4014 | def is_finite(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4015 | """Return True if the operand is finite; otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4016 | |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4017 | A Decimal instance is considered finite if it is neither |
| 4018 | infinite nor a NaN. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4019 | |
| 4020 | >>> ExtendedContext.is_finite(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4021 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4022 | >>> ExtendedContext.is_finite(Decimal('-0.3')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4023 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4024 | >>> ExtendedContext.is_finite(Decimal('0')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4025 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4026 | >>> ExtendedContext.is_finite(Decimal('Inf')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4027 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4028 | >>> ExtendedContext.is_finite(Decimal('NaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4029 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4030 | """ |
| 4031 | return a.is_finite() |
| 4032 | |
| 4033 | def is_infinite(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4034 | """Return True if the operand is infinite; otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4035 | |
| 4036 | >>> ExtendedContext.is_infinite(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4037 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4038 | >>> ExtendedContext.is_infinite(Decimal('-Inf')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4039 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4040 | >>> ExtendedContext.is_infinite(Decimal('NaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4041 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4042 | """ |
| 4043 | return a.is_infinite() |
| 4044 | |
| 4045 | def is_nan(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4046 | """Return True if the operand is a qNaN or sNaN; |
| 4047 | otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4048 | |
| 4049 | >>> ExtendedContext.is_nan(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4050 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4051 | >>> ExtendedContext.is_nan(Decimal('NaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4052 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4053 | >>> ExtendedContext.is_nan(Decimal('-sNaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4054 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4055 | """ |
| 4056 | return a.is_nan() |
| 4057 | |
| 4058 | def is_normal(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4059 | """Return True if the operand is a normal number; |
| 4060 | otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4061 | |
| 4062 | >>> c = ExtendedContext.copy() |
| 4063 | >>> c.Emin = -999 |
| 4064 | >>> c.Emax = 999 |
| 4065 | >>> c.is_normal(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4066 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4067 | >>> c.is_normal(Decimal('0.1E-999')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4068 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4069 | >>> c.is_normal(Decimal('0.00')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4070 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4071 | >>> c.is_normal(Decimal('-Inf')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4072 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4073 | >>> c.is_normal(Decimal('NaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4074 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4075 | """ |
| 4076 | return a.is_normal(context=self) |
| 4077 | |
| 4078 | def is_qnan(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4079 | """Return True if the operand is a quiet NaN; otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4080 | |
| 4081 | >>> ExtendedContext.is_qnan(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4082 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4083 | >>> ExtendedContext.is_qnan(Decimal('NaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4084 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4085 | >>> ExtendedContext.is_qnan(Decimal('sNaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4086 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4087 | """ |
| 4088 | return a.is_qnan() |
| 4089 | |
| 4090 | def is_signed(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4091 | """Return True if the operand is negative; otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4092 | |
| 4093 | >>> ExtendedContext.is_signed(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4094 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4095 | >>> ExtendedContext.is_signed(Decimal('-12')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4096 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4097 | >>> ExtendedContext.is_signed(Decimal('-0')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4098 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4099 | """ |
| 4100 | return a.is_signed() |
| 4101 | |
| 4102 | def is_snan(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4103 | """Return True if the operand is a signaling NaN; |
| 4104 | otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4105 | |
| 4106 | >>> ExtendedContext.is_snan(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4107 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4108 | >>> ExtendedContext.is_snan(Decimal('NaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4109 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4110 | >>> ExtendedContext.is_snan(Decimal('sNaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4111 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4112 | """ |
| 4113 | return a.is_snan() |
| 4114 | |
| 4115 | def is_subnormal(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4116 | """Return True if the operand is subnormal; otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4117 | |
| 4118 | >>> c = ExtendedContext.copy() |
| 4119 | >>> c.Emin = -999 |
| 4120 | >>> c.Emax = 999 |
| 4121 | >>> c.is_subnormal(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4122 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4123 | >>> c.is_subnormal(Decimal('0.1E-999')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4124 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4125 | >>> c.is_subnormal(Decimal('0.00')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4126 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4127 | >>> c.is_subnormal(Decimal('-Inf')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4128 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4129 | >>> c.is_subnormal(Decimal('NaN')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4130 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4131 | """ |
| 4132 | return a.is_subnormal(context=self) |
| 4133 | |
| 4134 | def is_zero(self, a): |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4135 | """Return True if the operand is a zero; otherwise return False. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4136 | |
| 4137 | >>> ExtendedContext.is_zero(Decimal('0')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4138 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4139 | >>> ExtendedContext.is_zero(Decimal('2.50')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4140 | False |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4141 | >>> ExtendedContext.is_zero(Decimal('-0E+2')) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 4142 | True |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4143 | """ |
| 4144 | return a.is_zero() |
| 4145 | |
| 4146 | def ln(self, a): |
| 4147 | """Returns the natural (base e) logarithm of the operand. |
| 4148 | |
| 4149 | >>> c = ExtendedContext.copy() |
| 4150 | >>> c.Emin = -999 |
| 4151 | >>> c.Emax = 999 |
| 4152 | >>> c.ln(Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4153 | Decimal('-Infinity') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4154 | >>> c.ln(Decimal('1.000')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4155 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4156 | >>> c.ln(Decimal('2.71828183')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4157 | Decimal('1.00000000') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4158 | >>> c.ln(Decimal('10')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4159 | Decimal('2.30258509') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4160 | >>> c.ln(Decimal('+Infinity')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4161 | Decimal('Infinity') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4162 | """ |
| 4163 | return a.ln(context=self) |
| 4164 | |
| 4165 | def log10(self, a): |
| 4166 | """Returns the base 10 logarithm of the operand. |
| 4167 | |
| 4168 | >>> c = ExtendedContext.copy() |
| 4169 | >>> c.Emin = -999 |
| 4170 | >>> c.Emax = 999 |
| 4171 | >>> c.log10(Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4172 | Decimal('-Infinity') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4173 | >>> c.log10(Decimal('0.001')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4174 | Decimal('-3') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4175 | >>> c.log10(Decimal('1.000')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4176 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4177 | >>> c.log10(Decimal('2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4178 | Decimal('0.301029996') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4179 | >>> c.log10(Decimal('10')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4180 | Decimal('1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4181 | >>> c.log10(Decimal('70')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4182 | Decimal('1.84509804') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4183 | >>> c.log10(Decimal('+Infinity')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4184 | Decimal('Infinity') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4185 | """ |
| 4186 | return a.log10(context=self) |
| 4187 | |
| 4188 | def logb(self, a): |
| 4189 | """ Returns the exponent of the magnitude of the operand's MSD. |
| 4190 | |
| 4191 | The result is the integer which is the exponent of the magnitude |
| 4192 | of the most significant digit of the operand (as though the |
| 4193 | operand were truncated to a single digit while maintaining the |
| 4194 | value of that digit and without limiting the resulting exponent). |
| 4195 | |
| 4196 | >>> ExtendedContext.logb(Decimal('250')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4197 | Decimal('2') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4198 | >>> ExtendedContext.logb(Decimal('2.50')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4199 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4200 | >>> ExtendedContext.logb(Decimal('0.03')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4201 | Decimal('-2') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4202 | >>> ExtendedContext.logb(Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4203 | Decimal('-Infinity') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4204 | """ |
| 4205 | return a.logb(context=self) |
| 4206 | |
| 4207 | def logical_and(self, a, b): |
| 4208 | """Applies the logical operation 'and' between each operand's digits. |
| 4209 | |
| 4210 | The operands must be both logical numbers. |
| 4211 | |
| 4212 | >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4213 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4214 | >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4215 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4216 | >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4217 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4218 | >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4219 | Decimal('1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4220 | >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4221 | Decimal('1000') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4222 | >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4223 | Decimal('10') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4224 | """ |
| 4225 | return a.logical_and(b, context=self) |
| 4226 | |
| 4227 | def logical_invert(self, a): |
| 4228 | """Invert all the digits in the operand. |
| 4229 | |
| 4230 | The operand must be a logical number. |
| 4231 | |
| 4232 | >>> ExtendedContext.logical_invert(Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4233 | Decimal('111111111') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4234 | >>> ExtendedContext.logical_invert(Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4235 | Decimal('111111110') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4236 | >>> ExtendedContext.logical_invert(Decimal('111111111')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4237 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4238 | >>> ExtendedContext.logical_invert(Decimal('101010101')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4239 | Decimal('10101010') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4240 | """ |
| 4241 | return a.logical_invert(context=self) |
| 4242 | |
| 4243 | def logical_or(self, a, b): |
| 4244 | """Applies the logical operation 'or' between each operand's digits. |
| 4245 | |
| 4246 | The operands must be both logical numbers. |
| 4247 | |
| 4248 | >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4249 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4250 | >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4251 | Decimal('1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4252 | >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4253 | Decimal('1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4254 | >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4255 | Decimal('1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4256 | >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4257 | Decimal('1110') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4258 | >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4259 | Decimal('1110') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4260 | """ |
| 4261 | return a.logical_or(b, context=self) |
| 4262 | |
| 4263 | def logical_xor(self, a, b): |
| 4264 | """Applies the logical operation 'xor' between each operand's digits. |
| 4265 | |
| 4266 | The operands must be both logical numbers. |
| 4267 | |
| 4268 | >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4269 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4270 | >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4271 | Decimal('1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4272 | >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4273 | Decimal('1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4274 | >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4275 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4276 | >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4277 | Decimal('110') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4278 | >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4279 | Decimal('1101') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4280 | """ |
| 4281 | return a.logical_xor(b, context=self) |
| 4282 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4283 | def max(self, a,b): |
| 4284 | """max compares two values numerically and returns the maximum. |
| 4285 | |
| 4286 | If either operand is a NaN then the general rules apply. |
Andrew M. Kuchling | c8acc88 | 2008-01-16 00:32:03 +0000 | [diff] [blame] | 4287 | Otherwise, the operands are compared as though by the compare |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 4288 | operation. If they are numerically equal then the left-hand operand |
| 4289 | is chosen as the result. Otherwise the maximum (closer to positive |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4290 | infinity) of the two operands is chosen as the result. |
| 4291 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4292 | >>> ExtendedContext.max(Decimal('3'), Decimal('2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4293 | Decimal('3') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4294 | >>> ExtendedContext.max(Decimal('-10'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4295 | Decimal('3') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4296 | >>> ExtendedContext.max(Decimal('1.0'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4297 | Decimal('1') |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 4298 | >>> ExtendedContext.max(Decimal('7'), Decimal('NaN')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4299 | Decimal('7') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4300 | """ |
| 4301 | return a.max(b, context=self) |
| 4302 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4303 | def max_mag(self, a, b): |
| 4304 | """Compares the values numerically with their sign ignored.""" |
| 4305 | return a.max_mag(b, context=self) |
| 4306 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4307 | def min(self, a,b): |
| 4308 | """min compares two values numerically and returns the minimum. |
| 4309 | |
| 4310 | If either operand is a NaN then the general rules apply. |
Andrew M. Kuchling | c8acc88 | 2008-01-16 00:32:03 +0000 | [diff] [blame] | 4311 | Otherwise, the operands are compared as though by the compare |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 4312 | operation. If they are numerically equal then the left-hand operand |
| 4313 | is chosen as the result. Otherwise the minimum (closer to negative |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4314 | infinity) of the two operands is chosen as the result. |
| 4315 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4316 | >>> ExtendedContext.min(Decimal('3'), Decimal('2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4317 | Decimal('2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4318 | >>> ExtendedContext.min(Decimal('-10'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4319 | Decimal('-10') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4320 | >>> ExtendedContext.min(Decimal('1.0'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4321 | Decimal('1.0') |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 4322 | >>> ExtendedContext.min(Decimal('7'), Decimal('NaN')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4323 | Decimal('7') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4324 | """ |
| 4325 | return a.min(b, context=self) |
| 4326 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4327 | def min_mag(self, a, b): |
| 4328 | """Compares the values numerically with their sign ignored.""" |
| 4329 | return a.min_mag(b, context=self) |
| 4330 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4331 | def minus(self, a): |
| 4332 | """Minus corresponds to unary prefix minus in Python. |
| 4333 | |
| 4334 | The operation is evaluated using the same rules as subtract; the |
| 4335 | operation minus(a) is calculated as subtract('0', a) where the '0' |
| 4336 | has the same exponent as the operand. |
| 4337 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4338 | >>> ExtendedContext.minus(Decimal('1.3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4339 | Decimal('-1.3') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4340 | >>> ExtendedContext.minus(Decimal('-1.3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4341 | Decimal('1.3') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4342 | """ |
| 4343 | return a.__neg__(context=self) |
| 4344 | |
| 4345 | def multiply(self, a, b): |
| 4346 | """multiply multiplies two operands. |
| 4347 | |
Martin v. Löwis | cfe3128 | 2006-07-19 17:18:32 +0000 | [diff] [blame] | 4348 | If either operand is a special value then the general rules apply. |
| 4349 | Otherwise, the operands are multiplied together ('long multiplication'), |
| 4350 | resulting in a number which may be as long as the sum of the lengths |
| 4351 | of the two operands. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4352 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4353 | >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4354 | Decimal('3.60') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4355 | >>> ExtendedContext.multiply(Decimal('7'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4356 | Decimal('21') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4357 | >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4358 | Decimal('0.72') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4359 | >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4360 | Decimal('-0.0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4361 | >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4362 | Decimal('4.28135971E+11') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4363 | """ |
| 4364 | return a.__mul__(b, context=self) |
| 4365 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4366 | def next_minus(self, a): |
| 4367 | """Returns the largest representable number smaller than a. |
| 4368 | |
| 4369 | >>> c = ExtendedContext.copy() |
| 4370 | >>> c.Emin = -999 |
| 4371 | >>> c.Emax = 999 |
| 4372 | >>> ExtendedContext.next_minus(Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4373 | Decimal('0.999999999') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4374 | >>> c.next_minus(Decimal('1E-1007')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4375 | Decimal('0E-1007') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4376 | >>> ExtendedContext.next_minus(Decimal('-1.00000003')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4377 | Decimal('-1.00000004') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4378 | >>> c.next_minus(Decimal('Infinity')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4379 | Decimal('9.99999999E+999') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4380 | """ |
| 4381 | return a.next_minus(context=self) |
| 4382 | |
| 4383 | def next_plus(self, a): |
| 4384 | """Returns the smallest representable number larger than a. |
| 4385 | |
| 4386 | >>> c = ExtendedContext.copy() |
| 4387 | >>> c.Emin = -999 |
| 4388 | >>> c.Emax = 999 |
| 4389 | >>> ExtendedContext.next_plus(Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4390 | Decimal('1.00000001') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4391 | >>> c.next_plus(Decimal('-1E-1007')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4392 | Decimal('-0E-1007') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4393 | >>> ExtendedContext.next_plus(Decimal('-1.00000003')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4394 | Decimal('-1.00000002') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4395 | >>> c.next_plus(Decimal('-Infinity')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4396 | Decimal('-9.99999999E+999') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4397 | """ |
| 4398 | return a.next_plus(context=self) |
| 4399 | |
| 4400 | def next_toward(self, a, b): |
| 4401 | """Returns the number closest to a, in direction towards b. |
| 4402 | |
| 4403 | The result is the closest representable number from the first |
| 4404 | operand (but not the first operand) that is in the direction |
| 4405 | towards the second operand, unless the operands have the same |
| 4406 | value. |
| 4407 | |
| 4408 | >>> c = ExtendedContext.copy() |
| 4409 | >>> c.Emin = -999 |
| 4410 | >>> c.Emax = 999 |
| 4411 | >>> c.next_toward(Decimal('1'), Decimal('2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4412 | Decimal('1.00000001') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4413 | >>> c.next_toward(Decimal('-1E-1007'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4414 | Decimal('-0E-1007') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4415 | >>> c.next_toward(Decimal('-1.00000003'), Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4416 | Decimal('-1.00000002') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4417 | >>> c.next_toward(Decimal('1'), Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4418 | Decimal('0.999999999') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4419 | >>> c.next_toward(Decimal('1E-1007'), Decimal('-100')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4420 | Decimal('0E-1007') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4421 | >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4422 | Decimal('-1.00000004') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4423 | >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4424 | Decimal('-0.00') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4425 | """ |
| 4426 | return a.next_toward(b, context=self) |
| 4427 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4428 | def normalize(self, a): |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 4429 | """normalize reduces an operand to its simplest form. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4430 | |
| 4431 | Essentially a plus operation with all trailing zeros removed from the |
| 4432 | result. |
| 4433 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4434 | >>> ExtendedContext.normalize(Decimal('2.1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4435 | Decimal('2.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4436 | >>> ExtendedContext.normalize(Decimal('-2.0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4437 | Decimal('-2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4438 | >>> ExtendedContext.normalize(Decimal('1.200')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4439 | Decimal('1.2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4440 | >>> ExtendedContext.normalize(Decimal('-120')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4441 | Decimal('-1.2E+2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4442 | >>> ExtendedContext.normalize(Decimal('120.00')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4443 | Decimal('1.2E+2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4444 | >>> ExtendedContext.normalize(Decimal('0.00')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4445 | Decimal('0') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4446 | """ |
| 4447 | return a.normalize(context=self) |
| 4448 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4449 | def number_class(self, a): |
| 4450 | """Returns an indication of the class of the operand. |
| 4451 | |
| 4452 | The class is one of the following strings: |
| 4453 | -sNaN |
| 4454 | -NaN |
| 4455 | -Infinity |
| 4456 | -Normal |
| 4457 | -Subnormal |
| 4458 | -Zero |
| 4459 | +Zero |
| 4460 | +Subnormal |
| 4461 | +Normal |
| 4462 | +Infinity |
| 4463 | |
| 4464 | >>> c = Context(ExtendedContext) |
| 4465 | >>> c.Emin = -999 |
| 4466 | >>> c.Emax = 999 |
| 4467 | >>> c.number_class(Decimal('Infinity')) |
| 4468 | '+Infinity' |
| 4469 | >>> c.number_class(Decimal('1E-10')) |
| 4470 | '+Normal' |
| 4471 | >>> c.number_class(Decimal('2.50')) |
| 4472 | '+Normal' |
| 4473 | >>> c.number_class(Decimal('0.1E-999')) |
| 4474 | '+Subnormal' |
| 4475 | >>> c.number_class(Decimal('0')) |
| 4476 | '+Zero' |
| 4477 | >>> c.number_class(Decimal('-0')) |
| 4478 | '-Zero' |
| 4479 | >>> c.number_class(Decimal('-0.1E-999')) |
| 4480 | '-Subnormal' |
| 4481 | >>> c.number_class(Decimal('-1E-10')) |
| 4482 | '-Normal' |
| 4483 | >>> c.number_class(Decimal('-2.50')) |
| 4484 | '-Normal' |
| 4485 | >>> c.number_class(Decimal('-Infinity')) |
| 4486 | '-Infinity' |
| 4487 | >>> c.number_class(Decimal('NaN')) |
| 4488 | 'NaN' |
| 4489 | >>> c.number_class(Decimal('-NaN')) |
| 4490 | 'NaN' |
| 4491 | >>> c.number_class(Decimal('sNaN')) |
| 4492 | 'sNaN' |
| 4493 | """ |
| 4494 | return a.number_class(context=self) |
| 4495 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4496 | def plus(self, a): |
| 4497 | """Plus corresponds to unary prefix plus in Python. |
| 4498 | |
| 4499 | The operation is evaluated using the same rules as add; the |
| 4500 | operation plus(a) is calculated as add('0', a) where the '0' |
| 4501 | has the same exponent as the operand. |
| 4502 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4503 | >>> ExtendedContext.plus(Decimal('1.3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4504 | Decimal('1.3') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4505 | >>> ExtendedContext.plus(Decimal('-1.3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4506 | Decimal('-1.3') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4507 | """ |
| 4508 | return a.__pos__(context=self) |
| 4509 | |
| 4510 | def power(self, a, b, modulo=None): |
| 4511 | """Raises a to the power of b, to modulo if given. |
| 4512 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4513 | With two arguments, compute a**b. If a is negative then b |
| 4514 | must be integral. The result will be inexact unless b is |
| 4515 | integral and the result is finite and can be expressed exactly |
| 4516 | in 'precision' digits. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4517 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4518 | With three arguments, compute (a**b) % modulo. For the |
| 4519 | three argument form, the following restrictions on the |
| 4520 | arguments hold: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4521 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4522 | - all three arguments must be integral |
| 4523 | - b must be nonnegative |
| 4524 | - at least one of a or b must be nonzero |
| 4525 | - modulo must be nonzero and have at most 'precision' digits |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4526 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4527 | The result of pow(a, b, modulo) is identical to the result |
| 4528 | that would be obtained by computing (a**b) % modulo with |
| 4529 | unbounded precision, but is computed more efficiently. It is |
| 4530 | always exact. |
| 4531 | |
| 4532 | >>> c = ExtendedContext.copy() |
| 4533 | >>> c.Emin = -999 |
| 4534 | >>> c.Emax = 999 |
| 4535 | >>> c.power(Decimal('2'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4536 | Decimal('8') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4537 | >>> c.power(Decimal('-2'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4538 | Decimal('-8') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4539 | >>> c.power(Decimal('2'), Decimal('-3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4540 | Decimal('0.125') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4541 | >>> c.power(Decimal('1.7'), Decimal('8')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4542 | Decimal('69.7575744') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4543 | >>> c.power(Decimal('10'), Decimal('0.301029996')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4544 | Decimal('2.00000000') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4545 | >>> c.power(Decimal('Infinity'), Decimal('-1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4546 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4547 | >>> c.power(Decimal('Infinity'), Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4548 | Decimal('1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4549 | >>> c.power(Decimal('Infinity'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4550 | Decimal('Infinity') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4551 | >>> c.power(Decimal('-Infinity'), Decimal('-1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4552 | Decimal('-0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4553 | >>> c.power(Decimal('-Infinity'), Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4554 | Decimal('1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4555 | >>> c.power(Decimal('-Infinity'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4556 | Decimal('-Infinity') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4557 | >>> c.power(Decimal('-Infinity'), Decimal('2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4558 | Decimal('Infinity') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4559 | >>> c.power(Decimal('0'), Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4560 | Decimal('NaN') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4561 | |
| 4562 | >>> c.power(Decimal('3'), Decimal('7'), Decimal('16')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4563 | Decimal('11') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4564 | >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4565 | Decimal('-11') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4566 | >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4567 | Decimal('1') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4568 | >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4569 | Decimal('11') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4570 | >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4571 | Decimal('11729830') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4572 | >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4573 | Decimal('-0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4574 | >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4575 | Decimal('1') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4576 | """ |
| 4577 | return a.__pow__(b, modulo, context=self) |
| 4578 | |
| 4579 | def quantize(self, a, b): |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 4580 | """Returns a value equal to 'a' (rounded), having the exponent of 'b'. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4581 | |
| 4582 | 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] | 4583 | operand. It may be rounded using the current rounding setting (if the |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4584 | exponent is being increased), multiplied by a positive power of ten (if |
| 4585 | the exponent is being decreased), or is unchanged (if the exponent is |
| 4586 | already equal to that of the right-hand operand). |
| 4587 | |
| 4588 | Unlike other operations, if the length of the coefficient after the |
| 4589 | quantize operation would be greater than precision then an Invalid |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 4590 | operation condition is raised. This guarantees that, unless there is |
| 4591 | 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] | 4592 | equal to that of the right-hand operand. |
| 4593 | |
| 4594 | Also unlike other operations, quantize will never raise Underflow, even |
| 4595 | if the result is subnormal and inexact. |
| 4596 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4597 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4598 | Decimal('2.170') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4599 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4600 | Decimal('2.17') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4601 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4602 | Decimal('2.2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4603 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4604 | Decimal('2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4605 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4606 | Decimal('0E+1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4607 | >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4608 | Decimal('-Infinity') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4609 | >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4610 | Decimal('NaN') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4611 | >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4612 | Decimal('-0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4613 | >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4614 | Decimal('-0E+5') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4615 | >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4616 | Decimal('NaN') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4617 | >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4618 | Decimal('NaN') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4619 | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4620 | Decimal('217.0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4621 | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4622 | Decimal('217') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4623 | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4624 | Decimal('2.2E+2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4625 | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4626 | Decimal('2E+2') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4627 | """ |
| 4628 | return a.quantize(b, context=self) |
| 4629 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4630 | def radix(self): |
| 4631 | """Just returns 10, as this is Decimal, :) |
| 4632 | |
| 4633 | >>> ExtendedContext.radix() |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4634 | Decimal('10') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4635 | """ |
| 4636 | return Decimal(10) |
| 4637 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4638 | def remainder(self, a, b): |
| 4639 | """Returns the remainder from integer division. |
| 4640 | |
| 4641 | The result is the residue of the dividend after the operation of |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 4642 | calculating integer division as described for divide-integer, rounded |
Neal Norwitz | 0d4c06e | 2007-04-25 06:30:05 +0000 | [diff] [blame] | 4643 | to precision digits if necessary. The sign of the result, if |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 4644 | non-zero, is the same as that of the original dividend. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4645 | |
| 4646 | This operation will fail under the same conditions as integer division |
| 4647 | (that is, if integer division on the same two operands would fail, the |
| 4648 | remainder cannot be calculated). |
| 4649 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4650 | >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4651 | Decimal('2.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4652 | >>> ExtendedContext.remainder(Decimal('10'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4653 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4654 | >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4655 | Decimal('-1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4656 | >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4657 | Decimal('0.2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4658 | >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4659 | Decimal('0.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4660 | >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4661 | Decimal('1.0') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4662 | """ |
| 4663 | return a.__mod__(b, context=self) |
| 4664 | |
| 4665 | def remainder_near(self, a, b): |
| 4666 | """Returns to be "a - b * n", where n is the integer nearest the exact |
| 4667 | 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] | 4668 | 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] | 4669 | sign of a. |
| 4670 | |
| 4671 | This operation will fail under the same conditions as integer division |
| 4672 | (that is, if integer division on the same two operands would fail, the |
| 4673 | remainder cannot be calculated). |
| 4674 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4675 | >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4676 | Decimal('-0.9') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4677 | >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4678 | Decimal('-2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4679 | >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4680 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4681 | >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4682 | Decimal('-1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4683 | >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4684 | Decimal('0.2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4685 | >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4686 | Decimal('0.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4687 | >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4688 | Decimal('-0.3') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4689 | """ |
| 4690 | return a.remainder_near(b, context=self) |
| 4691 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4692 | def rotate(self, a, b): |
| 4693 | """Returns a rotated copy of a, b times. |
| 4694 | |
| 4695 | The coefficient of the result is a rotated copy of the digits in |
| 4696 | the coefficient of the first operand. The number of places of |
| 4697 | rotation is taken from the absolute value of the second operand, |
| 4698 | with the rotation being to the left if the second operand is |
| 4699 | positive or to the right otherwise. |
| 4700 | |
| 4701 | >>> ExtendedContext.rotate(Decimal('34'), Decimal('8')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4702 | Decimal('400000003') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4703 | >>> ExtendedContext.rotate(Decimal('12'), Decimal('9')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4704 | Decimal('12') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4705 | >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4706 | Decimal('891234567') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4707 | >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4708 | Decimal('123456789') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4709 | >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4710 | Decimal('345678912') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4711 | """ |
| 4712 | return a.rotate(b, context=self) |
| 4713 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4714 | def same_quantum(self, a, b): |
| 4715 | """Returns True if the two operands have the same exponent. |
| 4716 | |
| 4717 | The result is never affected by either the sign or the coefficient of |
| 4718 | either operand. |
| 4719 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4720 | >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4721 | False |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4722 | >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4723 | True |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4724 | >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4725 | False |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4726 | >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4727 | True |
| 4728 | """ |
| 4729 | return a.same_quantum(b) |
| 4730 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4731 | def scaleb (self, a, b): |
| 4732 | """Returns the first operand after adding the second value its exp. |
| 4733 | |
| 4734 | >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4735 | Decimal('0.0750') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4736 | >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4737 | Decimal('7.50') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4738 | >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4739 | Decimal('7.50E+3') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4740 | """ |
| 4741 | return a.scaleb (b, context=self) |
| 4742 | |
| 4743 | def shift(self, a, b): |
| 4744 | """Returns a shifted copy of a, b times. |
| 4745 | |
| 4746 | The coefficient of the result is a shifted copy of the digits |
| 4747 | in the coefficient of the first operand. The number of places |
| 4748 | to shift is taken from the absolute value of the second operand, |
| 4749 | with the shift being to the left if the second operand is |
| 4750 | positive or to the right otherwise. Digits shifted into the |
| 4751 | coefficient are zeros. |
| 4752 | |
| 4753 | >>> ExtendedContext.shift(Decimal('34'), Decimal('8')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4754 | Decimal('400000000') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4755 | >>> ExtendedContext.shift(Decimal('12'), Decimal('9')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4756 | Decimal('0') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4757 | >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4758 | Decimal('1234567') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4759 | >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4760 | Decimal('123456789') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4761 | >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4762 | Decimal('345678900') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4763 | """ |
| 4764 | return a.shift(b, context=self) |
| 4765 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4766 | def sqrt(self, a): |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 4767 | """Square root of a non-negative number to context precision. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4768 | |
| 4769 | If the result must be inexact, it is rounded using the round-half-even |
| 4770 | algorithm. |
| 4771 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4772 | >>> ExtendedContext.sqrt(Decimal('0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4773 | Decimal('0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4774 | >>> ExtendedContext.sqrt(Decimal('-0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4775 | Decimal('-0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4776 | >>> ExtendedContext.sqrt(Decimal('0.39')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4777 | Decimal('0.624499800') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4778 | >>> ExtendedContext.sqrt(Decimal('100')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4779 | Decimal('10') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4780 | >>> ExtendedContext.sqrt(Decimal('1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4781 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4782 | >>> ExtendedContext.sqrt(Decimal('1.0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4783 | Decimal('1.0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4784 | >>> ExtendedContext.sqrt(Decimal('1.00')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4785 | Decimal('1.0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4786 | >>> ExtendedContext.sqrt(Decimal('7')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4787 | Decimal('2.64575131') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4788 | >>> ExtendedContext.sqrt(Decimal('10')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4789 | Decimal('3.16227766') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4790 | >>> ExtendedContext.prec |
Raymond Hettinger | 6ea4845 | 2004-07-03 12:26:21 +0000 | [diff] [blame] | 4791 | 9 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4792 | """ |
| 4793 | return a.sqrt(context=self) |
| 4794 | |
| 4795 | def subtract(self, a, b): |
Georg Brandl | f33d01d | 2005-08-22 19:35:18 +0000 | [diff] [blame] | 4796 | """Return the difference between the two operands. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4797 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4798 | >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4799 | Decimal('0.23') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4800 | >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4801 | Decimal('0.00') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4802 | >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4803 | Decimal('-0.77') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4804 | """ |
| 4805 | return a.__sub__(b, context=self) |
| 4806 | |
| 4807 | def to_eng_string(self, a): |
| 4808 | """Converts a number to a string, using scientific notation. |
| 4809 | |
| 4810 | The operation is not affected by the context. |
| 4811 | """ |
| 4812 | return a.to_eng_string(context=self) |
| 4813 | |
| 4814 | def to_sci_string(self, a): |
| 4815 | """Converts a number to a string, using scientific notation. |
| 4816 | |
| 4817 | The operation is not affected by the context. |
| 4818 | """ |
| 4819 | return a.__str__(context=self) |
| 4820 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4821 | def to_integral_exact(self, a): |
| 4822 | """Rounds to an integer. |
| 4823 | |
| 4824 | When the operand has a negative exponent, the result is the same |
| 4825 | as using the quantize() operation using the given operand as the |
| 4826 | left-hand-operand, 1E+0 as the right-hand-operand, and the precision |
| 4827 | of the operand as the precision setting; Inexact and Rounded flags |
| 4828 | are allowed in this operation. The rounding mode is taken from the |
| 4829 | context. |
| 4830 | |
| 4831 | >>> ExtendedContext.to_integral_exact(Decimal('2.1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4832 | Decimal('2') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4833 | >>> ExtendedContext.to_integral_exact(Decimal('100')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4834 | Decimal('100') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4835 | >>> ExtendedContext.to_integral_exact(Decimal('100.0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4836 | Decimal('100') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4837 | >>> ExtendedContext.to_integral_exact(Decimal('101.5')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4838 | Decimal('102') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4839 | >>> ExtendedContext.to_integral_exact(Decimal('-101.5')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4840 | Decimal('-102') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4841 | >>> ExtendedContext.to_integral_exact(Decimal('10E+5')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4842 | Decimal('1.0E+6') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4843 | >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4844 | Decimal('7.89E+77') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4845 | >>> ExtendedContext.to_integral_exact(Decimal('-Inf')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4846 | Decimal('-Infinity') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4847 | """ |
| 4848 | return a.to_integral_exact(context=self) |
| 4849 | |
| 4850 | def to_integral_value(self, a): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4851 | """Rounds to an integer. |
| 4852 | |
| 4853 | When the operand has a negative exponent, the result is the same |
| 4854 | as using the quantize() operation using the given operand as the |
| 4855 | left-hand-operand, 1E+0 as the right-hand-operand, and the precision |
| 4856 | of the operand as the precision setting, except that no flags will |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 4857 | be set. The rounding mode is taken from the context. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4858 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4859 | >>> ExtendedContext.to_integral_value(Decimal('2.1')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4860 | Decimal('2') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4861 | >>> ExtendedContext.to_integral_value(Decimal('100')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4862 | Decimal('100') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4863 | >>> ExtendedContext.to_integral_value(Decimal('100.0')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4864 | Decimal('100') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4865 | >>> ExtendedContext.to_integral_value(Decimal('101.5')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4866 | Decimal('102') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4867 | >>> ExtendedContext.to_integral_value(Decimal('-101.5')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4868 | Decimal('-102') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4869 | >>> ExtendedContext.to_integral_value(Decimal('10E+5')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4870 | Decimal('1.0E+6') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4871 | >>> ExtendedContext.to_integral_value(Decimal('7.89E+77')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4872 | Decimal('7.89E+77') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4873 | >>> ExtendedContext.to_integral_value(Decimal('-Inf')) |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 4874 | Decimal('-Infinity') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4875 | """ |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4876 | return a.to_integral_value(context=self) |
| 4877 | |
| 4878 | # the method name changed, but we provide also the old one, for compatibility |
| 4879 | to_integral = to_integral_value |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4880 | |
| 4881 | class _WorkRep(object): |
| 4882 | __slots__ = ('sign','int','exp') |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 4883 | # sign: 0 or 1 |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 4884 | # int: int or long |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4885 | # exp: None, int, or string |
| 4886 | |
| 4887 | def __init__(self, value=None): |
| 4888 | if value is None: |
| 4889 | self.sign = None |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 4890 | self.int = 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4891 | self.exp = None |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 4892 | elif isinstance(value, Decimal): |
| 4893 | self.sign = value._sign |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 4894 | self.int = int(value._int) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4895 | self.exp = value._exp |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 4896 | else: |
| 4897 | # assert isinstance(value, tuple) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4898 | self.sign = value[0] |
| 4899 | self.int = value[1] |
| 4900 | self.exp = value[2] |
| 4901 | |
| 4902 | def __repr__(self): |
| 4903 | return "(%r, %r, %r)" % (self.sign, self.int, self.exp) |
| 4904 | |
| 4905 | __str__ = __repr__ |
| 4906 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4907 | |
| 4908 | |
Facundo Batista | e64acfa | 2007-12-17 14:18:42 +0000 | [diff] [blame] | 4909 | def _normalize(op1, op2, prec = 0): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4910 | """Normalizes op1, op2 to have the same exp and length of coefficient. |
| 4911 | |
| 4912 | Done during addition. |
| 4913 | """ |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4914 | if op1.exp < op2.exp: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4915 | tmp = op2 |
| 4916 | other = op1 |
| 4917 | else: |
| 4918 | tmp = op1 |
| 4919 | other = op2 |
| 4920 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4921 | # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1). |
| 4922 | # Then adding 10**exp to tmp has the same effect (after rounding) |
| 4923 | # as adding any positive quantity smaller than 10**exp; similarly |
| 4924 | # for subtraction. So if other is smaller than 10**exp we replace |
| 4925 | # 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] | 4926 | tmp_len = len(str(tmp.int)) |
| 4927 | other_len = len(str(other.int)) |
| 4928 | exp = tmp.exp + min(-1, tmp_len - prec - 2) |
| 4929 | if other_len + other.exp - 1 < exp: |
| 4930 | other.int = 1 |
| 4931 | other.exp = exp |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 4932 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4933 | tmp.int *= 10 ** (tmp.exp - other.exp) |
| 4934 | tmp.exp = other.exp |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4935 | return op1, op2 |
| 4936 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 4937 | ##### Integer arithmetic functions used by ln, log10, exp and __pow__ ##### |
| 4938 | |
| 4939 | # This function from Tim Peters was taken from here: |
| 4940 | # http://mail.python.org/pipermail/python-list/1999-July/007758.html |
| 4941 | # The correction being in the function definition is for speed, and |
| 4942 | # the whole function is not resolved with math.log because of avoiding |
| 4943 | # the use of floats. |
| 4944 | def _nbits(n, correction = { |
| 4945 | '0': 4, '1': 3, '2': 2, '3': 2, |
| 4946 | '4': 1, '5': 1, '6': 1, '7': 1, |
| 4947 | '8': 0, '9': 0, 'a': 0, 'b': 0, |
| 4948 | 'c': 0, 'd': 0, 'e': 0, 'f': 0}): |
| 4949 | """Number of bits in binary representation of the positive integer n, |
| 4950 | or 0 if n == 0. |
| 4951 | """ |
| 4952 | if n < 0: |
| 4953 | raise ValueError("The argument to _nbits should be nonnegative.") |
| 4954 | hex_n = "%x" % n |
| 4955 | return 4*len(hex_n) - correction[hex_n[0]] |
| 4956 | |
| 4957 | def _sqrt_nearest(n, a): |
| 4958 | """Closest integer to the square root of the positive integer n. a is |
| 4959 | an initial approximation to the square root. Any positive integer |
| 4960 | will do for a, but the closer a is to the square root of n the |
| 4961 | faster convergence will be. |
| 4962 | |
| 4963 | """ |
| 4964 | if n <= 0 or a <= 0: |
| 4965 | raise ValueError("Both arguments to _sqrt_nearest should be positive.") |
| 4966 | |
| 4967 | b=0 |
| 4968 | while a != b: |
| 4969 | b, a = a, a--n//a>>1 |
| 4970 | return a |
| 4971 | |
| 4972 | def _rshift_nearest(x, shift): |
| 4973 | """Given an integer x and a nonnegative integer shift, return closest |
| 4974 | integer to x / 2**shift; use round-to-even in case of a tie. |
| 4975 | |
| 4976 | """ |
| 4977 | b, q = 1L << shift, x >> shift |
| 4978 | return q + (2*(x & (b-1)) + (q&1) > b) |
| 4979 | |
| 4980 | def _div_nearest(a, b): |
| 4981 | """Closest integer to a/b, a and b positive integers; rounds to even |
| 4982 | in the case of a tie. |
| 4983 | |
| 4984 | """ |
| 4985 | q, r = divmod(a, b) |
| 4986 | return q + (2*r + (q&1) > b) |
| 4987 | |
| 4988 | def _ilog(x, M, L = 8): |
| 4989 | """Integer approximation to M*log(x/M), with absolute error boundable |
| 4990 | in terms only of x/M. |
| 4991 | |
| 4992 | Given positive integers x and M, return an integer approximation to |
| 4993 | M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference |
| 4994 | between the approximation and the exact result is at most 22. For |
| 4995 | L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In |
| 4996 | both cases these are upper bounds on the error; it will usually be |
| 4997 | much smaller.""" |
| 4998 | |
| 4999 | # The basic algorithm is the following: let log1p be the function |
| 5000 | # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use |
| 5001 | # the reduction |
| 5002 | # |
| 5003 | # log1p(y) = 2*log1p(y/(1+sqrt(1+y))) |
| 5004 | # |
| 5005 | # repeatedly until the argument to log1p is small (< 2**-L in |
| 5006 | # absolute value). For small y we can use the Taylor series |
| 5007 | # expansion |
| 5008 | # |
| 5009 | # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T |
| 5010 | # |
| 5011 | # truncating at T such that y**T is small enough. The whole |
| 5012 | # computation is carried out in a form of fixed-point arithmetic, |
| 5013 | # with a real number z being represented by an integer |
| 5014 | # approximation to z*M. To avoid loss of precision, the y below |
| 5015 | # is actually an integer approximation to 2**R*y*M, where R is the |
| 5016 | # number of reductions performed so far. |
| 5017 | |
| 5018 | y = x-M |
| 5019 | # argument reduction; R = number of reductions performed |
| 5020 | R = 0 |
| 5021 | while (R <= L and long(abs(y)) << L-R >= M or |
| 5022 | R > L and abs(y) >> R-L >= M): |
| 5023 | y = _div_nearest(long(M*y) << 1, |
| 5024 | M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M)) |
| 5025 | R += 1 |
| 5026 | |
| 5027 | # Taylor series with T terms |
| 5028 | T = -int(-10*len(str(M))//(3*L)) |
| 5029 | yshift = _rshift_nearest(y, R) |
| 5030 | w = _div_nearest(M, T) |
| 5031 | for k in xrange(T-1, 0, -1): |
| 5032 | w = _div_nearest(M, k) - _div_nearest(yshift*w, M) |
| 5033 | |
| 5034 | return _div_nearest(w*y, M) |
| 5035 | |
| 5036 | def _dlog10(c, e, p): |
| 5037 | """Given integers c, e and p with c > 0, p >= 0, compute an integer |
| 5038 | approximation to 10**p * log10(c*10**e), with an absolute error of |
| 5039 | at most 1. Assumes that c*10**e is not exactly 1.""" |
| 5040 | |
| 5041 | # increase precision by 2; compensate for this by dividing |
| 5042 | # final result by 100 |
| 5043 | p += 2 |
| 5044 | |
| 5045 | # write c*10**e as d*10**f with either: |
| 5046 | # f >= 0 and 1 <= d <= 10, or |
| 5047 | # f <= 0 and 0.1 <= d <= 1. |
| 5048 | # Thus for c*10**e close to 1, f = 0 |
| 5049 | l = len(str(c)) |
| 5050 | f = e+l - (e+l >= 1) |
| 5051 | |
| 5052 | if p > 0: |
| 5053 | M = 10**p |
| 5054 | k = e+p-f |
| 5055 | if k >= 0: |
| 5056 | c *= 10**k |
| 5057 | else: |
| 5058 | c = _div_nearest(c, 10**-k) |
| 5059 | |
| 5060 | log_d = _ilog(c, M) # error < 5 + 22 = 27 |
Facundo Batista | be6c7ba | 2007-10-02 18:21:18 +0000 | [diff] [blame] | 5061 | log_10 = _log10_digits(p) # error < 1 |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5062 | log_d = _div_nearest(log_d*M, log_10) |
| 5063 | log_tenpower = f*M # exact |
| 5064 | else: |
| 5065 | log_d = 0 # error < 2.31 |
| 5066 | log_tenpower = div_nearest(f, 10**-p) # error < 0.5 |
| 5067 | |
| 5068 | return _div_nearest(log_tenpower+log_d, 100) |
| 5069 | |
| 5070 | def _dlog(c, e, p): |
| 5071 | """Given integers c, e and p with c > 0, compute an integer |
| 5072 | approximation to 10**p * log(c*10**e), with an absolute error of |
| 5073 | at most 1. Assumes that c*10**e is not exactly 1.""" |
| 5074 | |
| 5075 | # Increase precision by 2. The precision increase is compensated |
| 5076 | # for at the end with a division by 100. |
| 5077 | p += 2 |
| 5078 | |
| 5079 | # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10, |
| 5080 | # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e) |
| 5081 | # as 10**p * log(d) + 10**p*f * log(10). |
| 5082 | l = len(str(c)) |
| 5083 | f = e+l - (e+l >= 1) |
| 5084 | |
| 5085 | # compute approximation to 10**p*log(d), with error < 27 |
| 5086 | if p > 0: |
| 5087 | k = e+p-f |
| 5088 | if k >= 0: |
| 5089 | c *= 10**k |
| 5090 | else: |
| 5091 | c = _div_nearest(c, 10**-k) # error of <= 0.5 in c |
| 5092 | |
| 5093 | # _ilog magnifies existing error in c by a factor of at most 10 |
| 5094 | log_d = _ilog(c, 10**p) # error < 5 + 22 = 27 |
| 5095 | else: |
| 5096 | # p <= 0: just approximate the whole thing by 0; error < 2.31 |
| 5097 | log_d = 0 |
| 5098 | |
Facundo Batista | be6c7ba | 2007-10-02 18:21:18 +0000 | [diff] [blame] | 5099 | # compute approximation to f*10**p*log(10), with error < 11. |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5100 | if f: |
Facundo Batista | be6c7ba | 2007-10-02 18:21:18 +0000 | [diff] [blame] | 5101 | extra = len(str(abs(f)))-1 |
| 5102 | if p + extra >= 0: |
| 5103 | # error in f * _log10_digits(p+extra) < |f| * 1 = |f| |
| 5104 | # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11 |
| 5105 | f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5106 | else: |
| 5107 | f_log_ten = 0 |
| 5108 | else: |
| 5109 | f_log_ten = 0 |
| 5110 | |
Facundo Batista | be6c7ba | 2007-10-02 18:21:18 +0000 | [diff] [blame] | 5111 | # 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] | 5112 | return _div_nearest(f_log_ten + log_d, 100) |
| 5113 | |
Facundo Batista | be6c7ba | 2007-10-02 18:21:18 +0000 | [diff] [blame] | 5114 | class _Log10Memoize(object): |
| 5115 | """Class to compute, store, and allow retrieval of, digits of the |
| 5116 | constant log(10) = 2.302585.... This constant is needed by |
| 5117 | Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__.""" |
| 5118 | def __init__(self): |
| 5119 | self.digits = "23025850929940456840179914546843642076011014886" |
| 5120 | |
| 5121 | def getdigits(self, p): |
| 5122 | """Given an integer p >= 0, return floor(10**p)*log(10). |
| 5123 | |
| 5124 | For example, self.getdigits(3) returns 2302. |
| 5125 | """ |
| 5126 | # digits are stored as a string, for quick conversion to |
| 5127 | # integer in the case that we've already computed enough |
| 5128 | # digits; the stored digits should always be correct |
| 5129 | # (truncated, not rounded to nearest). |
| 5130 | if p < 0: |
| 5131 | raise ValueError("p should be nonnegative") |
| 5132 | |
| 5133 | if p >= len(self.digits): |
| 5134 | # compute p+3, p+6, p+9, ... digits; continue until at |
| 5135 | # least one of the extra digits is nonzero |
| 5136 | extra = 3 |
| 5137 | while True: |
| 5138 | # compute p+extra digits, correct to within 1ulp |
| 5139 | M = 10**(p+extra+2) |
| 5140 | digits = str(_div_nearest(_ilog(10*M, M), 100)) |
| 5141 | if digits[-extra:] != '0'*extra: |
| 5142 | break |
| 5143 | extra += 3 |
| 5144 | # keep all reliable digits so far; remove trailing zeros |
| 5145 | # and next nonzero digit |
| 5146 | self.digits = digits.rstrip('0')[:-1] |
| 5147 | return int(self.digits[:p+1]) |
| 5148 | |
| 5149 | _log10_digits = _Log10Memoize().getdigits |
| 5150 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5151 | def _iexp(x, M, L=8): |
| 5152 | """Given integers x and M, M > 0, such that x/M is small in absolute |
| 5153 | value, compute an integer approximation to M*exp(x/M). For 0 <= |
| 5154 | x/M <= 2.4, the absolute error in the result is bounded by 60 (and |
| 5155 | is usually much smaller).""" |
| 5156 | |
| 5157 | # Algorithm: to compute exp(z) for a real number z, first divide z |
| 5158 | # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then |
| 5159 | # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor |
| 5160 | # series |
| 5161 | # |
| 5162 | # expm1(x) = x + x**2/2! + x**3/3! + ... |
| 5163 | # |
| 5164 | # Now use the identity |
| 5165 | # |
| 5166 | # expm1(2x) = expm1(x)*(expm1(x)+2) |
| 5167 | # |
| 5168 | # R times to compute the sequence expm1(z/2**R), |
| 5169 | # expm1(z/2**(R-1)), ... , exp(z/2), exp(z). |
| 5170 | |
| 5171 | # Find R such that x/2**R/M <= 2**-L |
| 5172 | R = _nbits((long(x)<<L)//M) |
| 5173 | |
| 5174 | # Taylor series. (2**L)**T > M |
| 5175 | T = -int(-10*len(str(M))//(3*L)) |
| 5176 | y = _div_nearest(x, T) |
| 5177 | Mshift = long(M)<<R |
| 5178 | for i in xrange(T-1, 0, -1): |
| 5179 | y = _div_nearest(x*(Mshift + y), Mshift * i) |
| 5180 | |
| 5181 | # Expansion |
| 5182 | for k in xrange(R-1, -1, -1): |
| 5183 | Mshift = long(M)<<(k+2) |
| 5184 | y = _div_nearest(y*(y+Mshift), Mshift) |
| 5185 | |
| 5186 | return M+y |
| 5187 | |
| 5188 | def _dexp(c, e, p): |
| 5189 | """Compute an approximation to exp(c*10**e), with p decimal places of |
| 5190 | precision. |
| 5191 | |
Facundo Batista | be6c7ba | 2007-10-02 18:21:18 +0000 | [diff] [blame] | 5192 | Returns integers d, f such that: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5193 | |
| 5194 | 10**(p-1) <= d <= 10**p, and |
| 5195 | (d-1)*10**f < exp(c*10**e) < (d+1)*10**f |
| 5196 | |
| 5197 | In other words, d*10**f is an approximation to exp(c*10**e) with p |
| 5198 | digits of precision, and with an error in d of at most 1. This is |
| 5199 | almost, but not quite, the same as the error being < 1ulp: when d |
| 5200 | = 10**(p-1) the error could be up to 10 ulp.""" |
| 5201 | |
| 5202 | # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision |
| 5203 | p += 2 |
| 5204 | |
Facundo Batista | be6c7ba | 2007-10-02 18:21:18 +0000 | [diff] [blame] | 5205 | # compute log(10) with extra precision = adjusted exponent of c*10**e |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5206 | extra = max(0, e + len(str(c)) - 1) |
| 5207 | q = p + extra |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5208 | |
Facundo Batista | be6c7ba | 2007-10-02 18:21:18 +0000 | [diff] [blame] | 5209 | # 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] | 5210 | # rounding down |
| 5211 | shift = e+q |
| 5212 | if shift >= 0: |
| 5213 | cshift = c*10**shift |
| 5214 | else: |
| 5215 | cshift = c//10**-shift |
Facundo Batista | be6c7ba | 2007-10-02 18:21:18 +0000 | [diff] [blame] | 5216 | quot, rem = divmod(cshift, _log10_digits(q)) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5217 | |
| 5218 | # reduce remainder back to original precision |
| 5219 | rem = _div_nearest(rem, 10**extra) |
| 5220 | |
| 5221 | # error in result of _iexp < 120; error after division < 0.62 |
| 5222 | return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3 |
| 5223 | |
| 5224 | def _dpower(xc, xe, yc, ye, p): |
| 5225 | """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and |
| 5226 | y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that: |
| 5227 | |
| 5228 | 10**(p-1) <= c <= 10**p, and |
| 5229 | (c-1)*10**e < x**y < (c+1)*10**e |
| 5230 | |
| 5231 | in other words, c*10**e is an approximation to x**y with p digits |
| 5232 | of precision, and with an error in c of at most 1. (This is |
| 5233 | almost, but not quite, the same as the error being < 1ulp: when c |
| 5234 | == 10**(p-1) we can only guarantee error < 10ulp.) |
| 5235 | |
| 5236 | We assume that: x is positive and not equal to 1, and y is nonzero. |
| 5237 | """ |
| 5238 | |
| 5239 | # Find b such that 10**(b-1) <= |y| <= 10**b |
| 5240 | b = len(str(abs(yc))) + ye |
| 5241 | |
| 5242 | # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point |
| 5243 | lxc = _dlog(xc, xe, p+b+1) |
| 5244 | |
| 5245 | # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1) |
| 5246 | shift = ye-b |
| 5247 | if shift >= 0: |
| 5248 | pc = lxc*yc*10**shift |
| 5249 | else: |
| 5250 | pc = _div_nearest(lxc*yc, 10**-shift) |
| 5251 | |
| 5252 | if pc == 0: |
| 5253 | # we prefer a result that isn't exactly 1; this makes it |
| 5254 | # easier to compute a correctly rounded result in __pow__ |
| 5255 | if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1: |
| 5256 | coeff, exp = 10**(p-1)+1, 1-p |
| 5257 | else: |
| 5258 | coeff, exp = 10**p-1, -p |
| 5259 | else: |
| 5260 | coeff, exp = _dexp(pc, -(p+1), p+1) |
| 5261 | coeff = _div_nearest(coeff, 10) |
| 5262 | exp += 1 |
| 5263 | |
| 5264 | return coeff, exp |
| 5265 | |
| 5266 | def _log10_lb(c, correction = { |
| 5267 | '1': 100, '2': 70, '3': 53, '4': 40, '5': 31, |
| 5268 | '6': 23, '7': 16, '8': 10, '9': 5}): |
| 5269 | """Compute a lower bound for 100*log10(c) for a positive integer c.""" |
| 5270 | if c <= 0: |
| 5271 | raise ValueError("The argument to _log10_lb should be nonnegative.") |
| 5272 | str_c = str(c) |
| 5273 | return 100*len(str_c) - correction[str_c[0]] |
| 5274 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 5275 | ##### Helper Functions #################################################### |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5276 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5277 | def _convert_other(other, raiseit=False): |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5278 | """Convert other to Decimal. |
| 5279 | |
| 5280 | Verifies that it's ok to use in an implicit construction. |
| 5281 | """ |
| 5282 | if isinstance(other, Decimal): |
| 5283 | return other |
| 5284 | if isinstance(other, (int, long)): |
| 5285 | return Decimal(other) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5286 | if raiseit: |
| 5287 | raise TypeError("Unable to convert %s to Decimal" % other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 5288 | return NotImplemented |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5289 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 5290 | ##### Setup Specific Contexts ############################################ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5291 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5292 | # The default context prototype used by Context() |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 5293 | # Is mutable, so that new contexts can have different default values |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5294 | |
| 5295 | DefaultContext = Context( |
Raymond Hettinger | 6ea4845 | 2004-07-03 12:26:21 +0000 | [diff] [blame] | 5296 | prec=28, rounding=ROUND_HALF_EVEN, |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 5297 | traps=[DivisionByZero, Overflow, InvalidOperation], |
| 5298 | flags=[], |
Raymond Hettinger | 99148e7 | 2004-07-14 19:56:56 +0000 | [diff] [blame] | 5299 | Emax=999999999, |
| 5300 | Emin=-999999999, |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 5301 | capitals=1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5302 | ) |
| 5303 | |
| 5304 | # Pre-made alternate contexts offered by the specification |
| 5305 | # Don't change these; the user should be able to select these |
| 5306 | # contexts and be able to reproduce results from other implementations |
| 5307 | # of the spec. |
| 5308 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5309 | BasicContext = Context( |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5310 | prec=9, rounding=ROUND_HALF_UP, |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 5311 | traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow], |
| 5312 | flags=[], |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5313 | ) |
| 5314 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5315 | ExtendedContext = Context( |
Raymond Hettinger | 6ea4845 | 2004-07-03 12:26:21 +0000 | [diff] [blame] | 5316 | prec=9, rounding=ROUND_HALF_EVEN, |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 5317 | traps=[], |
| 5318 | flags=[], |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5319 | ) |
| 5320 | |
| 5321 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 5322 | ##### crud for parsing strings ############################################# |
Mark Dickinson | 6a123cb | 2008-02-24 18:12:36 +0000 | [diff] [blame] | 5323 | # |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 5324 | # Regular expression used for parsing numeric strings. Additional |
| 5325 | # comments: |
| 5326 | # |
| 5327 | # 1. Uncomment the two '\s*' lines to allow leading and/or trailing |
| 5328 | # whitespace. But note that the specification disallows whitespace in |
| 5329 | # a numeric string. |
| 5330 | # |
| 5331 | # 2. For finite numbers (not infinities and NaNs) the body of the |
| 5332 | # number between the optional sign and the optional exponent must have |
| 5333 | # at least one decimal digit, possibly after the decimal point. The |
| 5334 | # lookahead expression '(?=\d|\.\d)' checks this. |
| 5335 | # |
| 5336 | # As the flag UNICODE is not enabled here, we're explicitly avoiding any |
| 5337 | # other meaning for \d than the numbers [0-9]. |
| 5338 | |
| 5339 | import re |
| 5340 | _parser = re.compile(r""" # A numeric string consists of: |
| 5341 | # \s* |
| 5342 | (?P<sign>[-+])? # an optional sign, followed by either... |
| 5343 | ( |
| 5344 | (?=\d|\.\d) # ...a number (with at least one digit) |
| 5345 | (?P<int>\d*) # consisting of a (possibly empty) integer part |
| 5346 | (\.(?P<frac>\d*))? # followed by an optional fractional part |
| 5347 | (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or... |
| 5348 | | |
| 5349 | Inf(inity)? # ...an infinity, or... |
| 5350 | | |
| 5351 | (?P<signal>s)? # ...an (optionally signaling) |
| 5352 | NaN # NaN |
| 5353 | (?P<diag>\d*) # with (possibly empty) diagnostic information. |
| 5354 | ) |
| 5355 | # \s* |
Mark Dickinson | 59bc20b | 2008-01-12 01:56:00 +0000 | [diff] [blame] | 5356 | \Z |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 5357 | """, re.VERBOSE | re.IGNORECASE).match |
| 5358 | |
Facundo Batista | 2ec7415 | 2007-12-03 17:55:00 +0000 | [diff] [blame] | 5359 | _all_zeros = re.compile('0*$').match |
| 5360 | _exact_half = re.compile('50*$').match |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 5361 | |
| 5362 | ##### PEP3101 support functions ############################################## |
| 5363 | # The functions parse_format_specifier and format_align have little to do |
| 5364 | # with the Decimal class, and could potentially be reused for other pure |
| 5365 | # Python numeric classes that want to implement __format__ |
| 5366 | # |
| 5367 | # A format specifier for Decimal looks like: |
| 5368 | # |
| 5369 | # [[fill]align][sign][0][minimumwidth][.precision][type] |
| 5370 | # |
| 5371 | |
| 5372 | _parse_format_specifier_regex = re.compile(r"""\A |
| 5373 | (?: |
| 5374 | (?P<fill>.)? |
| 5375 | (?P<align>[<>=^]) |
| 5376 | )? |
| 5377 | (?P<sign>[-+ ])? |
| 5378 | (?P<zeropad>0)? |
| 5379 | (?P<minimumwidth>(?!0)\d+)? |
| 5380 | (?:\.(?P<precision>0|(?!0)\d+))? |
| 5381 | (?P<type>[eEfFgG%])? |
| 5382 | \Z |
| 5383 | """, re.VERBOSE) |
| 5384 | |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 5385 | del re |
| 5386 | |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 5387 | def _parse_format_specifier(format_spec): |
| 5388 | """Parse and validate a format specifier. |
| 5389 | |
| 5390 | Turns a standard numeric format specifier into a dict, with the |
| 5391 | following entries: |
| 5392 | |
| 5393 | fill: fill character to pad field to minimum width |
| 5394 | align: alignment type, either '<', '>', '=' or '^' |
| 5395 | sign: either '+', '-' or ' ' |
| 5396 | minimumwidth: nonnegative integer giving minimum width |
| 5397 | precision: nonnegative integer giving precision, or None |
| 5398 | type: one of the characters 'eEfFgG%', or None |
| 5399 | unicode: either True or False (always True for Python 3.x) |
| 5400 | |
| 5401 | """ |
| 5402 | m = _parse_format_specifier_regex.match(format_spec) |
| 5403 | if m is None: |
| 5404 | raise ValueError("Invalid format specifier: " + format_spec) |
| 5405 | |
| 5406 | # get the dictionary |
| 5407 | format_dict = m.groupdict() |
| 5408 | |
| 5409 | # defaults for fill and alignment |
| 5410 | fill = format_dict['fill'] |
| 5411 | align = format_dict['align'] |
| 5412 | if format_dict.pop('zeropad') is not None: |
| 5413 | # in the face of conflict, refuse the temptation to guess |
| 5414 | if fill is not None and fill != '0': |
| 5415 | raise ValueError("Fill character conflicts with '0'" |
| 5416 | " in format specifier: " + format_spec) |
| 5417 | if align is not None and align != '=': |
| 5418 | raise ValueError("Alignment conflicts with '0' in " |
| 5419 | "format specifier: " + format_spec) |
| 5420 | fill = '0' |
| 5421 | align = '=' |
| 5422 | format_dict['fill'] = fill or ' ' |
| 5423 | format_dict['align'] = align or '<' |
| 5424 | |
| 5425 | if format_dict['sign'] is None: |
| 5426 | format_dict['sign'] = '-' |
| 5427 | |
| 5428 | # turn minimumwidth and precision entries into integers. |
| 5429 | # minimumwidth defaults to 0; precision remains None if not given |
| 5430 | format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0') |
| 5431 | if format_dict['precision'] is not None: |
| 5432 | format_dict['precision'] = int(format_dict['precision']) |
| 5433 | |
| 5434 | # if format type is 'g' or 'G' then a precision of 0 makes little |
| 5435 | # sense; convert it to 1. Same if format type is unspecified. |
| 5436 | if format_dict['precision'] == 0: |
| 5437 | if format_dict['type'] in 'gG' or format_dict['type'] is None: |
| 5438 | format_dict['precision'] = 1 |
| 5439 | |
| 5440 | # record whether return type should be str or unicode |
| 5441 | format_dict['unicode'] = isinstance(format_spec, unicode) |
| 5442 | |
| 5443 | return format_dict |
| 5444 | |
| 5445 | def _format_align(body, spec_dict): |
| 5446 | """Given an unpadded, non-aligned numeric string, add padding and |
| 5447 | aligment to conform with the given format specifier dictionary (as |
| 5448 | output from parse_format_specifier). |
| 5449 | |
| 5450 | It's assumed that if body is negative then it starts with '-'. |
| 5451 | Any leading sign ('-' or '+') is stripped from the body before |
| 5452 | applying the alignment and padding rules, and replaced in the |
| 5453 | appropriate position. |
| 5454 | |
| 5455 | """ |
| 5456 | # figure out the sign; we only examine the first character, so if |
| 5457 | # body has leading whitespace the results may be surprising. |
| 5458 | if len(body) > 0 and body[0] in '-+': |
| 5459 | sign = body[0] |
| 5460 | body = body[1:] |
| 5461 | else: |
| 5462 | sign = '' |
| 5463 | |
| 5464 | if sign != '-': |
| 5465 | if spec_dict['sign'] in ' +': |
| 5466 | sign = spec_dict['sign'] |
| 5467 | else: |
| 5468 | sign = '' |
| 5469 | |
| 5470 | # how much extra space do we have to play with? |
| 5471 | minimumwidth = spec_dict['minimumwidth'] |
| 5472 | fill = spec_dict['fill'] |
| 5473 | padding = fill*(max(minimumwidth - (len(sign+body)), 0)) |
| 5474 | |
| 5475 | align = spec_dict['align'] |
| 5476 | if align == '<': |
| 5477 | result = padding + sign + body |
| 5478 | elif align == '>': |
| 5479 | result = sign + body + padding |
| 5480 | elif align == '=': |
| 5481 | result = sign + padding + body |
| 5482 | else: #align == '^' |
| 5483 | half = len(padding)//2 |
| 5484 | result = padding[:half] + sign + body + padding[half:] |
| 5485 | |
| 5486 | # make sure that result is unicode if necessary |
| 5487 | if spec_dict['unicode']: |
| 5488 | result = unicode(result) |
| 5489 | |
| 5490 | return result |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 5491 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 5492 | ##### Useful Constants (internal use only) ################################ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5493 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 5494 | # Reusable defaults |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5495 | Inf = Decimal('Inf') |
| 5496 | negInf = Decimal('-Inf') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 5497 | NaN = Decimal('NaN') |
| 5498 | Dec_0 = Decimal(0) |
| 5499 | Dec_p1 = Decimal(1) |
| 5500 | Dec_n1 = Decimal(-1) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5501 | |
Facundo Batista | 59c5884 | 2007-04-10 12:58:45 +0000 | [diff] [blame] | 5502 | # Infsign[sign] is infinity w/ that sign |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5503 | Infsign = (Inf, negInf) |
| 5504 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5505 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5506 | |
| 5507 | if __name__ == '__main__': |
| 5508 | import doctest, sys |
| 5509 | doctest.testmod(sys.modules[__name__]) |