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 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +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 |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +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) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +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) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +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) |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 59 | >>> print(dig / Decimal(3)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 60 | 0.333333333 |
| 61 | >>> getcontext().prec = 18 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 62 | >>> print(dig / Decimal(3)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 63 | 0.333333333333333333 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 64 | >>> print(dig.sqrt()) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 65 | 1 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 66 | >>> print(Decimal(3).sqrt()) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 67 | 1.73205080756887729 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 68 | >>> print(Decimal(3) ** 123) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 69 | 4.85192780976896427E+58 |
| 70 | >>> inf = Decimal(1) / Decimal(0) |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 71 | >>> print(inf) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 72 | Infinity |
| 73 | >>> neginf = Decimal(-1) / Decimal(0) |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 74 | >>> print(neginf) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 75 | -Infinity |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 76 | >>> print(neginf + inf) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 77 | NaN |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 78 | >>> print(neginf * inf) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 79 | -Infinity |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 80 | >>> print(dig / 0) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 81 | Infinity |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 82 | >>> getcontext().traps[DivisionByZero] = 1 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 83 | >>> print(dig / 0) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 84 | Traceback (most recent call last): |
| 85 | ... |
| 86 | ... |
| 87 | ... |
Guido van Rossum | 6a2a2a0 | 2006-08-26 20:37:44 +0000 | [diff] [blame] | 88 | decimal.DivisionByZero: x / 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 89 | >>> c = Context() |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 90 | >>> c.traps[InvalidOperation] = 0 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +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)) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 94 | Decimal('NaN') |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 95 | >>> c.traps[InvalidOperation] = 1 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +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 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 99 | >>> print(c.flags[InvalidOperation]) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 100 | 0 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 101 | >>> print(c.divide(Decimal(0), Decimal(0))) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 102 | Traceback (most recent call last): |
| 103 | ... |
| 104 | ... |
| 105 | ... |
Guido van Rossum | 6a2a2a0 | 2006-08-26 20:37:44 +0000 | [diff] [blame] | 106 | decimal.InvalidOperation: 0 / 0 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 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 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 111 | >>> print(c.divide(Decimal(0), Decimal(0))) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 112 | NaN |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +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', |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +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 |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 134 | 'setcontext', 'getcontext', 'localcontext' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 135 | ] |
| 136 | |
Guido van Rossum | a13f4a1 | 2007-12-10 20:04:04 +0000 | [diff] [blame] | 137 | import numbers as _numbers |
Raymond Hettinger | eb26084 | 2005-06-07 18:52:34 +0000 | [diff] [blame] | 138 | import copy as _copy |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 139 | |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 140 | try: |
| 141 | from collections import namedtuple as _namedtuple |
| 142 | DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent') |
| 143 | except ImportError: |
| 144 | DecimalTuple = lambda *args: args |
| 145 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 146 | # Rounding |
Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 147 | ROUND_DOWN = 'ROUND_DOWN' |
| 148 | ROUND_HALF_UP = 'ROUND_HALF_UP' |
| 149 | ROUND_HALF_EVEN = 'ROUND_HALF_EVEN' |
| 150 | ROUND_CEILING = 'ROUND_CEILING' |
| 151 | ROUND_FLOOR = 'ROUND_FLOOR' |
| 152 | ROUND_UP = 'ROUND_UP' |
| 153 | ROUND_HALF_DOWN = 'ROUND_HALF_DOWN' |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 154 | ROUND_05UP = 'ROUND_05UP' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 155 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 156 | # Errors |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 157 | |
| 158 | class DecimalException(ArithmeticError): |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 159 | """Base exception class. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 160 | |
| 161 | Used exceptions derive from this. |
| 162 | If an exception derives from another exception besides this (such as |
| 163 | Underflow (Inexact, Rounded, Subnormal) that indicates that it is only |
| 164 | called if the others are present. This isn't actually used for |
| 165 | anything, though. |
| 166 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 167 | handle -- Called when context._raise_error is called and the |
| 168 | trap_enabler is set. First argument is self, second is the |
| 169 | context. More arguments can be given, those being after |
| 170 | the explanation in _raise_error (For example, |
| 171 | context._raise_error(NewError, '(-x)!', self._sign) would |
| 172 | call NewError().handle(context, self._sign).) |
| 173 | |
| 174 | To define a new exception, it should be sufficient to have it derive |
| 175 | from DecimalException. |
| 176 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 177 | def handle(self, context, *args): |
| 178 | pass |
| 179 | |
| 180 | |
| 181 | class Clamped(DecimalException): |
| 182 | """Exponent of a 0 changed to fit bounds. |
| 183 | |
| 184 | This occurs and signals clamped if the exponent of a result has been |
| 185 | altered in order to fit the constraints of a specific concrete |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 186 | representation. This may occur when the exponent of a zero result would |
| 187 | be outside the bounds of a representation, or when a large normal |
| 188 | number would have an encoded exponent that cannot be represented. In |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 189 | this latter case, the exponent is reduced to fit and the corresponding |
| 190 | number of zero digits are appended to the coefficient ("fold-down"). |
| 191 | """ |
| 192 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 193 | class InvalidOperation(DecimalException): |
| 194 | """An invalid operation was performed. |
| 195 | |
| 196 | Various bad things cause this: |
| 197 | |
| 198 | Something creates a signaling NaN |
| 199 | -INF + INF |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 200 | 0 * (+-)INF |
| 201 | (+-)INF / (+-)INF |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 202 | x % 0 |
| 203 | (+-)INF % x |
| 204 | x._rescale( non-integer ) |
| 205 | sqrt(-x) , x > 0 |
| 206 | 0 ** 0 |
| 207 | x ** (non-integer) |
| 208 | x ** (+-)INF |
| 209 | An operand is invalid |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 210 | |
| 211 | The result of the operation after these is a quiet positive NaN, |
| 212 | except when the cause is a signaling NaN, in which case the result is |
| 213 | also a quiet NaN, but with the original sign, and an optional |
| 214 | diagnostic information. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 215 | """ |
| 216 | def handle(self, context, *args): |
| 217 | if args: |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 218 | ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True) |
| 219 | return ans._fix_nan(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 220 | return NaN |
| 221 | |
| 222 | class ConversionSyntax(InvalidOperation): |
| 223 | """Trying to convert badly formed string. |
| 224 | |
| 225 | This occurs and signals invalid-operation if an string is being |
| 226 | converted to a number and it does not conform to the numeric string |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 227 | syntax. The result is [0,qNaN]. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 228 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 229 | def handle(self, context, *args): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 230 | return NaN |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 231 | |
| 232 | class DivisionByZero(DecimalException, ZeroDivisionError): |
| 233 | """Division by 0. |
| 234 | |
| 235 | This occurs and signals division-by-zero if division of a finite number |
| 236 | by zero was attempted (during a divide-integer or divide operation, or a |
| 237 | power operation with negative right-hand operand), and the dividend was |
| 238 | not zero. |
| 239 | |
| 240 | The result of the operation is [sign,inf], where sign is the exclusive |
| 241 | or of the signs of the operands for divide, or is 1 for an odd power of |
| 242 | -0, for power. |
| 243 | """ |
| 244 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 245 | def handle(self, context, sign, *args): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 246 | return Infsign[sign] |
| 247 | |
| 248 | class DivisionImpossible(InvalidOperation): |
| 249 | """Cannot perform the division adequately. |
| 250 | |
| 251 | This occurs and signals invalid-operation if the integer result of a |
| 252 | divide-integer or remainder operation had too many digits (would be |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 253 | longer than precision). The result is [0,qNaN]. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 254 | """ |
| 255 | |
| 256 | def handle(self, context, *args): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 257 | return NaN |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 258 | |
| 259 | class DivisionUndefined(InvalidOperation, ZeroDivisionError): |
| 260 | """Undefined result of division. |
| 261 | |
| 262 | This occurs and signals invalid-operation if division by zero was |
| 263 | attempted (during a divide-integer, divide, or remainder operation), and |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 264 | the dividend is also zero. The result is [0,qNaN]. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 265 | """ |
| 266 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 267 | def handle(self, context, *args): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 268 | return NaN |
| 269 | |
| 270 | class Inexact(DecimalException): |
| 271 | """Had to round, losing information. |
| 272 | |
| 273 | This occurs and signals inexact whenever the result of an operation is |
| 274 | not exact (that is, it needed to be rounded and any discarded digits |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 275 | were non-zero), or if an overflow or underflow condition occurs. The |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 276 | result in all cases is unchanged. |
| 277 | |
| 278 | The inexact signal may be tested (or trapped) to determine if a given |
| 279 | operation (or sequence of operations) was inexact. |
| 280 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 281 | |
| 282 | class InvalidContext(InvalidOperation): |
| 283 | """Invalid context. Unknown rounding, for example. |
| 284 | |
| 285 | This occurs and signals invalid-operation if an invalid context was |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 286 | detected during an operation. This can occur if contexts are not checked |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 287 | on creation and either the precision exceeds the capability of the |
| 288 | underlying concrete representation or an unknown or unsupported rounding |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 289 | was specified. These aspects of the context need only be checked when |
| 290 | the values are required to be used. The result is [0,qNaN]. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 291 | """ |
| 292 | |
| 293 | def handle(self, context, *args): |
| 294 | return NaN |
| 295 | |
| 296 | class Rounded(DecimalException): |
| 297 | """Number got rounded (not necessarily changed during rounding). |
| 298 | |
| 299 | This occurs and signals rounded whenever the result of an operation is |
| 300 | rounded (that is, some zero or non-zero digits were discarded from the |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 301 | coefficient), or if an overflow or underflow condition occurs. The |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 302 | result in all cases is unchanged. |
| 303 | |
| 304 | The rounded signal may be tested (or trapped) to determine if a given |
| 305 | operation (or sequence of operations) caused a loss of precision. |
| 306 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 307 | |
| 308 | class Subnormal(DecimalException): |
| 309 | """Exponent < Emin before rounding. |
| 310 | |
| 311 | This occurs and signals subnormal whenever the result of a conversion or |
| 312 | operation is subnormal (that is, its adjusted exponent is less than |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 313 | Emin, before any rounding). The result in all cases is unchanged. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 314 | |
| 315 | The subnormal signal may be tested (or trapped) to determine if a given |
| 316 | or operation (or sequence of operations) yielded a subnormal result. |
| 317 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 318 | |
| 319 | class Overflow(Inexact, Rounded): |
| 320 | """Numerical overflow. |
| 321 | |
| 322 | This occurs and signals overflow if the adjusted exponent of a result |
| 323 | (from a conversion or from an operation that is not an attempt to divide |
| 324 | by zero), after rounding, would be greater than the largest value that |
| 325 | can be handled by the implementation (the value Emax). |
| 326 | |
| 327 | The result depends on the rounding mode: |
| 328 | |
| 329 | For round-half-up and round-half-even (and for round-half-down and |
| 330 | round-up, if implemented), the result of the operation is [sign,inf], |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 331 | 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] | 332 | result is the largest finite number that can be represented in the |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 333 | current precision, with the sign of the intermediate result. For |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 334 | round-ceiling, the result is the same as for round-down if the sign of |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 335 | 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] | 336 | the result is the same as for round-down if the sign of the intermediate |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 337 | 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] | 338 | will also be raised. |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 339 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 340 | |
| 341 | def handle(self, context, sign, *args): |
| 342 | if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN, |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 343 | ROUND_HALF_DOWN, ROUND_UP): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 344 | return Infsign[sign] |
| 345 | if sign == 0: |
| 346 | if context.rounding == ROUND_CEILING: |
| 347 | return Infsign[sign] |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 348 | return _dec_from_triple(sign, '9'*context.prec, |
| 349 | context.Emax-context.prec+1) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 350 | if sign == 1: |
| 351 | if context.rounding == ROUND_FLOOR: |
| 352 | return Infsign[sign] |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 353 | return _dec_from_triple(sign, '9'*context.prec, |
| 354 | context.Emax-context.prec+1) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 355 | |
| 356 | |
| 357 | class Underflow(Inexact, Rounded, Subnormal): |
| 358 | """Numerical underflow with result rounded to 0. |
| 359 | |
| 360 | This occurs and signals underflow if a result is inexact and the |
| 361 | adjusted exponent of the result would be smaller (more negative) than |
| 362 | the smallest value that can be handled by the implementation (the value |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 363 | Emin). That is, the result is both inexact and subnormal. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 364 | |
| 365 | The result after an underflow will be a subnormal number rounded, if |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 366 | 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] | 367 | in 0 with the sign of the intermediate result and an exponent of Etiny. |
| 368 | |
| 369 | In all cases, Inexact, Rounded, and Subnormal will also be raised. |
| 370 | """ |
| 371 | |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 372 | # List of public traps and flags |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 373 | _signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded, |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 374 | Underflow, InvalidOperation, Subnormal] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 375 | |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 376 | # Map conditions (per the spec) to signals |
| 377 | _condition_map = {ConversionSyntax:InvalidOperation, |
| 378 | DivisionImpossible:InvalidOperation, |
| 379 | DivisionUndefined:InvalidOperation, |
| 380 | InvalidContext:InvalidOperation} |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 381 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 382 | ##### Context Functions ################################################## |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 383 | |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 384 | # The getcontext() and setcontext() function manage access to a thread-local |
| 385 | # current context. Py2.4 offers direct support for thread locals. If that |
Georg Brandl | f992640 | 2008-06-13 06:32:25 +0000 | [diff] [blame] | 386 | # is not available, use threading.current_thread() which is slower but will |
Raymond Hettinger | 7e71fa5 | 2004-12-18 19:07:19 +0000 | [diff] [blame] | 387 | # work for older Pythons. If threads are not part of the build, create a |
| 388 | # mock threading object with threading.local() returning the module namespace. |
| 389 | |
| 390 | try: |
| 391 | import threading |
| 392 | except ImportError: |
| 393 | # Python was compiled without threads; create a mock object instead |
| 394 | import sys |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 395 | class MockThreading(object): |
Raymond Hettinger | 7e71fa5 | 2004-12-18 19:07:19 +0000 | [diff] [blame] | 396 | def local(self, sys=sys): |
| 397 | return sys.modules[__name__] |
| 398 | threading = MockThreading() |
| 399 | del sys, MockThreading |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 400 | |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 401 | try: |
| 402 | threading.local |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 403 | |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 404 | except AttributeError: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 405 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 406 | # To fix reloading, force it to create a new context |
| 407 | # Old contexts have different exceptions in their dicts, making problems. |
Georg Brandl | f992640 | 2008-06-13 06:32:25 +0000 | [diff] [blame] | 408 | if hasattr(threading.current_thread(), '__decimal_context__'): |
| 409 | del threading.current_thread().__decimal_context__ |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 410 | |
| 411 | def setcontext(context): |
| 412 | """Set this thread's context to context.""" |
| 413 | if context in (DefaultContext, BasicContext, ExtendedContext): |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 414 | context = context.copy() |
Raymond Hettinger | 61992ef | 2004-08-06 23:42:16 +0000 | [diff] [blame] | 415 | context.clear_flags() |
Georg Brandl | f992640 | 2008-06-13 06:32:25 +0000 | [diff] [blame] | 416 | threading.current_thread().__decimal_context__ = context |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 417 | |
| 418 | def getcontext(): |
| 419 | """Returns this thread's context. |
| 420 | |
| 421 | If this thread does not yet have a context, returns |
| 422 | a new context and sets this thread's context. |
| 423 | New contexts are copies of DefaultContext. |
| 424 | """ |
| 425 | try: |
Georg Brandl | f992640 | 2008-06-13 06:32:25 +0000 | [diff] [blame] | 426 | return threading.current_thread().__decimal_context__ |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 427 | except AttributeError: |
| 428 | context = Context() |
Georg Brandl | f992640 | 2008-06-13 06:32:25 +0000 | [diff] [blame] | 429 | threading.current_thread().__decimal_context__ = context |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 430 | return context |
| 431 | |
| 432 | else: |
| 433 | |
| 434 | local = threading.local() |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 435 | if hasattr(local, '__decimal_context__'): |
| 436 | del local.__decimal_context__ |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 437 | |
| 438 | def getcontext(_local=local): |
| 439 | """Returns this thread's context. |
| 440 | |
| 441 | If this thread does not yet have a context, returns |
| 442 | a new context and sets this thread's context. |
| 443 | New contexts are copies of DefaultContext. |
| 444 | """ |
| 445 | try: |
| 446 | return _local.__decimal_context__ |
| 447 | except AttributeError: |
| 448 | context = Context() |
| 449 | _local.__decimal_context__ = context |
| 450 | return context |
| 451 | |
| 452 | def setcontext(context, _local=local): |
| 453 | """Set this thread's context to context.""" |
| 454 | if context in (DefaultContext, BasicContext, ExtendedContext): |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 455 | context = context.copy() |
Raymond Hettinger | 61992ef | 2004-08-06 23:42:16 +0000 | [diff] [blame] | 456 | context.clear_flags() |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 457 | _local.__decimal_context__ = context |
| 458 | |
| 459 | del threading, local # Don't contaminate the namespace |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 460 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 461 | def localcontext(ctx=None): |
| 462 | """Return a context manager for a copy of the supplied context |
| 463 | |
| 464 | Uses a copy of the current context if no context is specified |
| 465 | The returned context manager creates a local decimal context |
| 466 | in a with statement: |
| 467 | def sin(x): |
| 468 | with localcontext() as ctx: |
| 469 | ctx.prec += 2 |
| 470 | # Rest of sin calculation algorithm |
| 471 | # uses a precision 2 greater than normal |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 472 | return +s # Convert result to normal precision |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 473 | |
| 474 | def sin(x): |
| 475 | with localcontext(ExtendedContext): |
| 476 | # Rest of sin calculation algorithm |
| 477 | # uses the Extended Context from the |
| 478 | # General Decimal Arithmetic Specification |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 479 | return +s # Convert result to normal context |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 480 | |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 481 | >>> setcontext(DefaultContext) |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 482 | >>> print(getcontext().prec) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 483 | 28 |
| 484 | >>> with localcontext(): |
| 485 | ... ctx = getcontext() |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 486 | ... ctx.prec += 2 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 487 | ... print(ctx.prec) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 488 | ... |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 489 | 30 |
| 490 | >>> with localcontext(ExtendedContext): |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 491 | ... print(getcontext().prec) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 492 | ... |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 493 | 9 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 494 | >>> print(getcontext().prec) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 495 | 28 |
| 496 | """ |
| 497 | if ctx is None: ctx = getcontext() |
| 498 | return _ContextManager(ctx) |
| 499 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 500 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 501 | ##### Decimal class ####################################################### |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 502 | |
Christian Heimes | 08976cb | 2008-03-16 00:32:36 +0000 | [diff] [blame] | 503 | class Decimal(_numbers.Real): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 504 | """Floating point class for decimal arithmetic.""" |
| 505 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 506 | __slots__ = ('_exp','_int','_sign', '_is_special') |
| 507 | # Generally, the value of the Decimal instance is given by |
| 508 | # (-1)**_sign * _int * 10**_exp |
| 509 | # Special values are signified by _is_special == True |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 510 | |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 511 | # We're immutable, so use __new__ not __init__ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 512 | def __new__(cls, value="0", context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 513 | """Create a decimal point instance. |
| 514 | |
| 515 | >>> Decimal('3.14') # string input |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 516 | Decimal('3.14') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 517 | >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 518 | Decimal('3.14') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 519 | >>> Decimal(314) # int |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 520 | Decimal('314') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 521 | >>> Decimal(Decimal(314)) # another decimal instance |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 522 | Decimal('314') |
Christian Heimes | a62da1d | 2008-01-12 19:39:10 +0000 | [diff] [blame] | 523 | >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 524 | Decimal('3.14') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 525 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 526 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 527 | # Note that the coefficient, self._int, is actually stored as |
| 528 | # a string rather than as a tuple of digits. This speeds up |
| 529 | # the "digits to integer" and "integer to digits" conversions |
| 530 | # that are used in almost every arithmetic operation on |
| 531 | # Decimals. This is an internal detail: the as_tuple function |
| 532 | # and the Decimal constructor still deal with tuples of |
| 533 | # digits. |
| 534 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 535 | self = object.__new__(cls) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 536 | |
Christian Heimes | d59c64c | 2007-11-30 19:27:20 +0000 | [diff] [blame] | 537 | # From a string |
| 538 | # REs insist on real strings, so we can too. |
| 539 | if isinstance(value, str): |
Christian Heimes | a62da1d | 2008-01-12 19:39:10 +0000 | [diff] [blame] | 540 | m = _parser(value.strip()) |
Christian Heimes | d59c64c | 2007-11-30 19:27:20 +0000 | [diff] [blame] | 541 | if m is None: |
| 542 | if context is None: |
| 543 | context = getcontext() |
| 544 | return context._raise_error(ConversionSyntax, |
| 545 | "Invalid literal for Decimal: %r" % value) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 546 | |
Christian Heimes | d59c64c | 2007-11-30 19:27:20 +0000 | [diff] [blame] | 547 | if m.group('sign') == "-": |
| 548 | self._sign = 1 |
| 549 | else: |
| 550 | self._sign = 0 |
| 551 | intpart = m.group('int') |
| 552 | if intpart is not None: |
| 553 | # finite number |
| 554 | fracpart = m.group('frac') |
| 555 | exp = int(m.group('exp') or '0') |
| 556 | if fracpart is not None: |
| 557 | self._int = (intpart+fracpart).lstrip('0') or '0' |
| 558 | self._exp = exp - len(fracpart) |
| 559 | else: |
| 560 | self._int = intpart.lstrip('0') or '0' |
| 561 | self._exp = exp |
| 562 | self._is_special = False |
| 563 | else: |
| 564 | diag = m.group('diag') |
| 565 | if diag is not None: |
| 566 | # NaN |
| 567 | self._int = diag.lstrip('0') |
| 568 | if m.group('signal'): |
| 569 | self._exp = 'N' |
| 570 | else: |
| 571 | self._exp = 'n' |
| 572 | else: |
| 573 | # infinity |
| 574 | self._int = '0' |
| 575 | self._exp = 'F' |
| 576 | self._is_special = True |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 577 | return self |
| 578 | |
| 579 | # From an integer |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 580 | if isinstance(value, int): |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 581 | if value >= 0: |
| 582 | self._sign = 0 |
| 583 | else: |
| 584 | self._sign = 1 |
| 585 | self._exp = 0 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 586 | self._int = str(abs(value)) |
Christian Heimes | d59c64c | 2007-11-30 19:27:20 +0000 | [diff] [blame] | 587 | self._is_special = False |
| 588 | return self |
| 589 | |
| 590 | # From another decimal |
| 591 | if isinstance(value, Decimal): |
| 592 | self._exp = value._exp |
| 593 | self._sign = value._sign |
| 594 | self._int = value._int |
| 595 | self._is_special = value._is_special |
| 596 | return self |
| 597 | |
| 598 | # From an internal working value |
| 599 | if isinstance(value, _WorkRep): |
| 600 | self._sign = value.sign |
| 601 | self._int = str(value.int) |
| 602 | self._exp = int(value.exp) |
| 603 | self._is_special = False |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 604 | return self |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 605 | |
| 606 | # tuple/list conversion (possibly from as_tuple()) |
| 607 | if isinstance(value, (list,tuple)): |
| 608 | if len(value) != 3: |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 609 | raise ValueError('Invalid tuple size in creation of Decimal ' |
| 610 | 'from list or tuple. The list or tuple ' |
| 611 | 'should have exactly three elements.') |
| 612 | # process sign. The isinstance test rejects floats |
| 613 | if not (isinstance(value[0], int) and value[0] in (0,1)): |
| 614 | raise ValueError("Invalid sign. The first value in the tuple " |
| 615 | "should be an integer; either 0 for a " |
| 616 | "positive number or 1 for a negative number.") |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 617 | self._sign = value[0] |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 618 | if value[2] == 'F': |
| 619 | # infinity: value[1] is ignored |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 620 | self._int = '0' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 621 | self._exp = value[2] |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 622 | self._is_special = True |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 623 | else: |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 624 | # process and validate the digits in value[1] |
| 625 | digits = [] |
| 626 | for digit in value[1]: |
| 627 | if isinstance(digit, int) and 0 <= digit <= 9: |
| 628 | # skip leading zeros |
| 629 | if digits or digit != 0: |
| 630 | digits.append(digit) |
| 631 | else: |
| 632 | raise ValueError("The second value in the tuple must " |
| 633 | "be composed of integers in the range " |
| 634 | "0 through 9.") |
| 635 | if value[2] in ('n', 'N'): |
| 636 | # NaN: digits form the diagnostic |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 637 | self._int = ''.join(map(str, digits)) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 638 | self._exp = value[2] |
| 639 | self._is_special = True |
| 640 | elif isinstance(value[2], int): |
| 641 | # finite number: digits give the coefficient |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 642 | self._int = ''.join(map(str, digits or [0])) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 643 | self._exp = value[2] |
| 644 | self._is_special = False |
| 645 | else: |
| 646 | raise ValueError("The third value in the tuple must " |
| 647 | "be an integer, or one of the " |
| 648 | "strings 'F', 'n', 'N'.") |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 649 | return self |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 650 | |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 651 | if isinstance(value, float): |
| 652 | raise TypeError("Cannot convert float to Decimal. " + |
| 653 | "First convert the float to a string") |
| 654 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 655 | raise TypeError("Cannot convert %r to Decimal" % value) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 656 | |
| 657 | def _isnan(self): |
| 658 | """Returns whether the number is not actually one. |
| 659 | |
| 660 | 0 if a number |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 661 | 1 if NaN |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 662 | 2 if sNaN |
| 663 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 664 | if self._is_special: |
| 665 | exp = self._exp |
| 666 | if exp == 'n': |
| 667 | return 1 |
| 668 | elif exp == 'N': |
| 669 | return 2 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 670 | return 0 |
| 671 | |
| 672 | def _isinfinity(self): |
| 673 | """Returns whether the number is infinite |
| 674 | |
| 675 | 0 if finite or not a number |
| 676 | 1 if +INF |
| 677 | -1 if -INF |
| 678 | """ |
| 679 | if self._exp == 'F': |
| 680 | if self._sign: |
| 681 | return -1 |
| 682 | return 1 |
| 683 | return 0 |
| 684 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 685 | def _check_nans(self, other=None, context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 686 | """Returns whether the number is not actually one. |
| 687 | |
| 688 | if self, other are sNaN, signal |
| 689 | if self, other are NaN return nan |
| 690 | return 0 |
| 691 | |
| 692 | Done before operations. |
| 693 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 694 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 695 | self_is_nan = self._isnan() |
| 696 | if other is None: |
| 697 | other_is_nan = False |
| 698 | else: |
| 699 | other_is_nan = other._isnan() |
| 700 | |
| 701 | if self_is_nan or other_is_nan: |
| 702 | if context is None: |
| 703 | context = getcontext() |
| 704 | |
| 705 | if self_is_nan == 2: |
| 706 | return context._raise_error(InvalidOperation, 'sNaN', |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 707 | self) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 708 | if other_is_nan == 2: |
| 709 | return context._raise_error(InvalidOperation, 'sNaN', |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 710 | other) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 711 | if self_is_nan: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 712 | return self._fix_nan(context) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 713 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 714 | return other._fix_nan(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 715 | return 0 |
| 716 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 717 | def _compare_check_nans(self, other, context): |
| 718 | """Version of _check_nans used for the signaling comparisons |
| 719 | compare_signal, __le__, __lt__, __ge__, __gt__. |
| 720 | |
| 721 | Signal InvalidOperation if either self or other is a (quiet |
| 722 | or signaling) NaN. Signaling NaNs take precedence over quiet |
| 723 | NaNs. |
| 724 | |
| 725 | Return 0 if neither operand is a NaN. |
| 726 | |
| 727 | """ |
| 728 | if context is None: |
| 729 | context = getcontext() |
| 730 | |
| 731 | if self._is_special or other._is_special: |
| 732 | if self.is_snan(): |
| 733 | return context._raise_error(InvalidOperation, |
| 734 | 'comparison involving sNaN', |
| 735 | self) |
| 736 | elif other.is_snan(): |
| 737 | return context._raise_error(InvalidOperation, |
| 738 | 'comparison involving sNaN', |
| 739 | other) |
| 740 | elif self.is_qnan(): |
| 741 | return context._raise_error(InvalidOperation, |
| 742 | 'comparison involving NaN', |
| 743 | self) |
| 744 | elif other.is_qnan(): |
| 745 | return context._raise_error(InvalidOperation, |
| 746 | 'comparison involving NaN', |
| 747 | other) |
| 748 | return 0 |
| 749 | |
Jack Diederich | 4dafcc4 | 2006-11-28 19:15:13 +0000 | [diff] [blame] | 750 | def __bool__(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 751 | """Return True if self is nonzero; otherwise return False. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 752 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 753 | NaNs and infinities are considered nonzero. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 754 | """ |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 755 | return self._is_special or self._int != '0' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 756 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 757 | def _cmp(self, other): |
| 758 | """Compare the two non-NaN decimal instances self and other. |
| 759 | |
| 760 | Returns -1 if self < other, 0 if self == other and 1 |
| 761 | if self > other. This routine is for internal use only.""" |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 762 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 763 | if self._is_special or other._is_special: |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 764 | return cmp(self._isinfinity(), other._isinfinity()) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 765 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 766 | # check for zeros; note that cmp(0, -0) should return 0 |
| 767 | if not self: |
| 768 | if not other: |
| 769 | return 0 |
| 770 | else: |
| 771 | return -((-1)**other._sign) |
| 772 | if not other: |
| 773 | return (-1)**self._sign |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 774 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 775 | # If different signs, neg one is less |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 776 | if other._sign < self._sign: |
| 777 | return -1 |
| 778 | if self._sign < other._sign: |
| 779 | return 1 |
| 780 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 781 | self_adjusted = self.adjusted() |
| 782 | other_adjusted = other.adjusted() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 783 | if self_adjusted == other_adjusted: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 784 | self_padded = self._int + '0'*(self._exp - other._exp) |
| 785 | other_padded = other._int + '0'*(other._exp - self._exp) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 786 | return cmp(self_padded, other_padded) * (-1)**self._sign |
| 787 | elif self_adjusted > other_adjusted: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 788 | return (-1)**self._sign |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 789 | else: # self_adjusted < other_adjusted |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 790 | return -((-1)**self._sign) |
| 791 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 792 | # Note: The Decimal standard doesn't cover rich comparisons for |
| 793 | # Decimals. In particular, the specification is silent on the |
| 794 | # subject of what should happen for a comparison involving a NaN. |
| 795 | # We take the following approach: |
| 796 | # |
| 797 | # == comparisons involving a NaN always return False |
| 798 | # != comparisons involving a NaN always return True |
| 799 | # <, >, <= and >= comparisons involving a (quiet or signaling) |
| 800 | # NaN signal InvalidOperation, and return False if the |
Christian Heimes | 3feef61 | 2008-02-11 06:19:17 +0000 | [diff] [blame] | 801 | # InvalidOperation is not trapped. |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 802 | # |
| 803 | # This behavior is designed to conform as closely as possible to |
| 804 | # that specified by IEEE 754. |
| 805 | |
Raymond Hettinger | 0aeac10 | 2004-07-05 22:53:03 +0000 | [diff] [blame] | 806 | def __eq__(self, other): |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 807 | other = _convert_other(other) |
| 808 | if other is NotImplemented: |
| 809 | return other |
| 810 | if self.is_nan() or other.is_nan(): |
| 811 | return False |
| 812 | return self._cmp(other) == 0 |
Raymond Hettinger | 0aeac10 | 2004-07-05 22:53:03 +0000 | [diff] [blame] | 813 | |
| 814 | def __ne__(self, other): |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 815 | other = _convert_other(other) |
| 816 | if other is NotImplemented: |
| 817 | return other |
| 818 | if self.is_nan() or other.is_nan(): |
| 819 | return True |
| 820 | return self._cmp(other) != 0 |
Raymond Hettinger | 0aeac10 | 2004-07-05 22:53:03 +0000 | [diff] [blame] | 821 | |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 822 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 823 | def __lt__(self, other, context=None): |
| 824 | other = _convert_other(other) |
| 825 | if other is NotImplemented: |
| 826 | return other |
| 827 | ans = self._compare_check_nans(other, context) |
| 828 | if ans: |
| 829 | return False |
| 830 | return self._cmp(other) < 0 |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 831 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 832 | def __le__(self, other, context=None): |
| 833 | other = _convert_other(other) |
| 834 | if other is NotImplemented: |
| 835 | return other |
| 836 | ans = self._compare_check_nans(other, context) |
| 837 | if ans: |
| 838 | return False |
| 839 | return self._cmp(other) <= 0 |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 840 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 841 | def __gt__(self, other, context=None): |
| 842 | other = _convert_other(other) |
| 843 | if other is NotImplemented: |
| 844 | return other |
| 845 | ans = self._compare_check_nans(other, context) |
| 846 | if ans: |
| 847 | return False |
| 848 | return self._cmp(other) > 0 |
| 849 | |
| 850 | def __ge__(self, other, context=None): |
| 851 | other = _convert_other(other) |
| 852 | if other is NotImplemented: |
| 853 | return other |
| 854 | ans = self._compare_check_nans(other, context) |
| 855 | if ans: |
| 856 | return False |
| 857 | return self._cmp(other) >= 0 |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 858 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 859 | def compare(self, other, context=None): |
| 860 | """Compares one to another. |
| 861 | |
| 862 | -1 => a < b |
| 863 | 0 => a = b |
| 864 | 1 => a > b |
| 865 | NaN => one is NaN |
| 866 | Like __cmp__, but returns Decimal instances. |
| 867 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 868 | other = _convert_other(other, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 869 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 870 | # Compare(NaN, NaN) = NaN |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 871 | if (self._is_special or other and other._is_special): |
| 872 | ans = self._check_nans(other, context) |
| 873 | if ans: |
| 874 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 875 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 876 | return Decimal(self._cmp(other)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 877 | |
| 878 | def __hash__(self): |
| 879 | """x.__hash__() <==> hash(x)""" |
| 880 | # Decimal integers must hash the same as the ints |
Christian Heimes | 2380ac7 | 2008-01-09 00:17:24 +0000 | [diff] [blame] | 881 | # |
| 882 | # The hash of a nonspecial noninteger Decimal must depend only |
| 883 | # on the value of that Decimal, and not on its representation. |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 884 | # For example: hash(Decimal('100E-1')) == hash(Decimal('10')). |
Raymond Hettinger | bea3f6f | 2005-03-15 04:59:17 +0000 | [diff] [blame] | 885 | if self._is_special: |
| 886 | if self._isnan(): |
| 887 | raise TypeError('Cannot hash a NaN value.') |
| 888 | return hash(str(self)) |
Thomas Wouters | 8ce81f7 | 2007-09-20 18:22:40 +0000 | [diff] [blame] | 889 | if not self: |
| 890 | return 0 |
| 891 | if self._isinteger(): |
| 892 | op = _WorkRep(self.to_integral_value()) |
| 893 | # to make computation feasible for Decimals with large |
| 894 | # exponent, we use the fact that hash(n) == hash(m) for |
| 895 | # any two nonzero integers n and m such that (i) n and m |
| 896 | # have the same sign, and (ii) n is congruent to m modulo |
| 897 | # 2**64-1. So we can replace hash((-1)**s*c*10**e) with |
| 898 | # hash((-1)**s*c*pow(10, e, 2**64-1). |
| 899 | return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1)) |
Christian Heimes | 2380ac7 | 2008-01-09 00:17:24 +0000 | [diff] [blame] | 900 | # The value of a nonzero nonspecial Decimal instance is |
| 901 | # faithfully represented by the triple consisting of its sign, |
| 902 | # its adjusted exponent, and its coefficient with trailing |
| 903 | # zeros removed. |
| 904 | return hash((self._sign, |
| 905 | self._exp+len(self._int), |
| 906 | self._int.rstrip('0'))) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 907 | |
| 908 | def as_tuple(self): |
| 909 | """Represents the number as a triple tuple. |
| 910 | |
| 911 | To show the internals exactly as they are. |
| 912 | """ |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 913 | return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 914 | |
| 915 | def __repr__(self): |
| 916 | """Represents the number as an instance of Decimal.""" |
| 917 | # Invariant: eval(repr(d)) == d |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 918 | return "Decimal('%s')" % str(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 919 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 920 | def __str__(self, eng=False, context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 921 | """Return string representation of the number in scientific notation. |
| 922 | |
| 923 | Captures all of the information in the underlying representation. |
| 924 | """ |
| 925 | |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 926 | sign = ['', '-'][self._sign] |
Raymond Hettinger | e5a0a96 | 2005-06-20 09:49:42 +0000 | [diff] [blame] | 927 | if self._is_special: |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 928 | if self._exp == 'F': |
| 929 | return sign + 'Infinity' |
| 930 | elif self._exp == 'n': |
| 931 | return sign + 'NaN' + self._int |
| 932 | else: # self._exp == 'N' |
| 933 | return sign + 'sNaN' + self._int |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 934 | |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 935 | # number of digits of self._int to left of decimal point |
| 936 | leftdigits = self._exp + len(self._int) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 937 | |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 938 | # dotplace is number of digits of self._int to the left of the |
| 939 | # decimal point in the mantissa of the output string (that is, |
| 940 | # after adjusting the exponent) |
| 941 | if self._exp <= 0 and leftdigits > -6: |
| 942 | # no exponent required |
| 943 | dotplace = leftdigits |
| 944 | elif not eng: |
| 945 | # usual scientific notation: 1 digit on left of the point |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 946 | dotplace = 1 |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 947 | elif self._int == '0': |
| 948 | # engineering notation, zero |
| 949 | dotplace = (leftdigits + 1) % 3 - 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 950 | else: |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 951 | # engineering notation, nonzero |
| 952 | dotplace = (leftdigits - 1) % 3 + 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 953 | |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 954 | if dotplace <= 0: |
| 955 | intpart = '0' |
| 956 | fracpart = '.' + '0'*(-dotplace) + self._int |
| 957 | elif dotplace >= len(self._int): |
| 958 | intpart = self._int+'0'*(dotplace-len(self._int)) |
| 959 | fracpart = '' |
| 960 | else: |
| 961 | intpart = self._int[:dotplace] |
| 962 | fracpart = '.' + self._int[dotplace:] |
| 963 | if leftdigits == dotplace: |
| 964 | exp = '' |
| 965 | else: |
| 966 | if context is None: |
| 967 | context = getcontext() |
| 968 | exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace) |
| 969 | |
| 970 | return sign + intpart + fracpart + exp |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 971 | |
| 972 | def to_eng_string(self, context=None): |
| 973 | """Convert to engineering-type string. |
| 974 | |
| 975 | Engineering notation has an exponent which is a multiple of 3, so there |
| 976 | are up to 3 digits left of the decimal place. |
| 977 | |
| 978 | Same rules for when in exponential and when as a value as in __str__. |
| 979 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 980 | return self.__str__(eng=True, context=context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 981 | |
| 982 | def __neg__(self, context=None): |
| 983 | """Returns a copy with the sign switched. |
| 984 | |
| 985 | Rounds, if it has reason. |
| 986 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 987 | if self._is_special: |
| 988 | ans = self._check_nans(context=context) |
| 989 | if ans: |
| 990 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 991 | |
| 992 | if not self: |
| 993 | # -Decimal('0') is Decimal('0'), not Decimal('-0') |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 994 | ans = self.copy_abs() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 995 | else: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 996 | ans = self.copy_negate() |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 997 | |
| 998 | if context is None: |
| 999 | context = getcontext() |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1000 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1001 | |
| 1002 | def __pos__(self, context=None): |
| 1003 | """Returns a copy, unless it is a sNaN. |
| 1004 | |
| 1005 | Rounds the number (if more then precision digits) |
| 1006 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1007 | if self._is_special: |
| 1008 | ans = self._check_nans(context=context) |
| 1009 | if ans: |
| 1010 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1011 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1012 | if not self: |
| 1013 | # + (-0) = 0 |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 1014 | ans = self.copy_abs() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1015 | else: |
| 1016 | ans = Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1017 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1018 | if context is None: |
| 1019 | context = getcontext() |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1020 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1021 | |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1022 | def __abs__(self, round=True, context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1023 | """Returns the absolute value of self. |
| 1024 | |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1025 | If the keyword argument 'round' is false, do not round. The |
| 1026 | expression self.__abs__(round=False) is equivalent to |
| 1027 | self.copy_abs(). |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1028 | """ |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1029 | if not round: |
| 1030 | return self.copy_abs() |
| 1031 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1032 | if self._is_special: |
| 1033 | ans = self._check_nans(context=context) |
| 1034 | if ans: |
| 1035 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1036 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1037 | if self._sign: |
| 1038 | ans = self.__neg__(context=context) |
| 1039 | else: |
| 1040 | ans = self.__pos__(context=context) |
| 1041 | |
| 1042 | return ans |
| 1043 | |
| 1044 | def __add__(self, other, context=None): |
| 1045 | """Returns self + other. |
| 1046 | |
| 1047 | -INF + INF (or the reverse) cause InvalidOperation errors. |
| 1048 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1049 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1050 | if other is NotImplemented: |
| 1051 | return other |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1052 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1053 | if context is None: |
| 1054 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1055 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1056 | if self._is_special or other._is_special: |
| 1057 | ans = self._check_nans(other, context) |
| 1058 | if ans: |
| 1059 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1060 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1061 | if self._isinfinity(): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1062 | # If both INF, same sign => same as both, opposite => error. |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1063 | if self._sign != other._sign and other._isinfinity(): |
| 1064 | return context._raise_error(InvalidOperation, '-INF + INF') |
| 1065 | return Decimal(self) |
| 1066 | if other._isinfinity(): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1067 | return Decimal(other) # Can't both be infinity here |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1068 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1069 | exp = min(self._exp, other._exp) |
| 1070 | negativezero = 0 |
| 1071 | if context.rounding == ROUND_FLOOR and self._sign != other._sign: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1072 | # 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] | 1073 | negativezero = 1 |
| 1074 | |
| 1075 | if not self and not other: |
| 1076 | sign = min(self._sign, other._sign) |
| 1077 | if negativezero: |
| 1078 | sign = 1 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1079 | ans = _dec_from_triple(sign, '0', exp) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1080 | ans = ans._fix(context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1081 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1082 | if not self: |
Facundo Batista | 99b5548 | 2004-10-26 23:38:46 +0000 | [diff] [blame] | 1083 | exp = max(exp, other._exp - context.prec-1) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1084 | ans = other._rescale(exp, context.rounding) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1085 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1086 | return ans |
| 1087 | if not other: |
Facundo Batista | 99b5548 | 2004-10-26 23:38:46 +0000 | [diff] [blame] | 1088 | exp = max(exp, self._exp - context.prec-1) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1089 | ans = self._rescale(exp, context.rounding) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1090 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1091 | return ans |
| 1092 | |
| 1093 | op1 = _WorkRep(self) |
| 1094 | op2 = _WorkRep(other) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1095 | op1, op2 = _normalize(op1, op2, context.prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1096 | |
| 1097 | result = _WorkRep() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1098 | if op1.sign != op2.sign: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1099 | # Equal and opposite |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1100 | if op1.int == op2.int: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1101 | ans = _dec_from_triple(negativezero, '0', exp) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1102 | ans = ans._fix(context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1103 | return ans |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1104 | if op1.int < op2.int: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1105 | op1, op2 = op2, op1 |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1106 | # OK, now abs(op1) > abs(op2) |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1107 | if op1.sign == 1: |
| 1108 | result.sign = 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1109 | op1.sign, op2.sign = op2.sign, op1.sign |
| 1110 | else: |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1111 | result.sign = 0 |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1112 | # So we know the sign, and op1 > 0. |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1113 | elif op1.sign == 1: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1114 | result.sign = 1 |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1115 | op1.sign, op2.sign = (0, 0) |
| 1116 | else: |
| 1117 | result.sign = 0 |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1118 | # Now, op1 > abs(op2) > 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1119 | |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1120 | if op2.sign == 0: |
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 | else: |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1123 | result.int = op1.int - op2.int |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1124 | |
| 1125 | result.exp = op1.exp |
| 1126 | ans = Decimal(result) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1127 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1128 | return ans |
| 1129 | |
| 1130 | __radd__ = __add__ |
| 1131 | |
| 1132 | def __sub__(self, other, context=None): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1133 | """Return self - other""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1134 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1135 | if other is NotImplemented: |
| 1136 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1137 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1138 | if self._is_special or other._is_special: |
| 1139 | ans = self._check_nans(other, context=context) |
| 1140 | if ans: |
| 1141 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1142 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1143 | # self - other is computed as self + other.copy_negate() |
| 1144 | return self.__add__(other.copy_negate(), context=context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1145 | |
| 1146 | def __rsub__(self, other, context=None): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1147 | """Return other - self""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1148 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1149 | if other is NotImplemented: |
| 1150 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1151 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1152 | return other.__sub__(self, context=context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1153 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1154 | def __mul__(self, other, context=None): |
| 1155 | """Return self * other. |
| 1156 | |
| 1157 | (+-) INF * 0 (or its reverse) raise InvalidOperation. |
| 1158 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1159 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1160 | if other is NotImplemented: |
| 1161 | return other |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1162 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1163 | if context is None: |
| 1164 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1165 | |
Raymond Hettinger | d87ac8f | 2004-07-09 10:52:54 +0000 | [diff] [blame] | 1166 | resultsign = self._sign ^ other._sign |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1167 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1168 | if self._is_special or other._is_special: |
| 1169 | ans = self._check_nans(other, context) |
| 1170 | if ans: |
| 1171 | return ans |
| 1172 | |
| 1173 | if self._isinfinity(): |
| 1174 | if not other: |
| 1175 | return context._raise_error(InvalidOperation, '(+-)INF * 0') |
| 1176 | return Infsign[resultsign] |
| 1177 | |
| 1178 | if other._isinfinity(): |
| 1179 | if not self: |
| 1180 | return context._raise_error(InvalidOperation, '0 * (+-)INF') |
| 1181 | return Infsign[resultsign] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1182 | |
| 1183 | resultexp = self._exp + other._exp |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1184 | |
| 1185 | # Special case for multiplying by zero |
| 1186 | if not self or not other: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1187 | ans = _dec_from_triple(resultsign, '0', resultexp) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1188 | # Fixing in case the exponent is out of bounds |
| 1189 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1190 | return ans |
| 1191 | |
| 1192 | # Special case for multiplying by power of 10 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1193 | if self._int == '1': |
| 1194 | ans = _dec_from_triple(resultsign, other._int, resultexp) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1195 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1196 | return ans |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1197 | if other._int == '1': |
| 1198 | ans = _dec_from_triple(resultsign, self._int, resultexp) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1199 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1200 | return ans |
| 1201 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1202 | op1 = _WorkRep(self) |
| 1203 | op2 = _WorkRep(other) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1204 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1205 | ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1206 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1207 | |
| 1208 | return ans |
| 1209 | __rmul__ = __mul__ |
| 1210 | |
Neal Norwitz | bcc0db8 | 2006-03-24 08:14:36 +0000 | [diff] [blame] | 1211 | def __truediv__(self, other, context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1212 | """Return self / other.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1213 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1214 | if other is NotImplemented: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1215 | return NotImplemented |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1216 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1217 | if context is None: |
| 1218 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1219 | |
Raymond Hettinger | d87ac8f | 2004-07-09 10:52:54 +0000 | [diff] [blame] | 1220 | sign = self._sign ^ other._sign |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1221 | |
| 1222 | if self._is_special or other._is_special: |
| 1223 | ans = self._check_nans(other, context) |
| 1224 | if ans: |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1225 | return ans |
| 1226 | |
| 1227 | if self._isinfinity() and other._isinfinity(): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1228 | return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1229 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1230 | if self._isinfinity(): |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1231 | return Infsign[sign] |
| 1232 | |
| 1233 | if other._isinfinity(): |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1234 | context._raise_error(Clamped, 'Division by infinity') |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1235 | return _dec_from_triple(sign, '0', context.Etiny()) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1236 | |
| 1237 | # Special cases for zeroes |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1238 | if not other: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1239 | if not self: |
| 1240 | return context._raise_error(DivisionUndefined, '0 / 0') |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1241 | return context._raise_error(DivisionByZero, 'x / 0', sign) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1242 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1243 | if not self: |
| 1244 | exp = self._exp - other._exp |
| 1245 | coeff = 0 |
| 1246 | else: |
| 1247 | # OK, so neither = 0, INF or NaN |
| 1248 | shift = len(other._int) - len(self._int) + context.prec + 1 |
| 1249 | exp = self._exp - other._exp - shift |
| 1250 | op1 = _WorkRep(self) |
| 1251 | op2 = _WorkRep(other) |
| 1252 | if shift >= 0: |
| 1253 | coeff, remainder = divmod(op1.int * 10**shift, op2.int) |
| 1254 | else: |
| 1255 | coeff, remainder = divmod(op1.int, op2.int * 10**-shift) |
| 1256 | if remainder: |
| 1257 | # result is not exact; adjust to ensure correct rounding |
| 1258 | if coeff % 5 == 0: |
| 1259 | coeff += 1 |
| 1260 | else: |
| 1261 | # result is exact; get as close to ideal exponent as possible |
| 1262 | ideal_exp = self._exp - other._exp |
| 1263 | while exp < ideal_exp and coeff % 10 == 0: |
| 1264 | coeff //= 10 |
| 1265 | exp += 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1266 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1267 | ans = _dec_from_triple(sign, str(coeff), exp) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1268 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1269 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1270 | def _divide(self, other, context): |
| 1271 | """Return (self // other, self % other), to context.prec precision. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1272 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1273 | Assumes that neither self nor other is a NaN, that self is not |
| 1274 | infinite and that other is nonzero. |
| 1275 | """ |
| 1276 | sign = self._sign ^ other._sign |
| 1277 | if other._isinfinity(): |
| 1278 | ideal_exp = self._exp |
| 1279 | else: |
| 1280 | ideal_exp = min(self._exp, other._exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1281 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1282 | expdiff = self.adjusted() - other.adjusted() |
| 1283 | if not self or other._isinfinity() or expdiff <= -2: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1284 | return (_dec_from_triple(sign, '0', 0), |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1285 | self._rescale(ideal_exp, context.rounding)) |
| 1286 | if expdiff <= context.prec: |
| 1287 | op1 = _WorkRep(self) |
| 1288 | op2 = _WorkRep(other) |
| 1289 | if op1.exp >= op2.exp: |
| 1290 | op1.int *= 10**(op1.exp - op2.exp) |
| 1291 | else: |
| 1292 | op2.int *= 10**(op2.exp - op1.exp) |
| 1293 | q, r = divmod(op1.int, op2.int) |
| 1294 | if q < 10**context.prec: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1295 | return (_dec_from_triple(sign, str(q), 0), |
| 1296 | _dec_from_triple(self._sign, str(r), ideal_exp)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1297 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1298 | # Here the quotient is too large to be representable |
| 1299 | ans = context._raise_error(DivisionImpossible, |
| 1300 | 'quotient too large in //, % or divmod') |
| 1301 | return ans, ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1302 | |
Neal Norwitz | bcc0db8 | 2006-03-24 08:14:36 +0000 | [diff] [blame] | 1303 | def __rtruediv__(self, other, context=None): |
| 1304 | """Swaps self/other and returns __truediv__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1305 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1306 | if other is NotImplemented: |
| 1307 | return other |
Neal Norwitz | bcc0db8 | 2006-03-24 08:14:36 +0000 | [diff] [blame] | 1308 | return other.__truediv__(self, context=context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1309 | |
| 1310 | def __divmod__(self, other, context=None): |
| 1311 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1312 | Return (self // other, self % other) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1313 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1314 | other = _convert_other(other) |
| 1315 | if other is NotImplemented: |
| 1316 | return other |
| 1317 | |
| 1318 | if context is None: |
| 1319 | context = getcontext() |
| 1320 | |
| 1321 | ans = self._check_nans(other, context) |
| 1322 | if ans: |
| 1323 | return (ans, ans) |
| 1324 | |
| 1325 | sign = self._sign ^ other._sign |
| 1326 | if self._isinfinity(): |
| 1327 | if other._isinfinity(): |
| 1328 | ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)') |
| 1329 | return ans, ans |
| 1330 | else: |
| 1331 | return (Infsign[sign], |
| 1332 | context._raise_error(InvalidOperation, 'INF % x')) |
| 1333 | |
| 1334 | if not other: |
| 1335 | if not self: |
| 1336 | ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)') |
| 1337 | return ans, ans |
| 1338 | else: |
| 1339 | return (context._raise_error(DivisionByZero, 'x // 0', sign), |
| 1340 | context._raise_error(InvalidOperation, 'x % 0')) |
| 1341 | |
| 1342 | quotient, remainder = self._divide(other, context) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1343 | remainder = remainder._fix(context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1344 | return quotient, remainder |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1345 | |
| 1346 | def __rdivmod__(self, other, context=None): |
| 1347 | """Swaps self/other and returns __divmod__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1348 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1349 | if other is NotImplemented: |
| 1350 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1351 | return other.__divmod__(self, context=context) |
| 1352 | |
| 1353 | def __mod__(self, other, context=None): |
| 1354 | """ |
| 1355 | self % other |
| 1356 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1357 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1358 | if other is NotImplemented: |
| 1359 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1360 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1361 | if context is None: |
| 1362 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1363 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1364 | ans = self._check_nans(other, context) |
| 1365 | if ans: |
| 1366 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1367 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1368 | if self._isinfinity(): |
| 1369 | return context._raise_error(InvalidOperation, 'INF % x') |
| 1370 | elif not other: |
| 1371 | if self: |
| 1372 | return context._raise_error(InvalidOperation, 'x % 0') |
| 1373 | else: |
| 1374 | return context._raise_error(DivisionUndefined, '0 % 0') |
| 1375 | |
| 1376 | remainder = self._divide(other, context)[1] |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1377 | remainder = remainder._fix(context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1378 | return remainder |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1379 | |
| 1380 | def __rmod__(self, other, context=None): |
| 1381 | """Swaps self/other and returns __mod__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1382 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1383 | if other is NotImplemented: |
| 1384 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1385 | return other.__mod__(self, context=context) |
| 1386 | |
| 1387 | def remainder_near(self, other, context=None): |
| 1388 | """ |
| 1389 | Remainder nearest to 0- abs(remainder-near) <= other/2 |
| 1390 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1391 | if context is None: |
| 1392 | context = getcontext() |
| 1393 | |
| 1394 | other = _convert_other(other, raiseit=True) |
| 1395 | |
| 1396 | ans = self._check_nans(other, context) |
| 1397 | if ans: |
| 1398 | return ans |
| 1399 | |
| 1400 | # self == +/-infinity -> InvalidOperation |
| 1401 | if self._isinfinity(): |
| 1402 | return context._raise_error(InvalidOperation, |
| 1403 | 'remainder_near(infinity, x)') |
| 1404 | |
| 1405 | # other == 0 -> either InvalidOperation or DivisionUndefined |
| 1406 | if not other: |
| 1407 | if self: |
| 1408 | return context._raise_error(InvalidOperation, |
| 1409 | 'remainder_near(x, 0)') |
| 1410 | else: |
| 1411 | return context._raise_error(DivisionUndefined, |
| 1412 | 'remainder_near(0, 0)') |
| 1413 | |
| 1414 | # other = +/-infinity -> remainder = self |
| 1415 | if other._isinfinity(): |
| 1416 | ans = Decimal(self) |
| 1417 | return ans._fix(context) |
| 1418 | |
| 1419 | # self = 0 -> remainder = self, with ideal exponent |
| 1420 | ideal_exponent = min(self._exp, other._exp) |
| 1421 | if not self: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1422 | ans = _dec_from_triple(self._sign, '0', ideal_exponent) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1423 | return ans._fix(context) |
| 1424 | |
| 1425 | # catch most cases of large or small quotient |
| 1426 | expdiff = self.adjusted() - other.adjusted() |
| 1427 | if expdiff >= context.prec + 1: |
| 1428 | # expdiff >= prec+1 => abs(self/other) > 10**prec |
| 1429 | return context._raise_error(DivisionImpossible) |
| 1430 | if expdiff <= -2: |
| 1431 | # expdiff <= -2 => abs(self/other) < 0.1 |
| 1432 | ans = self._rescale(ideal_exponent, context.rounding) |
| 1433 | return ans._fix(context) |
| 1434 | |
| 1435 | # adjust both arguments to have the same exponent, then divide |
| 1436 | op1 = _WorkRep(self) |
| 1437 | op2 = _WorkRep(other) |
| 1438 | if op1.exp >= op2.exp: |
| 1439 | op1.int *= 10**(op1.exp - op2.exp) |
| 1440 | else: |
| 1441 | op2.int *= 10**(op2.exp - op1.exp) |
| 1442 | q, r = divmod(op1.int, op2.int) |
| 1443 | # remainder is r*10**ideal_exponent; other is +/-op2.int * |
| 1444 | # 10**ideal_exponent. Apply correction to ensure that |
| 1445 | # abs(remainder) <= abs(other)/2 |
| 1446 | if 2*r + (q&1) > op2.int: |
| 1447 | r -= op2.int |
| 1448 | q += 1 |
| 1449 | |
| 1450 | if q >= 10**context.prec: |
| 1451 | return context._raise_error(DivisionImpossible) |
| 1452 | |
| 1453 | # result has same sign as self unless r is negative |
| 1454 | sign = self._sign |
| 1455 | if r < 0: |
| 1456 | sign = 1-sign |
| 1457 | r = -r |
| 1458 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1459 | ans = _dec_from_triple(sign, str(r), ideal_exponent) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1460 | return ans._fix(context) |
| 1461 | |
| 1462 | def __floordiv__(self, other, context=None): |
| 1463 | """self // other""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1464 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1465 | if other is NotImplemented: |
| 1466 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1467 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1468 | if context is None: |
| 1469 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1470 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1471 | ans = self._check_nans(other, context) |
| 1472 | if ans: |
| 1473 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1474 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1475 | if self._isinfinity(): |
| 1476 | if other._isinfinity(): |
| 1477 | return context._raise_error(InvalidOperation, 'INF // INF') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1478 | else: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1479 | return Infsign[self._sign ^ other._sign] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1480 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1481 | if not other: |
| 1482 | if self: |
| 1483 | return context._raise_error(DivisionByZero, 'x // 0', |
| 1484 | self._sign ^ other._sign) |
| 1485 | else: |
| 1486 | return context._raise_error(DivisionUndefined, '0 // 0') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1487 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1488 | return self._divide(other, context)[0] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1489 | |
| 1490 | def __rfloordiv__(self, other, context=None): |
| 1491 | """Swaps self/other and returns __floordiv__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1492 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1493 | if other is NotImplemented: |
| 1494 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1495 | return other.__floordiv__(self, context=context) |
| 1496 | |
| 1497 | def __float__(self): |
| 1498 | """Float representation.""" |
| 1499 | return float(str(self)) |
| 1500 | |
| 1501 | def __int__(self): |
Brett Cannon | 46b0802 | 2005-03-01 03:12:26 +0000 | [diff] [blame] | 1502 | """Converts self to an int, truncating if necessary.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1503 | if self._is_special: |
| 1504 | if self._isnan(): |
| 1505 | context = getcontext() |
| 1506 | return context._raise_error(InvalidContext) |
| 1507 | elif self._isinfinity(): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1508 | raise OverflowError("Cannot convert infinity to int") |
| 1509 | s = (-1)**self._sign |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1510 | if self._exp >= 0: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1511 | return s*int(self._int)*10**self._exp |
Raymond Hettinger | 605ed02 | 2004-11-24 07:28:48 +0000 | [diff] [blame] | 1512 | else: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1513 | return s*int(self._int[:self._exp] or '0') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1514 | |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 1515 | __trunc__ = __int__ |
| 1516 | |
Christian Heimes | 0bd4e11 | 2008-02-12 22:59:25 +0000 | [diff] [blame] | 1517 | @property |
| 1518 | def real(self): |
| 1519 | return self |
| 1520 | |
| 1521 | @property |
| 1522 | def imag(self): |
| 1523 | return Decimal(0) |
| 1524 | |
| 1525 | def conjugate(self): |
| 1526 | return self |
| 1527 | |
| 1528 | def __complex__(self): |
| 1529 | return complex(float(self)) |
| 1530 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1531 | def _fix_nan(self, context): |
| 1532 | """Decapitate the payload of a NaN to fit the context""" |
| 1533 | payload = self._int |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1534 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1535 | # maximum length of payload is precision if _clamp=0, |
| 1536 | # precision-1 if _clamp=1. |
| 1537 | max_payload_len = context.prec - context._clamp |
| 1538 | if len(payload) > max_payload_len: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1539 | payload = payload[len(payload)-max_payload_len:].lstrip('0') |
| 1540 | return _dec_from_triple(self._sign, payload, self._exp, True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1541 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1542 | |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1543 | def _fix(self, context): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1544 | """Round if it is necessary to keep self within prec precision. |
| 1545 | |
| 1546 | Rounds and fixes the exponent. Does not raise on a sNaN. |
| 1547 | |
| 1548 | Arguments: |
| 1549 | self - Decimal instance |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1550 | context - context used. |
| 1551 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1552 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1553 | if self._is_special: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1554 | if self._isnan(): |
| 1555 | # decapitate payload if necessary |
| 1556 | return self._fix_nan(context) |
| 1557 | else: |
| 1558 | # self is +/-Infinity; return unaltered |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1559 | return Decimal(self) |
| 1560 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1561 | # if self is zero then exponent should be between Etiny and |
| 1562 | # Emax if _clamp==0, and between Etiny and Etop if _clamp==1. |
| 1563 | Etiny = context.Etiny() |
| 1564 | Etop = context.Etop() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1565 | if not self: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1566 | exp_max = [context.Emax, Etop][context._clamp] |
| 1567 | new_exp = min(max(self._exp, Etiny), exp_max) |
| 1568 | if new_exp != self._exp: |
| 1569 | context._raise_error(Clamped) |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1570 | return _dec_from_triple(self._sign, '0', new_exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1571 | else: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1572 | return Decimal(self) |
| 1573 | |
| 1574 | # exp_min is the smallest allowable exponent of the result, |
| 1575 | # equal to max(self.adjusted()-context.prec+1, Etiny) |
| 1576 | exp_min = len(self._int) + self._exp - context.prec |
| 1577 | if exp_min > Etop: |
| 1578 | # overflow: exp_min > Etop iff self.adjusted() > Emax |
| 1579 | context._raise_error(Inexact) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1580 | context._raise_error(Rounded) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1581 | return context._raise_error(Overflow, 'above Emax', self._sign) |
| 1582 | self_is_subnormal = exp_min < Etiny |
| 1583 | if self_is_subnormal: |
| 1584 | context._raise_error(Subnormal) |
| 1585 | exp_min = Etiny |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1586 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1587 | # round if self has too many digits |
| 1588 | if self._exp < exp_min: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1589 | context._raise_error(Rounded) |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1590 | digits = len(self._int) + self._exp - exp_min |
| 1591 | if digits < 0: |
| 1592 | self = _dec_from_triple(self._sign, '1', exp_min-1) |
| 1593 | digits = 0 |
| 1594 | this_function = getattr(self, self._pick_rounding_function[context.rounding]) |
| 1595 | changed = this_function(digits) |
| 1596 | coeff = self._int[:digits] or '0' |
| 1597 | if changed == 1: |
| 1598 | coeff = str(int(coeff)+1) |
| 1599 | ans = _dec_from_triple(self._sign, coeff, exp_min) |
| 1600 | |
| 1601 | if changed: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1602 | context._raise_error(Inexact) |
| 1603 | if self_is_subnormal: |
| 1604 | context._raise_error(Underflow) |
| 1605 | if not ans: |
| 1606 | # raise Clamped on underflow to 0 |
| 1607 | context._raise_error(Clamped) |
| 1608 | elif len(ans._int) == context.prec+1: |
| 1609 | # we get here only if rescaling rounds the |
| 1610 | # cofficient up to exactly 10**context.prec |
| 1611 | if ans._exp < Etop: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1612 | ans = _dec_from_triple(ans._sign, |
| 1613 | ans._int[:-1], ans._exp+1) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1614 | else: |
| 1615 | # Inexact and Rounded have already been raised |
| 1616 | ans = context._raise_error(Overflow, 'above Emax', |
| 1617 | self._sign) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1618 | return ans |
| 1619 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1620 | # fold down if _clamp == 1 and self has too few digits |
| 1621 | if context._clamp == 1 and self._exp > Etop: |
| 1622 | context._raise_error(Clamped) |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1623 | self_padded = self._int + '0'*(self._exp - Etop) |
| 1624 | return _dec_from_triple(self._sign, self_padded, Etop) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1625 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1626 | # here self was representable to begin with; return unchanged |
| 1627 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1628 | |
| 1629 | _pick_rounding_function = {} |
| 1630 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1631 | # for each of the rounding functions below: |
| 1632 | # self is a finite, nonzero Decimal |
| 1633 | # prec is an integer satisfying 0 <= prec < len(self._int) |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1634 | # |
| 1635 | # each function returns either -1, 0, or 1, as follows: |
| 1636 | # 1 indicates that self should be rounded up (away from zero) |
| 1637 | # 0 indicates that self should be truncated, and that all the |
| 1638 | # digits to be truncated are zeros (so the value is unchanged) |
| 1639 | # -1 indicates that there are nonzero digits to be truncated |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1640 | |
| 1641 | def _round_down(self, prec): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1642 | """Also known as round-towards-0, truncate.""" |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1643 | if _all_zeros(self._int, prec): |
| 1644 | return 0 |
| 1645 | else: |
| 1646 | return -1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1647 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1648 | def _round_up(self, prec): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1649 | """Rounds away from 0.""" |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1650 | return -self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1651 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1652 | def _round_half_up(self, prec): |
| 1653 | """Rounds 5 up (away from 0)""" |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1654 | if self._int[prec] in '56789': |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1655 | return 1 |
| 1656 | elif _all_zeros(self._int, prec): |
| 1657 | return 0 |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1658 | else: |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1659 | return -1 |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1660 | |
| 1661 | def _round_half_down(self, prec): |
| 1662 | """Round 5 down""" |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1663 | if _exact_half(self._int, prec): |
| 1664 | return -1 |
| 1665 | else: |
| 1666 | return self._round_half_up(prec) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1667 | |
| 1668 | def _round_half_even(self, prec): |
| 1669 | """Round 5 to even, rest to nearest.""" |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1670 | if _exact_half(self._int, prec) and \ |
| 1671 | (prec == 0 or self._int[prec-1] in '02468'): |
| 1672 | return -1 |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1673 | else: |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1674 | return self._round_half_up(prec) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1675 | |
| 1676 | def _round_ceiling(self, prec): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1677 | """Rounds up (not away from 0 if negative.)""" |
| 1678 | if self._sign: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1679 | return self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1680 | else: |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1681 | return -self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1682 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1683 | def _round_floor(self, prec): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1684 | """Rounds down (not towards 0 if negative)""" |
| 1685 | if not self._sign: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1686 | return self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1687 | else: |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1688 | return -self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1689 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1690 | def _round_05up(self, prec): |
| 1691 | """Round down unless digit prec-1 is 0 or 5.""" |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1692 | if prec and self._int[prec-1] not in '05': |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1693 | return self._round_down(prec) |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1694 | else: |
| 1695 | return -self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1696 | |
Mark Dickinson | b27406c | 2008-05-09 13:42:33 +0000 | [diff] [blame] | 1697 | def __round__(self, n=None): |
| 1698 | """Round self to the nearest integer, or to a given precision. |
| 1699 | |
| 1700 | If only one argument is supplied, round a finite Decimal |
| 1701 | instance self to the nearest integer. If self is infinite or |
| 1702 | a NaN then a Python exception is raised. If self is finite |
| 1703 | and lies exactly halfway between two integers then it is |
| 1704 | rounded to the integer with even last digit. |
| 1705 | |
| 1706 | >>> round(Decimal('123.456')) |
| 1707 | 123 |
| 1708 | >>> round(Decimal('-456.789')) |
| 1709 | -457 |
| 1710 | >>> round(Decimal('-3.0')) |
| 1711 | -3 |
| 1712 | >>> round(Decimal('2.5')) |
| 1713 | 2 |
| 1714 | >>> round(Decimal('3.5')) |
| 1715 | 4 |
| 1716 | >>> round(Decimal('Inf')) |
| 1717 | Traceback (most recent call last): |
| 1718 | ... |
| 1719 | ... |
| 1720 | ... |
| 1721 | OverflowError: cannot round an infinity |
| 1722 | >>> round(Decimal('NaN')) |
| 1723 | Traceback (most recent call last): |
| 1724 | ... |
| 1725 | ... |
| 1726 | ... |
| 1727 | ValueError: cannot round a NaN |
| 1728 | |
| 1729 | If a second argument n is supplied, self is rounded to n |
| 1730 | decimal places using the rounding mode for the current |
| 1731 | context. |
| 1732 | |
| 1733 | For an integer n, round(self, -n) is exactly equivalent to |
| 1734 | self.quantize(Decimal('1En')). |
| 1735 | |
| 1736 | >>> round(Decimal('123.456'), 0) |
| 1737 | Decimal('123') |
| 1738 | >>> round(Decimal('123.456'), 2) |
| 1739 | Decimal('123.46') |
| 1740 | >>> round(Decimal('123.456'), -2) |
| 1741 | Decimal('1E+2') |
| 1742 | >>> round(Decimal('-Infinity'), 37) |
| 1743 | Decimal('NaN') |
| 1744 | >>> round(Decimal('sNaN123'), 0) |
| 1745 | Decimal('NaN123') |
| 1746 | |
| 1747 | """ |
| 1748 | if n is not None: |
| 1749 | # two-argument form: use the equivalent quantize call |
| 1750 | if not isinstance(n, int): |
| 1751 | raise TypeError('Second argument to round should be integral') |
| 1752 | exp = _dec_from_triple(0, '1', -n) |
| 1753 | return self.quantize(exp) |
| 1754 | |
| 1755 | # one-argument form |
| 1756 | if self._is_special: |
| 1757 | if self.is_nan(): |
| 1758 | raise ValueError("cannot round a NaN") |
| 1759 | else: |
| 1760 | raise OverflowError("cannot round an infinity") |
| 1761 | return int(self._rescale(0, ROUND_HALF_EVEN)) |
| 1762 | |
| 1763 | def __floor__(self): |
| 1764 | """Return the floor of self, as an integer. |
| 1765 | |
| 1766 | For a finite Decimal instance self, return the greatest |
| 1767 | integer n such that n <= self. If self is infinite or a NaN |
| 1768 | then a Python exception is raised. |
| 1769 | |
| 1770 | """ |
| 1771 | if self._is_special: |
| 1772 | if self.is_nan(): |
| 1773 | raise ValueError("cannot round a NaN") |
| 1774 | else: |
| 1775 | raise OverflowError("cannot round an infinity") |
| 1776 | return int(self._rescale(0, ROUND_FLOOR)) |
| 1777 | |
| 1778 | def __ceil__(self): |
| 1779 | """Return the ceiling of self, as an integer. |
| 1780 | |
| 1781 | For a finite Decimal instance self, return the least integer n |
| 1782 | such that n >= self. If self is infinite or a NaN then a |
| 1783 | Python exception is raised. |
| 1784 | |
| 1785 | """ |
| 1786 | if self._is_special: |
| 1787 | if self.is_nan(): |
| 1788 | raise ValueError("cannot round a NaN") |
| 1789 | else: |
| 1790 | raise OverflowError("cannot round an infinity") |
| 1791 | return int(self._rescale(0, ROUND_CEILING)) |
| 1792 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1793 | def fma(self, other, third, context=None): |
| 1794 | """Fused multiply-add. |
| 1795 | |
| 1796 | Returns self*other+third with no rounding of the intermediate |
| 1797 | product self*other. |
| 1798 | |
| 1799 | self and other are multiplied together, with no rounding of |
| 1800 | the result. The third operand is then added to the result, |
| 1801 | and a single final rounding is performed. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1802 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1803 | |
| 1804 | other = _convert_other(other, raiseit=True) |
Christian Heimes | 8b0facf | 2007-12-04 19:30:01 +0000 | [diff] [blame] | 1805 | |
| 1806 | # compute product; raise InvalidOperation if either operand is |
| 1807 | # a signaling NaN or if the product is zero times infinity. |
| 1808 | if self._is_special or other._is_special: |
| 1809 | if context is None: |
| 1810 | context = getcontext() |
| 1811 | if self._exp == 'N': |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 1812 | return context._raise_error(InvalidOperation, 'sNaN', self) |
Christian Heimes | 8b0facf | 2007-12-04 19:30:01 +0000 | [diff] [blame] | 1813 | if other._exp == 'N': |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 1814 | return context._raise_error(InvalidOperation, 'sNaN', other) |
Christian Heimes | 8b0facf | 2007-12-04 19:30:01 +0000 | [diff] [blame] | 1815 | if self._exp == 'n': |
| 1816 | product = self |
| 1817 | elif other._exp == 'n': |
| 1818 | product = other |
| 1819 | elif self._exp == 'F': |
| 1820 | if not other: |
| 1821 | return context._raise_error(InvalidOperation, |
| 1822 | 'INF * 0 in fma') |
| 1823 | product = Infsign[self._sign ^ other._sign] |
| 1824 | elif other._exp == 'F': |
| 1825 | if not self: |
| 1826 | return context._raise_error(InvalidOperation, |
| 1827 | '0 * INF in fma') |
| 1828 | product = Infsign[self._sign ^ other._sign] |
| 1829 | else: |
| 1830 | product = _dec_from_triple(self._sign ^ other._sign, |
| 1831 | str(int(self._int) * int(other._int)), |
| 1832 | self._exp + other._exp) |
| 1833 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1834 | third = _convert_other(third, raiseit=True) |
Christian Heimes | 8b0facf | 2007-12-04 19:30:01 +0000 | [diff] [blame] | 1835 | return product.__add__(third, context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1836 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1837 | def _power_modulo(self, other, modulo, context=None): |
| 1838 | """Three argument version of __pow__""" |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1839 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1840 | # if can't convert other and modulo to Decimal, raise |
| 1841 | # TypeError; there's no point returning NotImplemented (no |
| 1842 | # equivalent of __rpow__ for three argument pow) |
| 1843 | other = _convert_other(other, raiseit=True) |
| 1844 | modulo = _convert_other(modulo, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1845 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1846 | if context is None: |
| 1847 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1848 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1849 | # deal with NaNs: if there are any sNaNs then first one wins, |
| 1850 | # (i.e. behaviour for NaNs is identical to that of fma) |
| 1851 | self_is_nan = self._isnan() |
| 1852 | other_is_nan = other._isnan() |
| 1853 | modulo_is_nan = modulo._isnan() |
| 1854 | if self_is_nan or other_is_nan or modulo_is_nan: |
| 1855 | if self_is_nan == 2: |
| 1856 | return context._raise_error(InvalidOperation, 'sNaN', |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 1857 | self) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1858 | if other_is_nan == 2: |
| 1859 | return context._raise_error(InvalidOperation, 'sNaN', |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 1860 | other) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1861 | if modulo_is_nan == 2: |
| 1862 | return context._raise_error(InvalidOperation, 'sNaN', |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 1863 | modulo) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1864 | if self_is_nan: |
| 1865 | return self._fix_nan(context) |
| 1866 | if other_is_nan: |
| 1867 | return other._fix_nan(context) |
| 1868 | return modulo._fix_nan(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1869 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1870 | # check inputs: we apply same restrictions as Python's pow() |
| 1871 | if not (self._isinteger() and |
| 1872 | other._isinteger() and |
| 1873 | modulo._isinteger()): |
| 1874 | return context._raise_error(InvalidOperation, |
| 1875 | 'pow() 3rd argument not allowed ' |
| 1876 | 'unless all arguments are integers') |
| 1877 | if other < 0: |
| 1878 | return context._raise_error(InvalidOperation, |
| 1879 | 'pow() 2nd argument cannot be ' |
| 1880 | 'negative when 3rd argument specified') |
| 1881 | if not modulo: |
| 1882 | return context._raise_error(InvalidOperation, |
| 1883 | 'pow() 3rd argument cannot be 0') |
| 1884 | |
| 1885 | # additional restriction for decimal: the modulus must be less |
| 1886 | # than 10**prec in absolute value |
| 1887 | if modulo.adjusted() >= context.prec: |
| 1888 | return context._raise_error(InvalidOperation, |
| 1889 | 'insufficient precision: pow() 3rd ' |
| 1890 | 'argument must not have more than ' |
| 1891 | 'precision digits') |
| 1892 | |
| 1893 | # define 0**0 == NaN, for consistency with two-argument pow |
| 1894 | # (even though it hurts!) |
| 1895 | if not other and not self: |
| 1896 | return context._raise_error(InvalidOperation, |
| 1897 | 'at least one of pow() 1st argument ' |
| 1898 | 'and 2nd argument must be nonzero ;' |
| 1899 | '0**0 is not defined') |
| 1900 | |
| 1901 | # compute sign of result |
| 1902 | if other._iseven(): |
| 1903 | sign = 0 |
| 1904 | else: |
| 1905 | sign = self._sign |
| 1906 | |
| 1907 | # convert modulo to a Python integer, and self and other to |
| 1908 | # Decimal integers (i.e. force their exponents to be >= 0) |
| 1909 | modulo = abs(int(modulo)) |
| 1910 | base = _WorkRep(self.to_integral_value()) |
| 1911 | exponent = _WorkRep(other.to_integral_value()) |
| 1912 | |
| 1913 | # compute result using integer pow() |
| 1914 | base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo |
| 1915 | for i in range(exponent.exp): |
| 1916 | base = pow(base, 10, modulo) |
| 1917 | base = pow(base, exponent.int, modulo) |
| 1918 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1919 | return _dec_from_triple(sign, str(base), 0) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1920 | |
| 1921 | def _power_exact(self, other, p): |
| 1922 | """Attempt to compute self**other exactly. |
| 1923 | |
| 1924 | Given Decimals self and other and an integer p, attempt to |
| 1925 | compute an exact result for the power self**other, with p |
| 1926 | digits of precision. Return None if self**other is not |
| 1927 | exactly representable in p digits. |
| 1928 | |
| 1929 | Assumes that elimination of special cases has already been |
| 1930 | performed: self and other must both be nonspecial; self must |
| 1931 | be positive and not numerically equal to 1; other must be |
| 1932 | nonzero. For efficiency, other._exp should not be too large, |
| 1933 | so that 10**abs(other._exp) is a feasible calculation.""" |
| 1934 | |
| 1935 | # In the comments below, we write x for the value of self and |
| 1936 | # y for the value of other. Write x = xc*10**xe and y = |
| 1937 | # yc*10**ye. |
| 1938 | |
| 1939 | # The main purpose of this method is to identify the *failure* |
| 1940 | # of x**y to be exactly representable with as little effort as |
| 1941 | # possible. So we look for cheap and easy tests that |
| 1942 | # eliminate the possibility of x**y being exact. Only if all |
| 1943 | # these tests are passed do we go on to actually compute x**y. |
| 1944 | |
| 1945 | # Here's the main idea. First normalize both x and y. We |
| 1946 | # express y as a rational m/n, with m and n relatively prime |
| 1947 | # and n>0. Then for x**y to be exactly representable (at |
| 1948 | # *any* precision), xc must be the nth power of a positive |
| 1949 | # integer and xe must be divisible by n. If m is negative |
| 1950 | # then additionally xc must be a power of either 2 or 5, hence |
| 1951 | # a power of 2**n or 5**n. |
| 1952 | # |
| 1953 | # There's a limit to how small |y| can be: if y=m/n as above |
| 1954 | # then: |
| 1955 | # |
| 1956 | # (1) if xc != 1 then for the result to be representable we |
| 1957 | # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So |
| 1958 | # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <= |
| 1959 | # 2**(1/|y|), hence xc**|y| < 2 and the result is not |
| 1960 | # representable. |
| 1961 | # |
| 1962 | # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if |
| 1963 | # |y| < 1/|xe| then the result is not representable. |
| 1964 | # |
| 1965 | # Note that since x is not equal to 1, at least one of (1) and |
| 1966 | # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) < |
| 1967 | # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye. |
| 1968 | # |
| 1969 | # There's also a limit to how large y can be, at least if it's |
| 1970 | # positive: the normalized result will have coefficient xc**y, |
| 1971 | # so if it's representable then xc**y < 10**p, and y < |
| 1972 | # p/log10(xc). Hence if y*log10(xc) >= p then the result is |
| 1973 | # not exactly representable. |
| 1974 | |
| 1975 | # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye, |
| 1976 | # so |y| < 1/xe and the result is not representable. |
| 1977 | # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y| |
| 1978 | # < 1/nbits(xc). |
| 1979 | |
| 1980 | x = _WorkRep(self) |
| 1981 | xc, xe = x.int, x.exp |
| 1982 | while xc % 10 == 0: |
| 1983 | xc //= 10 |
| 1984 | xe += 1 |
| 1985 | |
| 1986 | y = _WorkRep(other) |
| 1987 | yc, ye = y.int, y.exp |
| 1988 | while yc % 10 == 0: |
| 1989 | yc //= 10 |
| 1990 | ye += 1 |
| 1991 | |
| 1992 | # case where xc == 1: result is 10**(xe*y), with xe*y |
| 1993 | # required to be an integer |
| 1994 | if xc == 1: |
| 1995 | if ye >= 0: |
| 1996 | exponent = xe*yc*10**ye |
| 1997 | else: |
| 1998 | exponent, remainder = divmod(xe*yc, 10**-ye) |
| 1999 | if remainder: |
| 2000 | return None |
| 2001 | if y.sign == 1: |
| 2002 | exponent = -exponent |
| 2003 | # if other is a nonnegative integer, use ideal exponent |
| 2004 | if other._isinteger() and other._sign == 0: |
| 2005 | ideal_exponent = self._exp*int(other) |
| 2006 | zeros = min(exponent-ideal_exponent, p-1) |
| 2007 | else: |
| 2008 | zeros = 0 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2009 | return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2010 | |
| 2011 | # case where y is negative: xc must be either a power |
| 2012 | # of 2 or a power of 5. |
| 2013 | if y.sign == 1: |
| 2014 | last_digit = xc % 10 |
| 2015 | if last_digit in (2,4,6,8): |
| 2016 | # quick test for power of 2 |
| 2017 | if xc & -xc != xc: |
| 2018 | return None |
| 2019 | # now xc is a power of 2; e is its exponent |
| 2020 | e = _nbits(xc)-1 |
| 2021 | # find e*y and xe*y; both must be integers |
| 2022 | if ye >= 0: |
| 2023 | y_as_int = yc*10**ye |
| 2024 | e = e*y_as_int |
| 2025 | xe = xe*y_as_int |
| 2026 | else: |
| 2027 | ten_pow = 10**-ye |
| 2028 | e, remainder = divmod(e*yc, ten_pow) |
| 2029 | if remainder: |
| 2030 | return None |
| 2031 | xe, remainder = divmod(xe*yc, ten_pow) |
| 2032 | if remainder: |
| 2033 | return None |
| 2034 | |
| 2035 | if e*65 >= p*93: # 93/65 > log(10)/log(5) |
| 2036 | return None |
| 2037 | xc = 5**e |
| 2038 | |
| 2039 | elif last_digit == 5: |
| 2040 | # e >= log_5(xc) if xc is a power of 5; we have |
| 2041 | # equality all the way up to xc=5**2658 |
| 2042 | e = _nbits(xc)*28//65 |
| 2043 | xc, remainder = divmod(5**e, xc) |
| 2044 | if remainder: |
| 2045 | return None |
| 2046 | while xc % 5 == 0: |
| 2047 | xc //= 5 |
| 2048 | e -= 1 |
| 2049 | if ye >= 0: |
| 2050 | y_as_integer = yc*10**ye |
| 2051 | e = e*y_as_integer |
| 2052 | xe = xe*y_as_integer |
| 2053 | else: |
| 2054 | ten_pow = 10**-ye |
| 2055 | e, remainder = divmod(e*yc, ten_pow) |
| 2056 | if remainder: |
| 2057 | return None |
| 2058 | xe, remainder = divmod(xe*yc, ten_pow) |
| 2059 | if remainder: |
| 2060 | return None |
| 2061 | if e*3 >= p*10: # 10/3 > log(10)/log(2) |
| 2062 | return None |
| 2063 | xc = 2**e |
| 2064 | else: |
| 2065 | return None |
| 2066 | |
| 2067 | if xc >= 10**p: |
| 2068 | return None |
| 2069 | xe = -e-xe |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2070 | return _dec_from_triple(0, str(xc), xe) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2071 | |
| 2072 | # now y is positive; find m and n such that y = m/n |
| 2073 | if ye >= 0: |
| 2074 | m, n = yc*10**ye, 1 |
| 2075 | else: |
| 2076 | if xe != 0 and len(str(abs(yc*xe))) <= -ye: |
| 2077 | return None |
| 2078 | xc_bits = _nbits(xc) |
| 2079 | if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye: |
| 2080 | return None |
| 2081 | m, n = yc, 10**(-ye) |
| 2082 | while m % 2 == n % 2 == 0: |
| 2083 | m //= 2 |
| 2084 | n //= 2 |
| 2085 | while m % 5 == n % 5 == 0: |
| 2086 | m //= 5 |
| 2087 | n //= 5 |
| 2088 | |
| 2089 | # compute nth root of xc*10**xe |
| 2090 | if n > 1: |
| 2091 | # if 1 < xc < 2**n then xc isn't an nth power |
| 2092 | if xc != 1 and xc_bits <= n: |
| 2093 | return None |
| 2094 | |
| 2095 | xe, rem = divmod(xe, n) |
| 2096 | if rem != 0: |
| 2097 | return None |
| 2098 | |
| 2099 | # compute nth root of xc using Newton's method |
| 2100 | a = 1 << -(-_nbits(xc)//n) # initial estimate |
| 2101 | while True: |
| 2102 | q, r = divmod(xc, a**(n-1)) |
| 2103 | if a <= q: |
| 2104 | break |
| 2105 | else: |
| 2106 | a = (a*(n-1) + q)//n |
| 2107 | if not (a == q and r == 0): |
| 2108 | return None |
| 2109 | xc = a |
| 2110 | |
| 2111 | # now xc*10**xe is the nth root of the original xc*10**xe |
| 2112 | # compute mth power of xc*10**xe |
| 2113 | |
| 2114 | # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m > |
| 2115 | # 10**p and the result is not representable. |
| 2116 | if xc > 1 and m > p*100//_log10_lb(xc): |
| 2117 | return None |
| 2118 | xc = xc**m |
| 2119 | xe *= m |
| 2120 | if xc > 10**p: |
| 2121 | return None |
| 2122 | |
| 2123 | # by this point the result *is* exactly representable |
| 2124 | # adjust the exponent to get as close as possible to the ideal |
| 2125 | # exponent, if necessary |
| 2126 | str_xc = str(xc) |
| 2127 | if other._isinteger() and other._sign == 0: |
| 2128 | ideal_exponent = self._exp*int(other) |
| 2129 | zeros = min(xe-ideal_exponent, p-len(str_xc)) |
| 2130 | else: |
| 2131 | zeros = 0 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2132 | return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2133 | |
| 2134 | def __pow__(self, other, modulo=None, context=None): |
| 2135 | """Return self ** other [ % modulo]. |
| 2136 | |
| 2137 | With two arguments, compute self**other. |
| 2138 | |
| 2139 | With three arguments, compute (self**other) % modulo. For the |
| 2140 | three argument form, the following restrictions on the |
| 2141 | arguments hold: |
| 2142 | |
| 2143 | - all three arguments must be integral |
| 2144 | - other must be nonnegative |
| 2145 | - either self or other (or both) must be nonzero |
| 2146 | - modulo must be nonzero and must have at most p digits, |
| 2147 | where p is the context precision. |
| 2148 | |
| 2149 | If any of these restrictions is violated the InvalidOperation |
| 2150 | flag is raised. |
| 2151 | |
| 2152 | The result of pow(self, other, modulo) is identical to the |
| 2153 | result that would be obtained by computing (self**other) % |
| 2154 | modulo with unbounded precision, but is computed more |
| 2155 | efficiently. It is always exact. |
| 2156 | """ |
| 2157 | |
| 2158 | if modulo is not None: |
| 2159 | return self._power_modulo(other, modulo, context) |
| 2160 | |
| 2161 | other = _convert_other(other) |
| 2162 | if other is NotImplemented: |
| 2163 | return other |
| 2164 | |
| 2165 | if context is None: |
| 2166 | context = getcontext() |
| 2167 | |
| 2168 | # either argument is a NaN => result is NaN |
| 2169 | ans = self._check_nans(other, context) |
| 2170 | if ans: |
| 2171 | return ans |
| 2172 | |
| 2173 | # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity) |
| 2174 | if not other: |
| 2175 | if not self: |
| 2176 | return context._raise_error(InvalidOperation, '0 ** 0') |
| 2177 | else: |
| 2178 | return Dec_p1 |
| 2179 | |
| 2180 | # result has sign 1 iff self._sign is 1 and other is an odd integer |
| 2181 | result_sign = 0 |
| 2182 | if self._sign == 1: |
| 2183 | if other._isinteger(): |
| 2184 | if not other._iseven(): |
| 2185 | result_sign = 1 |
| 2186 | else: |
| 2187 | # -ve**noninteger = NaN |
| 2188 | # (-0)**noninteger = 0**noninteger |
| 2189 | if self: |
| 2190 | return context._raise_error(InvalidOperation, |
| 2191 | 'x ** y with x negative and y not an integer') |
| 2192 | # negate self, without doing any unwanted rounding |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2193 | self = self.copy_negate() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2194 | |
| 2195 | # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity |
| 2196 | if not self: |
| 2197 | if other._sign == 0: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2198 | return _dec_from_triple(result_sign, '0', 0) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2199 | else: |
| 2200 | return Infsign[result_sign] |
| 2201 | |
| 2202 | # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2203 | if self._isinfinity(): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2204 | if other._sign == 0: |
| 2205 | return Infsign[result_sign] |
| 2206 | else: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2207 | return _dec_from_triple(result_sign, '0', 0) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2208 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2209 | # 1**other = 1, but the choice of exponent and the flags |
| 2210 | # depend on the exponent of self, and on whether other is a |
| 2211 | # positive integer, a negative integer, or neither |
| 2212 | if self == Dec_p1: |
| 2213 | if other._isinteger(): |
| 2214 | # exp = max(self._exp*max(int(other), 0), |
| 2215 | # 1-context.prec) but evaluating int(other) directly |
| 2216 | # is dangerous until we know other is small (other |
| 2217 | # could be 1e999999999) |
| 2218 | if other._sign == 1: |
| 2219 | multiplier = 0 |
| 2220 | elif other > context.prec: |
| 2221 | multiplier = context.prec |
| 2222 | else: |
| 2223 | multiplier = int(other) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2224 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2225 | exp = self._exp * multiplier |
| 2226 | if exp < 1-context.prec: |
| 2227 | exp = 1-context.prec |
| 2228 | context._raise_error(Rounded) |
| 2229 | else: |
| 2230 | context._raise_error(Inexact) |
| 2231 | context._raise_error(Rounded) |
| 2232 | exp = 1-context.prec |
| 2233 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2234 | return _dec_from_triple(result_sign, '1'+'0'*-exp, exp) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2235 | |
| 2236 | # compute adjusted exponent of self |
| 2237 | self_adj = self.adjusted() |
| 2238 | |
| 2239 | # self ** infinity is infinity if self > 1, 0 if self < 1 |
| 2240 | # self ** -infinity is infinity if self < 1, 0 if self > 1 |
| 2241 | if other._isinfinity(): |
| 2242 | if (other._sign == 0) == (self_adj < 0): |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2243 | return _dec_from_triple(result_sign, '0', 0) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2244 | else: |
| 2245 | return Infsign[result_sign] |
| 2246 | |
| 2247 | # from here on, the result always goes through the call |
| 2248 | # to _fix at the end of this function. |
| 2249 | ans = None |
| 2250 | |
| 2251 | # crude test to catch cases of extreme overflow/underflow. If |
| 2252 | # log10(self)*other >= 10**bound and bound >= len(str(Emax)) |
| 2253 | # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence |
| 2254 | # self**other >= 10**(Emax+1), so overflow occurs. The test |
| 2255 | # for underflow is similar. |
| 2256 | bound = self._log10_exp_bound() + other.adjusted() |
| 2257 | if (self_adj >= 0) == (other._sign == 0): |
| 2258 | # self > 1 and other +ve, or self < 1 and other -ve |
| 2259 | # possibility of overflow |
| 2260 | if bound >= len(str(context.Emax)): |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2261 | ans = _dec_from_triple(result_sign, '1', context.Emax+1) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2262 | else: |
| 2263 | # self > 1 and other -ve, or self < 1 and other +ve |
| 2264 | # possibility of underflow to 0 |
| 2265 | Etiny = context.Etiny() |
| 2266 | if bound >= len(str(-Etiny)): |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2267 | ans = _dec_from_triple(result_sign, '1', Etiny-1) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2268 | |
| 2269 | # try for an exact result with precision +1 |
| 2270 | if ans is None: |
| 2271 | ans = self._power_exact(other, context.prec + 1) |
| 2272 | if ans is not None and result_sign == 1: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2273 | ans = _dec_from_triple(1, ans._int, ans._exp) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2274 | |
| 2275 | # usual case: inexact result, x**y computed directly as exp(y*log(x)) |
| 2276 | if ans is None: |
| 2277 | p = context.prec |
| 2278 | x = _WorkRep(self) |
| 2279 | xc, xe = x.int, x.exp |
| 2280 | y = _WorkRep(other) |
| 2281 | yc, ye = y.int, y.exp |
| 2282 | if y.sign == 1: |
| 2283 | yc = -yc |
| 2284 | |
| 2285 | # compute correctly rounded result: start with precision +3, |
| 2286 | # then increase precision until result is unambiguously roundable |
| 2287 | extra = 3 |
| 2288 | while True: |
| 2289 | coeff, exp = _dpower(xc, xe, yc, ye, p+extra) |
| 2290 | if coeff % (5*10**(len(str(coeff))-p-1)): |
| 2291 | break |
| 2292 | extra += 3 |
| 2293 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2294 | ans = _dec_from_triple(result_sign, str(coeff), exp) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2295 | |
| 2296 | # the specification says that for non-integer other we need to |
| 2297 | # raise Inexact, even when the result is actually exact. In |
| 2298 | # the same way, we need to raise Underflow here if the result |
| 2299 | # is subnormal. (The call to _fix will take care of raising |
| 2300 | # Rounded and Subnormal, as usual.) |
| 2301 | if not other._isinteger(): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2302 | context._raise_error(Inexact) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2303 | # pad with zeros up to length context.prec+1 if necessary |
| 2304 | if len(ans._int) <= context.prec: |
| 2305 | expdiff = context.prec+1 - len(ans._int) |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2306 | ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff, |
| 2307 | ans._exp-expdiff) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2308 | if ans.adjusted() < context.Emin: |
| 2309 | context._raise_error(Underflow) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2310 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2311 | # unlike exp, ln and log10, the power function respects the |
| 2312 | # rounding mode; no need to use ROUND_HALF_EVEN here |
| 2313 | ans = ans._fix(context) |
| 2314 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2315 | |
| 2316 | def __rpow__(self, other, context=None): |
| 2317 | """Swaps self/other and returns __pow__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2318 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 2319 | if other is NotImplemented: |
| 2320 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2321 | return other.__pow__(self, context=context) |
| 2322 | |
| 2323 | def normalize(self, context=None): |
| 2324 | """Normalize- strip trailing 0s, change anything equal to 0 to 0e0""" |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2325 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2326 | if context is None: |
| 2327 | context = getcontext() |
| 2328 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2329 | if self._is_special: |
| 2330 | ans = self._check_nans(context=context) |
| 2331 | if ans: |
| 2332 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2333 | |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 2334 | dup = self._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2335 | if dup._isinfinity(): |
| 2336 | return dup |
| 2337 | |
| 2338 | if not dup: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2339 | return _dec_from_triple(dup._sign, '0', 0) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2340 | exp_max = [context.Emax, context.Etop()][context._clamp] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2341 | end = len(dup._int) |
| 2342 | exp = dup._exp |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2343 | while dup._int[end-1] == '0' and exp < exp_max: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2344 | exp += 1 |
| 2345 | end -= 1 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2346 | return _dec_from_triple(dup._sign, dup._int[:end], exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2347 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2348 | def quantize(self, exp, rounding=None, context=None, watchexp=True): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2349 | """Quantize self so its exponent is the same as that of exp. |
| 2350 | |
| 2351 | Similar to self._rescale(exp._exp) but with error checking. |
| 2352 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2353 | exp = _convert_other(exp, raiseit=True) |
| 2354 | |
| 2355 | if context is None: |
| 2356 | context = getcontext() |
| 2357 | if rounding is None: |
| 2358 | rounding = context.rounding |
| 2359 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2360 | if self._is_special or exp._is_special: |
| 2361 | ans = self._check_nans(exp, context) |
| 2362 | if ans: |
| 2363 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2364 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2365 | if exp._isinfinity() or self._isinfinity(): |
| 2366 | if exp._isinfinity() and self._isinfinity(): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2367 | return Decimal(self) # if both are inf, it is OK |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2368 | return context._raise_error(InvalidOperation, |
| 2369 | 'quantize with one INF') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2370 | |
| 2371 | # if we're not watching exponents, do a simple rescale |
| 2372 | if not watchexp: |
| 2373 | ans = self._rescale(exp._exp, rounding) |
| 2374 | # raise Inexact and Rounded where appropriate |
| 2375 | if ans._exp > self._exp: |
| 2376 | context._raise_error(Rounded) |
| 2377 | if ans != self: |
| 2378 | context._raise_error(Inexact) |
| 2379 | return ans |
| 2380 | |
| 2381 | # exp._exp should be between Etiny and Emax |
| 2382 | if not (context.Etiny() <= exp._exp <= context.Emax): |
| 2383 | return context._raise_error(InvalidOperation, |
| 2384 | 'target exponent out of bounds in quantize') |
| 2385 | |
| 2386 | if not self: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2387 | ans = _dec_from_triple(self._sign, '0', exp._exp) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2388 | return ans._fix(context) |
| 2389 | |
| 2390 | self_adjusted = self.adjusted() |
| 2391 | if self_adjusted > context.Emax: |
| 2392 | return context._raise_error(InvalidOperation, |
| 2393 | 'exponent of quantize result too large for current context') |
| 2394 | if self_adjusted - exp._exp + 1 > context.prec: |
| 2395 | return context._raise_error(InvalidOperation, |
| 2396 | 'quantize result has too many digits for current context') |
| 2397 | |
| 2398 | ans = self._rescale(exp._exp, rounding) |
| 2399 | if ans.adjusted() > context.Emax: |
| 2400 | return context._raise_error(InvalidOperation, |
| 2401 | 'exponent of quantize result too large for current context') |
| 2402 | if len(ans._int) > context.prec: |
| 2403 | return context._raise_error(InvalidOperation, |
| 2404 | 'quantize result has too many digits for current context') |
| 2405 | |
| 2406 | # raise appropriate flags |
| 2407 | if ans._exp > self._exp: |
| 2408 | context._raise_error(Rounded) |
| 2409 | if ans != self: |
| 2410 | context._raise_error(Inexact) |
| 2411 | if ans and ans.adjusted() < context.Emin: |
| 2412 | context._raise_error(Subnormal) |
| 2413 | |
| 2414 | # call to fix takes care of any necessary folddown |
| 2415 | ans = ans._fix(context) |
| 2416 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2417 | |
| 2418 | def same_quantum(self, other): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2419 | """Return True if self and other have the same exponent; otherwise |
| 2420 | return False. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2421 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2422 | If either operand is a special value, the following rules are used: |
| 2423 | * return True if both operands are infinities |
| 2424 | * return True if both operands are NaNs |
| 2425 | * otherwise, return False. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2426 | """ |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2427 | other = _convert_other(other, raiseit=True) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2428 | if self._is_special or other._is_special: |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2429 | return (self.is_nan() and other.is_nan() or |
| 2430 | self.is_infinite() and other.is_infinite()) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2431 | return self._exp == other._exp |
| 2432 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2433 | def _rescale(self, exp, rounding): |
| 2434 | """Rescale self so that the exponent is exp, either by padding with zeros |
| 2435 | or by truncating digits, using the given rounding mode. |
| 2436 | |
| 2437 | Specials are returned without change. This operation is |
| 2438 | quiet: it raises no flags, and uses no information from the |
| 2439 | context. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2440 | |
| 2441 | exp = exp to scale to (an integer) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2442 | rounding = rounding mode |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2443 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2444 | if self._is_special: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2445 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2446 | if not self: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2447 | return _dec_from_triple(self._sign, '0', exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2448 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2449 | if self._exp >= exp: |
| 2450 | # pad answer with zeros if necessary |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2451 | return _dec_from_triple(self._sign, |
| 2452 | self._int + '0'*(self._exp - exp), exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2453 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2454 | # too many digits; round and lose data. If self.adjusted() < |
| 2455 | # exp-1, replace self by 10**(exp-1) before rounding |
| 2456 | digits = len(self._int) + self._exp - exp |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2457 | if digits < 0: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2458 | self = _dec_from_triple(self._sign, '1', exp-1) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2459 | digits = 0 |
| 2460 | this_function = getattr(self, self._pick_rounding_function[rounding]) |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 2461 | changed = this_function(digits) |
| 2462 | coeff = self._int[:digits] or '0' |
| 2463 | if changed == 1: |
| 2464 | coeff = str(int(coeff)+1) |
| 2465 | return _dec_from_triple(self._sign, coeff, exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2466 | |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 2467 | def _round(self, places, rounding): |
| 2468 | """Round a nonzero, nonspecial Decimal to a fixed number of |
| 2469 | significant figures, using the given rounding mode. |
| 2470 | |
| 2471 | Infinities, NaNs and zeros are returned unaltered. |
| 2472 | |
| 2473 | This operation is quiet: it raises no flags, and uses no |
| 2474 | information from the context. |
| 2475 | |
| 2476 | """ |
| 2477 | if places <= 0: |
| 2478 | raise ValueError("argument should be at least 1 in _round") |
| 2479 | if self._is_special or not self: |
| 2480 | return Decimal(self) |
| 2481 | ans = self._rescale(self.adjusted()+1-places, rounding) |
| 2482 | # it can happen that the rescale alters the adjusted exponent; |
| 2483 | # for example when rounding 99.97 to 3 significant figures. |
| 2484 | # When this happens we end up with an extra 0 at the end of |
| 2485 | # the number; a second rescale fixes this. |
| 2486 | if ans.adjusted() != self.adjusted(): |
| 2487 | ans = ans._rescale(ans.adjusted()+1-places, rounding) |
| 2488 | return ans |
| 2489 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2490 | def to_integral_exact(self, rounding=None, context=None): |
| 2491 | """Rounds to a nearby integer. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2492 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2493 | If no rounding mode is specified, take the rounding mode from |
| 2494 | the context. This method raises the Rounded and Inexact flags |
| 2495 | when appropriate. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2496 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2497 | See also: to_integral_value, which does exactly the same as |
| 2498 | this method except that it doesn't raise Inexact or Rounded. |
| 2499 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2500 | if self._is_special: |
| 2501 | ans = self._check_nans(context=context) |
| 2502 | if ans: |
| 2503 | return ans |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2504 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2505 | if self._exp >= 0: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2506 | return Decimal(self) |
| 2507 | if not self: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2508 | return _dec_from_triple(self._sign, '0', 0) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2509 | if context is None: |
| 2510 | context = getcontext() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2511 | if rounding is None: |
| 2512 | rounding = context.rounding |
| 2513 | context._raise_error(Rounded) |
| 2514 | ans = self._rescale(0, rounding) |
| 2515 | if ans != self: |
| 2516 | context._raise_error(Inexact) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2517 | return ans |
| 2518 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2519 | def to_integral_value(self, rounding=None, context=None): |
| 2520 | """Rounds to the nearest integer, without raising inexact, rounded.""" |
| 2521 | if context is None: |
| 2522 | context = getcontext() |
| 2523 | if rounding is None: |
| 2524 | rounding = context.rounding |
| 2525 | if self._is_special: |
| 2526 | ans = self._check_nans(context=context) |
| 2527 | if ans: |
| 2528 | return ans |
| 2529 | return Decimal(self) |
| 2530 | if self._exp >= 0: |
| 2531 | return Decimal(self) |
| 2532 | else: |
| 2533 | return self._rescale(0, rounding) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2534 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2535 | # the method name changed, but we provide also the old one, for compatibility |
| 2536 | to_integral = to_integral_value |
| 2537 | |
| 2538 | def sqrt(self, context=None): |
| 2539 | """Return the square root of self.""" |
Christian Heimes | 0348fb6 | 2008-03-26 12:55:56 +0000 | [diff] [blame] | 2540 | if context is None: |
| 2541 | context = getcontext() |
| 2542 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2543 | if self._is_special: |
| 2544 | ans = self._check_nans(context=context) |
| 2545 | if ans: |
| 2546 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2547 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2548 | if self._isinfinity() and self._sign == 0: |
| 2549 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2550 | |
| 2551 | if not self: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2552 | # exponent = self._exp // 2. sqrt(-0) = -0 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2553 | ans = _dec_from_triple(self._sign, '0', self._exp // 2) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2554 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2555 | |
| 2556 | if self._sign == 1: |
| 2557 | return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0') |
| 2558 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2559 | # At this point self represents a positive number. Let p be |
| 2560 | # the desired precision and express self in the form c*100**e |
| 2561 | # with c a positive real number and e an integer, c and e |
| 2562 | # being chosen so that 100**(p-1) <= c < 100**p. Then the |
| 2563 | # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1) |
| 2564 | # <= sqrt(c) < 10**p, so the closest representable Decimal at |
| 2565 | # precision p is n*10**e where n = round_half_even(sqrt(c)), |
| 2566 | # the closest integer to sqrt(c) with the even integer chosen |
| 2567 | # in the case of a tie. |
| 2568 | # |
| 2569 | # To ensure correct rounding in all cases, we use the |
| 2570 | # following trick: we compute the square root to an extra |
| 2571 | # place (precision p+1 instead of precision p), rounding down. |
| 2572 | # Then, if the result is inexact and its last digit is 0 or 5, |
| 2573 | # we increase the last digit to 1 or 6 respectively; if it's |
| 2574 | # exact we leave the last digit alone. Now the final round to |
| 2575 | # p places (or fewer in the case of underflow) will round |
| 2576 | # correctly and raise the appropriate flags. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2577 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2578 | # use an extra digit of precision |
| 2579 | prec = context.prec+1 |
| 2580 | |
| 2581 | # write argument in the form c*100**e where e = self._exp//2 |
| 2582 | # is the 'ideal' exponent, to be used if the square root is |
| 2583 | # exactly representable. l is the number of 'digits' of c in |
| 2584 | # base 100, so that 100**(l-1) <= c < 100**l. |
| 2585 | op = _WorkRep(self) |
| 2586 | e = op.exp >> 1 |
| 2587 | if op.exp & 1: |
| 2588 | c = op.int * 10 |
| 2589 | l = (len(self._int) >> 1) + 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2590 | else: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2591 | c = op.int |
| 2592 | l = len(self._int)+1 >> 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2593 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2594 | # rescale so that c has exactly prec base 100 'digits' |
| 2595 | shift = prec-l |
| 2596 | if shift >= 0: |
| 2597 | c *= 100**shift |
| 2598 | exact = True |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2599 | else: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2600 | c, remainder = divmod(c, 100**-shift) |
| 2601 | exact = not remainder |
| 2602 | e -= shift |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2603 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2604 | # find n = floor(sqrt(c)) using Newton's method |
| 2605 | n = 10**prec |
| 2606 | while True: |
| 2607 | q = c//n |
| 2608 | if n <= q: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2609 | break |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2610 | else: |
| 2611 | n = n + q >> 1 |
| 2612 | exact = exact and n*n == c |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2613 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2614 | if exact: |
| 2615 | # result is exact; rescale to use ideal exponent e |
| 2616 | if shift >= 0: |
| 2617 | # assert n % 10**shift == 0 |
| 2618 | n //= 10**shift |
| 2619 | else: |
| 2620 | n *= 10**-shift |
| 2621 | e += shift |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2622 | else: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2623 | # result is not exact; fix last digit as described above |
| 2624 | if n % 5 == 0: |
| 2625 | n += 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2626 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2627 | ans = _dec_from_triple(0, str(n), e) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2628 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2629 | # round, and fit to current context |
| 2630 | context = context._shallow_copy() |
| 2631 | rounding = context._set_rounding(ROUND_HALF_EVEN) |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 2632 | ans = ans._fix(context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2633 | context.rounding = rounding |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2634 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2635 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2636 | |
| 2637 | def max(self, other, context=None): |
| 2638 | """Returns the larger value. |
| 2639 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2640 | Like max(self, other) except if one is not a number, returns |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2641 | NaN (and signals if one is sNaN). Also rounds. |
| 2642 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2643 | other = _convert_other(other, raiseit=True) |
| 2644 | |
| 2645 | if context is None: |
| 2646 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2647 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2648 | if self._is_special or other._is_special: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2649 | # 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] | 2650 | # number is always returned |
| 2651 | sn = self._isnan() |
| 2652 | on = other._isnan() |
| 2653 | if sn or on: |
| 2654 | if on == 1 and sn != 2: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2655 | return self._fix_nan(context) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2656 | if sn == 1 and on != 2: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2657 | return other._fix_nan(context) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2658 | return self._check_nans(other, context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2659 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 2660 | c = self._cmp(other) |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2661 | if c == 0: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2662 | # If both operands are finite and equal in numerical value |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2663 | # then an ordering is applied: |
| 2664 | # |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2665 | # If the signs differ then max returns the operand with the |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2666 | # positive sign and min returns the operand with the negative sign |
| 2667 | # |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2668 | # If the signs are the same then the exponent is used to select |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2669 | # the result. This is exactly the ordering used in compare_total. |
| 2670 | c = self.compare_total(other) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2671 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2672 | if c == -1: |
| 2673 | ans = other |
| 2674 | else: |
| 2675 | ans = self |
| 2676 | |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 2677 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2678 | |
| 2679 | def min(self, other, context=None): |
| 2680 | """Returns the smaller value. |
| 2681 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2682 | Like min(self, other) except if one is not a number, returns |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2683 | NaN (and signals if one is sNaN). Also rounds. |
| 2684 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2685 | other = _convert_other(other, raiseit=True) |
| 2686 | |
| 2687 | if context is None: |
| 2688 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2689 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2690 | if self._is_special or other._is_special: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2691 | # 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] | 2692 | # number is always returned |
| 2693 | sn = self._isnan() |
| 2694 | on = other._isnan() |
| 2695 | if sn or on: |
| 2696 | if on == 1 and sn != 2: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2697 | return self._fix_nan(context) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2698 | if sn == 1 and on != 2: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2699 | return other._fix_nan(context) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2700 | return self._check_nans(other, context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2701 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 2702 | c = self._cmp(other) |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2703 | if c == 0: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2704 | c = self.compare_total(other) |
| 2705 | |
| 2706 | if c == -1: |
| 2707 | ans = self |
| 2708 | else: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2709 | ans = other |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2710 | |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 2711 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2712 | |
| 2713 | def _isinteger(self): |
| 2714 | """Returns whether self is an integer""" |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2715 | if self._is_special: |
| 2716 | return False |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2717 | if self._exp >= 0: |
| 2718 | return True |
| 2719 | rest = self._int[self._exp:] |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2720 | return rest == '0'*len(rest) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2721 | |
| 2722 | def _iseven(self): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2723 | """Returns True if self is even. Assumes self is an integer.""" |
| 2724 | if not self or self._exp > 0: |
| 2725 | return True |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2726 | return self._int[-1+self._exp] in '02468' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2727 | |
| 2728 | def adjusted(self): |
| 2729 | """Return the adjusted exponent of self""" |
| 2730 | try: |
| 2731 | return self._exp + len(self._int) - 1 |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2732 | # If NaN or Infinity, self._exp is string |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2733 | except TypeError: |
| 2734 | return 0 |
| 2735 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2736 | def canonical(self, context=None): |
| 2737 | """Returns the same Decimal object. |
| 2738 | |
| 2739 | As we do not have different encodings for the same number, the |
| 2740 | received object already is in its canonical form. |
| 2741 | """ |
| 2742 | return self |
| 2743 | |
| 2744 | def compare_signal(self, other, context=None): |
| 2745 | """Compares self to the other operand numerically. |
| 2746 | |
| 2747 | It's pretty much like compare(), but all NaNs signal, with signaling |
| 2748 | NaNs taking precedence over quiet NaNs. |
| 2749 | """ |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 2750 | other = _convert_other(other, raiseit = True) |
| 2751 | ans = self._compare_check_nans(other, context) |
| 2752 | if ans: |
| 2753 | return ans |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2754 | return self.compare(other, context=context) |
| 2755 | |
| 2756 | def compare_total(self, other): |
| 2757 | """Compares self to other using the abstract representations. |
| 2758 | |
| 2759 | This is not like the standard compare, which use their numerical |
| 2760 | value. Note that a total ordering is defined for all possible abstract |
| 2761 | representations. |
| 2762 | """ |
| 2763 | # if one is negative and the other is positive, it's easy |
| 2764 | if self._sign and not other._sign: |
| 2765 | return Dec_n1 |
| 2766 | if not self._sign and other._sign: |
| 2767 | return Dec_p1 |
| 2768 | sign = self._sign |
| 2769 | |
| 2770 | # let's handle both NaN types |
| 2771 | self_nan = self._isnan() |
| 2772 | other_nan = other._isnan() |
| 2773 | if self_nan or other_nan: |
| 2774 | if self_nan == other_nan: |
| 2775 | if self._int < other._int: |
| 2776 | if sign: |
| 2777 | return Dec_p1 |
| 2778 | else: |
| 2779 | return Dec_n1 |
| 2780 | if self._int > other._int: |
| 2781 | if sign: |
| 2782 | return Dec_n1 |
| 2783 | else: |
| 2784 | return Dec_p1 |
| 2785 | return Dec_0 |
| 2786 | |
| 2787 | if sign: |
| 2788 | if self_nan == 1: |
| 2789 | return Dec_n1 |
| 2790 | if other_nan == 1: |
| 2791 | return Dec_p1 |
| 2792 | if self_nan == 2: |
| 2793 | return Dec_n1 |
| 2794 | if other_nan == 2: |
| 2795 | return Dec_p1 |
| 2796 | else: |
| 2797 | if self_nan == 1: |
| 2798 | return Dec_p1 |
| 2799 | if other_nan == 1: |
| 2800 | return Dec_n1 |
| 2801 | if self_nan == 2: |
| 2802 | return Dec_p1 |
| 2803 | if other_nan == 2: |
| 2804 | return Dec_n1 |
| 2805 | |
| 2806 | if self < other: |
| 2807 | return Dec_n1 |
| 2808 | if self > other: |
| 2809 | return Dec_p1 |
| 2810 | |
| 2811 | if self._exp < other._exp: |
| 2812 | if sign: |
| 2813 | return Dec_p1 |
| 2814 | else: |
| 2815 | return Dec_n1 |
| 2816 | if self._exp > other._exp: |
| 2817 | if sign: |
| 2818 | return Dec_n1 |
| 2819 | else: |
| 2820 | return Dec_p1 |
| 2821 | return Dec_0 |
| 2822 | |
| 2823 | |
| 2824 | def compare_total_mag(self, other): |
| 2825 | """Compares self to other using abstract repr., ignoring sign. |
| 2826 | |
| 2827 | Like compare_total, but with operand's sign ignored and assumed to be 0. |
| 2828 | """ |
| 2829 | s = self.copy_abs() |
| 2830 | o = other.copy_abs() |
| 2831 | return s.compare_total(o) |
| 2832 | |
| 2833 | def copy_abs(self): |
| 2834 | """Returns a copy with the sign set to 0. """ |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2835 | return _dec_from_triple(0, self._int, self._exp, self._is_special) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2836 | |
| 2837 | def copy_negate(self): |
| 2838 | """Returns a copy with the sign inverted.""" |
| 2839 | if self._sign: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2840 | return _dec_from_triple(0, self._int, self._exp, self._is_special) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2841 | else: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2842 | return _dec_from_triple(1, self._int, self._exp, self._is_special) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2843 | |
| 2844 | def copy_sign(self, other): |
| 2845 | """Returns self with the sign of other.""" |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2846 | return _dec_from_triple(other._sign, self._int, |
| 2847 | self._exp, self._is_special) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2848 | |
| 2849 | def exp(self, context=None): |
| 2850 | """Returns e ** self.""" |
| 2851 | |
| 2852 | if context is None: |
| 2853 | context = getcontext() |
| 2854 | |
| 2855 | # exp(NaN) = NaN |
| 2856 | ans = self._check_nans(context=context) |
| 2857 | if ans: |
| 2858 | return ans |
| 2859 | |
| 2860 | # exp(-Infinity) = 0 |
| 2861 | if self._isinfinity() == -1: |
| 2862 | return Dec_0 |
| 2863 | |
| 2864 | # exp(0) = 1 |
| 2865 | if not self: |
| 2866 | return Dec_p1 |
| 2867 | |
| 2868 | # exp(Infinity) = Infinity |
| 2869 | if self._isinfinity() == 1: |
| 2870 | return Decimal(self) |
| 2871 | |
| 2872 | # the result is now guaranteed to be inexact (the true |
| 2873 | # mathematical result is transcendental). There's no need to |
| 2874 | # raise Rounded and Inexact here---they'll always be raised as |
| 2875 | # a result of the call to _fix. |
| 2876 | p = context.prec |
| 2877 | adj = self.adjusted() |
| 2878 | |
| 2879 | # we only need to do any computation for quite a small range |
| 2880 | # of adjusted exponents---for example, -29 <= adj <= 10 for |
| 2881 | # the default context. For smaller exponent the result is |
| 2882 | # indistinguishable from 1 at the given precision, while for |
| 2883 | # larger exponent the result either overflows or underflows. |
| 2884 | if self._sign == 0 and adj > len(str((context.Emax+1)*3)): |
| 2885 | # overflow |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2886 | ans = _dec_from_triple(0, '1', context.Emax+1) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2887 | elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)): |
| 2888 | # underflow to 0 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2889 | ans = _dec_from_triple(0, '1', context.Etiny()-1) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2890 | elif self._sign == 0 and adj < -p: |
| 2891 | # p+1 digits; final round will raise correct flags |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2892 | ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2893 | elif self._sign == 1 and adj < -p-1: |
| 2894 | # p+1 digits; final round will raise correct flags |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2895 | ans = _dec_from_triple(0, '9'*(p+1), -p-1) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2896 | # general case |
| 2897 | else: |
| 2898 | op = _WorkRep(self) |
| 2899 | c, e = op.int, op.exp |
| 2900 | if op.sign == 1: |
| 2901 | c = -c |
| 2902 | |
| 2903 | # compute correctly rounded result: increase precision by |
| 2904 | # 3 digits at a time until we get an unambiguously |
| 2905 | # roundable result |
| 2906 | extra = 3 |
| 2907 | while True: |
| 2908 | coeff, exp = _dexp(c, e, p+extra) |
| 2909 | if coeff % (5*10**(len(str(coeff))-p-1)): |
| 2910 | break |
| 2911 | extra += 3 |
| 2912 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2913 | ans = _dec_from_triple(0, str(coeff), exp) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2914 | |
| 2915 | # at this stage, ans should round correctly with *any* |
| 2916 | # rounding mode, not just with ROUND_HALF_EVEN |
| 2917 | context = context._shallow_copy() |
| 2918 | rounding = context._set_rounding(ROUND_HALF_EVEN) |
| 2919 | ans = ans._fix(context) |
| 2920 | context.rounding = rounding |
| 2921 | |
| 2922 | return ans |
| 2923 | |
| 2924 | def is_canonical(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2925 | """Return True if self is canonical; otherwise return False. |
| 2926 | |
| 2927 | Currently, the encoding of a Decimal instance is always |
| 2928 | canonical, so this method returns True for any Decimal. |
| 2929 | """ |
| 2930 | return True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2931 | |
| 2932 | def is_finite(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2933 | """Return True if self is finite; otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2934 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2935 | A Decimal instance is considered finite if it is neither |
| 2936 | infinite nor a NaN. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2937 | """ |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2938 | return not self._is_special |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2939 | |
| 2940 | def is_infinite(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2941 | """Return True if self is infinite; otherwise return False.""" |
| 2942 | return self._exp == 'F' |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2943 | |
| 2944 | def is_nan(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2945 | """Return True if self is a qNaN or sNaN; otherwise return False.""" |
| 2946 | return self._exp in ('n', 'N') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2947 | |
| 2948 | def is_normal(self, context=None): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2949 | """Return True if self is a normal number; otherwise return False.""" |
| 2950 | if self._is_special or not self: |
| 2951 | return False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2952 | if context is None: |
| 2953 | context = getcontext() |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2954 | return context.Emin <= self.adjusted() <= context.Emax |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2955 | |
| 2956 | def is_qnan(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2957 | """Return True if self is a quiet NaN; otherwise return False.""" |
| 2958 | return self._exp == 'n' |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2959 | |
| 2960 | def is_signed(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2961 | """Return True if self is negative; otherwise return False.""" |
| 2962 | return self._sign == 1 |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2963 | |
| 2964 | def is_snan(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2965 | """Return True if self is a signaling NaN; otherwise return False.""" |
| 2966 | return self._exp == 'N' |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2967 | |
| 2968 | def is_subnormal(self, context=None): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2969 | """Return True if self is subnormal; otherwise return False.""" |
| 2970 | if self._is_special or not self: |
| 2971 | return False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2972 | if context is None: |
| 2973 | context = getcontext() |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2974 | return self.adjusted() < context.Emin |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2975 | |
| 2976 | def is_zero(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2977 | """Return True if self is a zero; otherwise return False.""" |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2978 | return not self._is_special and self._int == '0' |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2979 | |
| 2980 | def _ln_exp_bound(self): |
| 2981 | """Compute a lower bound for the adjusted exponent of self.ln(). |
| 2982 | In other words, compute r such that self.ln() >= 10**r. Assumes |
| 2983 | that self is finite and positive and that self != 1. |
| 2984 | """ |
| 2985 | |
| 2986 | # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1 |
| 2987 | adj = self._exp + len(self._int) - 1 |
| 2988 | if adj >= 1: |
| 2989 | # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10) |
| 2990 | return len(str(adj*23//10)) - 1 |
| 2991 | if adj <= -2: |
| 2992 | # argument <= 0.1 |
| 2993 | return len(str((-1-adj)*23//10)) - 1 |
| 2994 | op = _WorkRep(self) |
| 2995 | c, e = op.int, op.exp |
| 2996 | if adj == 0: |
| 2997 | # 1 < self < 10 |
| 2998 | num = str(c-10**-e) |
| 2999 | den = str(c) |
| 3000 | return len(num) - len(den) - (num < den) |
| 3001 | # adj == -1, 0.1 <= self < 1 |
| 3002 | return e + len(str(10**-e - c)) - 1 |
| 3003 | |
| 3004 | |
| 3005 | def ln(self, context=None): |
| 3006 | """Returns the natural (base e) logarithm of self.""" |
| 3007 | |
| 3008 | if context is None: |
| 3009 | context = getcontext() |
| 3010 | |
| 3011 | # ln(NaN) = NaN |
| 3012 | ans = self._check_nans(context=context) |
| 3013 | if ans: |
| 3014 | return ans |
| 3015 | |
| 3016 | # ln(0.0) == -Infinity |
| 3017 | if not self: |
| 3018 | return negInf |
| 3019 | |
| 3020 | # ln(Infinity) = Infinity |
| 3021 | if self._isinfinity() == 1: |
| 3022 | return Inf |
| 3023 | |
| 3024 | # ln(1.0) == 0.0 |
| 3025 | if self == Dec_p1: |
| 3026 | return Dec_0 |
| 3027 | |
| 3028 | # ln(negative) raises InvalidOperation |
| 3029 | if self._sign == 1: |
| 3030 | return context._raise_error(InvalidOperation, |
| 3031 | 'ln of a negative value') |
| 3032 | |
| 3033 | # result is irrational, so necessarily inexact |
| 3034 | op = _WorkRep(self) |
| 3035 | c, e = op.int, op.exp |
| 3036 | p = context.prec |
| 3037 | |
| 3038 | # correctly rounded result: repeatedly increase precision by 3 |
| 3039 | # until we get an unambiguously roundable result |
| 3040 | places = p - self._ln_exp_bound() + 2 # at least p+3 places |
| 3041 | while True: |
| 3042 | coeff = _dlog(c, e, places) |
| 3043 | # assert len(str(abs(coeff)))-p >= 1 |
| 3044 | if coeff % (5*10**(len(str(abs(coeff)))-p-1)): |
| 3045 | break |
| 3046 | places += 3 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3047 | ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3048 | |
| 3049 | context = context._shallow_copy() |
| 3050 | rounding = context._set_rounding(ROUND_HALF_EVEN) |
| 3051 | ans = ans._fix(context) |
| 3052 | context.rounding = rounding |
| 3053 | return ans |
| 3054 | |
| 3055 | def _log10_exp_bound(self): |
| 3056 | """Compute a lower bound for the adjusted exponent of self.log10(). |
| 3057 | In other words, find r such that self.log10() >= 10**r. |
| 3058 | Assumes that self is finite and positive and that self != 1. |
| 3059 | """ |
| 3060 | |
| 3061 | # For x >= 10 or x < 0.1 we only need a bound on the integer |
| 3062 | # part of log10(self), and this comes directly from the |
| 3063 | # exponent of x. For 0.1 <= x <= 10 we use the inequalities |
| 3064 | # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| > |
| 3065 | # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0 |
| 3066 | |
| 3067 | adj = self._exp + len(self._int) - 1 |
| 3068 | if adj >= 1: |
| 3069 | # self >= 10 |
| 3070 | return len(str(adj))-1 |
| 3071 | if adj <= -2: |
| 3072 | # self < 0.1 |
| 3073 | return len(str(-1-adj))-1 |
| 3074 | op = _WorkRep(self) |
| 3075 | c, e = op.int, op.exp |
| 3076 | if adj == 0: |
| 3077 | # 1 < self < 10 |
| 3078 | num = str(c-10**-e) |
| 3079 | den = str(231*c) |
| 3080 | return len(num) - len(den) - (num < den) + 2 |
| 3081 | # adj == -1, 0.1 <= self < 1 |
| 3082 | num = str(10**-e-c) |
| 3083 | return len(num) + e - (num < "231") - 1 |
| 3084 | |
| 3085 | def log10(self, context=None): |
| 3086 | """Returns the base 10 logarithm of self.""" |
| 3087 | |
| 3088 | if context is None: |
| 3089 | context = getcontext() |
| 3090 | |
| 3091 | # log10(NaN) = NaN |
| 3092 | ans = self._check_nans(context=context) |
| 3093 | if ans: |
| 3094 | return ans |
| 3095 | |
| 3096 | # log10(0.0) == -Infinity |
| 3097 | if not self: |
| 3098 | return negInf |
| 3099 | |
| 3100 | # log10(Infinity) = Infinity |
| 3101 | if self._isinfinity() == 1: |
| 3102 | return Inf |
| 3103 | |
| 3104 | # log10(negative or -Infinity) raises InvalidOperation |
| 3105 | if self._sign == 1: |
| 3106 | return context._raise_error(InvalidOperation, |
| 3107 | 'log10 of a negative value') |
| 3108 | |
| 3109 | # log10(10**n) = n |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3110 | if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3111 | # answer may need rounding |
| 3112 | ans = Decimal(self._exp + len(self._int) - 1) |
| 3113 | else: |
| 3114 | # result is irrational, so necessarily inexact |
| 3115 | op = _WorkRep(self) |
| 3116 | c, e = op.int, op.exp |
| 3117 | p = context.prec |
| 3118 | |
| 3119 | # correctly rounded result: repeatedly increase precision |
| 3120 | # until result is unambiguously roundable |
| 3121 | places = p-self._log10_exp_bound()+2 |
| 3122 | while True: |
| 3123 | coeff = _dlog10(c, e, places) |
| 3124 | # assert len(str(abs(coeff)))-p >= 1 |
| 3125 | if coeff % (5*10**(len(str(abs(coeff)))-p-1)): |
| 3126 | break |
| 3127 | places += 3 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3128 | ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3129 | |
| 3130 | context = context._shallow_copy() |
| 3131 | rounding = context._set_rounding(ROUND_HALF_EVEN) |
| 3132 | ans = ans._fix(context) |
| 3133 | context.rounding = rounding |
| 3134 | return ans |
| 3135 | |
| 3136 | def logb(self, context=None): |
| 3137 | """ Returns the exponent of the magnitude of self's MSD. |
| 3138 | |
| 3139 | The result is the integer which is the exponent of the magnitude |
| 3140 | of the most significant digit of self (as though it were truncated |
| 3141 | to a single digit while maintaining the value of that digit and |
| 3142 | without limiting the resulting exponent). |
| 3143 | """ |
| 3144 | # logb(NaN) = NaN |
| 3145 | ans = self._check_nans(context=context) |
| 3146 | if ans: |
| 3147 | return ans |
| 3148 | |
| 3149 | if context is None: |
| 3150 | context = getcontext() |
| 3151 | |
| 3152 | # logb(+/-Inf) = +Inf |
| 3153 | if self._isinfinity(): |
| 3154 | return Inf |
| 3155 | |
| 3156 | # logb(0) = -Inf, DivisionByZero |
| 3157 | if not self: |
| 3158 | return context._raise_error(DivisionByZero, 'logb(0)', 1) |
| 3159 | |
| 3160 | # otherwise, simply return the adjusted exponent of self, as a |
| 3161 | # Decimal. Note that no attempt is made to fit the result |
| 3162 | # into the current context. |
| 3163 | return Decimal(self.adjusted()) |
| 3164 | |
| 3165 | def _islogical(self): |
| 3166 | """Return True if self is a logical operand. |
| 3167 | |
Christian Heimes | 679db4a | 2008-01-18 09:56:22 +0000 | [diff] [blame] | 3168 | For being logical, it must be a finite number with a sign of 0, |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3169 | an exponent of 0, and a coefficient whose digits must all be |
| 3170 | either 0 or 1. |
| 3171 | """ |
| 3172 | if self._sign != 0 or self._exp != 0: |
| 3173 | return False |
| 3174 | for dig in self._int: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3175 | if dig not in '01': |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3176 | return False |
| 3177 | return True |
| 3178 | |
| 3179 | def _fill_logical(self, context, opa, opb): |
| 3180 | dif = context.prec - len(opa) |
| 3181 | if dif > 0: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3182 | opa = '0'*dif + opa |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3183 | elif dif < 0: |
| 3184 | opa = opa[-context.prec:] |
| 3185 | dif = context.prec - len(opb) |
| 3186 | if dif > 0: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3187 | opb = '0'*dif + opb |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3188 | elif dif < 0: |
| 3189 | opb = opb[-context.prec:] |
| 3190 | return opa, opb |
| 3191 | |
| 3192 | def logical_and(self, other, context=None): |
| 3193 | """Applies an 'and' operation between self and other's digits.""" |
| 3194 | if context is None: |
| 3195 | context = getcontext() |
| 3196 | if not self._islogical() or not other._islogical(): |
| 3197 | return context._raise_error(InvalidOperation) |
| 3198 | |
| 3199 | # fill to context.prec |
| 3200 | (opa, opb) = self._fill_logical(context, self._int, other._int) |
| 3201 | |
| 3202 | # make the operation, and clean starting zeroes |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3203 | result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)]) |
| 3204 | return _dec_from_triple(0, result.lstrip('0') or '0', 0) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3205 | |
| 3206 | def logical_invert(self, context=None): |
| 3207 | """Invert all its digits.""" |
| 3208 | if context is None: |
| 3209 | context = getcontext() |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3210 | return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0), |
| 3211 | context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3212 | |
| 3213 | def logical_or(self, other, context=None): |
| 3214 | """Applies an 'or' operation between self and other's digits.""" |
| 3215 | if context is None: |
| 3216 | context = getcontext() |
| 3217 | if not self._islogical() or not other._islogical(): |
| 3218 | return context._raise_error(InvalidOperation) |
| 3219 | |
| 3220 | # fill to context.prec |
| 3221 | (opa, opb) = self._fill_logical(context, self._int, other._int) |
| 3222 | |
| 3223 | # make the operation, and clean starting zeroes |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3224 | result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb)) |
| 3225 | return _dec_from_triple(0, result.lstrip('0') or '0', 0) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3226 | |
| 3227 | def logical_xor(self, other, context=None): |
| 3228 | """Applies an 'xor' operation between self and other's digits.""" |
| 3229 | if context is None: |
| 3230 | context = getcontext() |
| 3231 | if not self._islogical() or not other._islogical(): |
| 3232 | return context._raise_error(InvalidOperation) |
| 3233 | |
| 3234 | # fill to context.prec |
| 3235 | (opa, opb) = self._fill_logical(context, self._int, other._int) |
| 3236 | |
| 3237 | # make the operation, and clean starting zeroes |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3238 | result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb)) |
| 3239 | return _dec_from_triple(0, result.lstrip('0') or '0', 0) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3240 | |
| 3241 | def max_mag(self, other, context=None): |
| 3242 | """Compares the values numerically with their sign ignored.""" |
| 3243 | other = _convert_other(other, raiseit=True) |
| 3244 | |
| 3245 | if context is None: |
| 3246 | context = getcontext() |
| 3247 | |
| 3248 | if self._is_special or other._is_special: |
| 3249 | # If one operand is a quiet NaN and the other is number, then the |
| 3250 | # number is always returned |
| 3251 | sn = self._isnan() |
| 3252 | on = other._isnan() |
| 3253 | if sn or on: |
| 3254 | if on == 1 and sn != 2: |
| 3255 | return self._fix_nan(context) |
| 3256 | if sn == 1 and on != 2: |
| 3257 | return other._fix_nan(context) |
| 3258 | return self._check_nans(other, context) |
| 3259 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 3260 | c = self.copy_abs()._cmp(other.copy_abs()) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3261 | if c == 0: |
| 3262 | c = self.compare_total(other) |
| 3263 | |
| 3264 | if c == -1: |
| 3265 | ans = other |
| 3266 | else: |
| 3267 | ans = self |
| 3268 | |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 3269 | return ans._fix(context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3270 | |
| 3271 | def min_mag(self, other, context=None): |
| 3272 | """Compares the values numerically with their sign ignored.""" |
| 3273 | other = _convert_other(other, raiseit=True) |
| 3274 | |
| 3275 | if context is None: |
| 3276 | context = getcontext() |
| 3277 | |
| 3278 | if self._is_special or other._is_special: |
| 3279 | # If one operand is a quiet NaN and the other is number, then the |
| 3280 | # number is always returned |
| 3281 | sn = self._isnan() |
| 3282 | on = other._isnan() |
| 3283 | if sn or on: |
| 3284 | if on == 1 and sn != 2: |
| 3285 | return self._fix_nan(context) |
| 3286 | if sn == 1 and on != 2: |
| 3287 | return other._fix_nan(context) |
| 3288 | return self._check_nans(other, context) |
| 3289 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 3290 | c = self.copy_abs()._cmp(other.copy_abs()) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3291 | if c == 0: |
| 3292 | c = self.compare_total(other) |
| 3293 | |
| 3294 | if c == -1: |
| 3295 | ans = self |
| 3296 | else: |
| 3297 | ans = other |
| 3298 | |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 3299 | return ans._fix(context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3300 | |
| 3301 | def next_minus(self, context=None): |
| 3302 | """Returns the largest representable number smaller than itself.""" |
| 3303 | if context is None: |
| 3304 | context = getcontext() |
| 3305 | |
| 3306 | ans = self._check_nans(context=context) |
| 3307 | if ans: |
| 3308 | return ans |
| 3309 | |
| 3310 | if self._isinfinity() == -1: |
| 3311 | return negInf |
| 3312 | if self._isinfinity() == 1: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3313 | return _dec_from_triple(0, '9'*context.prec, context.Etop()) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3314 | |
| 3315 | context = context.copy() |
| 3316 | context._set_rounding(ROUND_FLOOR) |
| 3317 | context._ignore_all_flags() |
| 3318 | new_self = self._fix(context) |
| 3319 | if new_self != self: |
| 3320 | return new_self |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3321 | return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1), |
| 3322 | context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3323 | |
| 3324 | def next_plus(self, context=None): |
| 3325 | """Returns the smallest representable number larger than itself.""" |
| 3326 | if context is None: |
| 3327 | context = getcontext() |
| 3328 | |
| 3329 | ans = self._check_nans(context=context) |
| 3330 | if ans: |
| 3331 | return ans |
| 3332 | |
| 3333 | if self._isinfinity() == 1: |
| 3334 | return Inf |
| 3335 | if self._isinfinity() == -1: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3336 | return _dec_from_triple(1, '9'*context.prec, context.Etop()) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3337 | |
| 3338 | context = context.copy() |
| 3339 | context._set_rounding(ROUND_CEILING) |
| 3340 | context._ignore_all_flags() |
| 3341 | new_self = self._fix(context) |
| 3342 | if new_self != self: |
| 3343 | return new_self |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3344 | return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1), |
| 3345 | context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3346 | |
| 3347 | def next_toward(self, other, context=None): |
| 3348 | """Returns the number closest to self, in the direction towards other. |
| 3349 | |
| 3350 | The result is the closest representable number to self |
| 3351 | (excluding self) that is in the direction towards other, |
| 3352 | unless both have the same value. If the two operands are |
| 3353 | numerically equal, then the result is a copy of self with the |
| 3354 | sign set to be the same as the sign of other. |
| 3355 | """ |
| 3356 | other = _convert_other(other, raiseit=True) |
| 3357 | |
| 3358 | if context is None: |
| 3359 | context = getcontext() |
| 3360 | |
| 3361 | ans = self._check_nans(other, context) |
| 3362 | if ans: |
| 3363 | return ans |
| 3364 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 3365 | comparison = self._cmp(other) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3366 | if comparison == 0: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3367 | return self.copy_sign(other) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3368 | |
| 3369 | if comparison == -1: |
| 3370 | ans = self.next_plus(context) |
| 3371 | else: # comparison == 1 |
| 3372 | ans = self.next_minus(context) |
| 3373 | |
| 3374 | # decide which flags to raise using value of ans |
| 3375 | if ans._isinfinity(): |
| 3376 | context._raise_error(Overflow, |
| 3377 | 'Infinite result from next_toward', |
| 3378 | ans._sign) |
| 3379 | context._raise_error(Rounded) |
| 3380 | context._raise_error(Inexact) |
| 3381 | elif ans.adjusted() < context.Emin: |
| 3382 | context._raise_error(Underflow) |
| 3383 | context._raise_error(Subnormal) |
| 3384 | context._raise_error(Rounded) |
| 3385 | context._raise_error(Inexact) |
| 3386 | # if precision == 1 then we don't raise Clamped for a |
| 3387 | # result 0E-Etiny. |
| 3388 | if not ans: |
| 3389 | context._raise_error(Clamped) |
| 3390 | |
| 3391 | return ans |
| 3392 | |
| 3393 | def number_class(self, context=None): |
| 3394 | """Returns an indication of the class of self. |
| 3395 | |
| 3396 | The class is one of the following strings: |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 3397 | sNaN |
| 3398 | NaN |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3399 | -Infinity |
| 3400 | -Normal |
| 3401 | -Subnormal |
| 3402 | -Zero |
| 3403 | +Zero |
| 3404 | +Subnormal |
| 3405 | +Normal |
| 3406 | +Infinity |
| 3407 | """ |
| 3408 | if self.is_snan(): |
| 3409 | return "sNaN" |
| 3410 | if self.is_qnan(): |
| 3411 | return "NaN" |
| 3412 | inf = self._isinfinity() |
| 3413 | if inf == 1: |
| 3414 | return "+Infinity" |
| 3415 | if inf == -1: |
| 3416 | return "-Infinity" |
| 3417 | if self.is_zero(): |
| 3418 | if self._sign: |
| 3419 | return "-Zero" |
| 3420 | else: |
| 3421 | return "+Zero" |
| 3422 | if context is None: |
| 3423 | context = getcontext() |
| 3424 | if self.is_subnormal(context=context): |
| 3425 | if self._sign: |
| 3426 | return "-Subnormal" |
| 3427 | else: |
| 3428 | return "+Subnormal" |
| 3429 | # just a normal, regular, boring number, :) |
| 3430 | if self._sign: |
| 3431 | return "-Normal" |
| 3432 | else: |
| 3433 | return "+Normal" |
| 3434 | |
| 3435 | def radix(self): |
| 3436 | """Just returns 10, as this is Decimal, :)""" |
| 3437 | return Decimal(10) |
| 3438 | |
| 3439 | def rotate(self, other, context=None): |
| 3440 | """Returns a rotated copy of self, value-of-other times.""" |
| 3441 | if context is None: |
| 3442 | context = getcontext() |
| 3443 | |
| 3444 | ans = self._check_nans(other, context) |
| 3445 | if ans: |
| 3446 | return ans |
| 3447 | |
| 3448 | if other._exp != 0: |
| 3449 | return context._raise_error(InvalidOperation) |
| 3450 | if not (-context.prec <= int(other) <= context.prec): |
| 3451 | return context._raise_error(InvalidOperation) |
| 3452 | |
| 3453 | if self._isinfinity(): |
| 3454 | return Decimal(self) |
| 3455 | |
| 3456 | # get values, pad if necessary |
| 3457 | torot = int(other) |
| 3458 | rotdig = self._int |
| 3459 | topad = context.prec - len(rotdig) |
| 3460 | if topad: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3461 | rotdig = '0'*topad + rotdig |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3462 | |
| 3463 | # let's rotate! |
| 3464 | rotated = rotdig[torot:] + rotdig[:torot] |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3465 | return _dec_from_triple(self._sign, |
| 3466 | rotated.lstrip('0') or '0', self._exp) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3467 | |
| 3468 | def scaleb (self, other, context=None): |
| 3469 | """Returns self operand after adding the second value to its exp.""" |
| 3470 | if context is None: |
| 3471 | context = getcontext() |
| 3472 | |
| 3473 | ans = self._check_nans(other, context) |
| 3474 | if ans: |
| 3475 | return ans |
| 3476 | |
| 3477 | if other._exp != 0: |
| 3478 | return context._raise_error(InvalidOperation) |
| 3479 | liminf = -2 * (context.Emax + context.prec) |
| 3480 | limsup = 2 * (context.Emax + context.prec) |
| 3481 | if not (liminf <= int(other) <= limsup): |
| 3482 | return context._raise_error(InvalidOperation) |
| 3483 | |
| 3484 | if self._isinfinity(): |
| 3485 | return Decimal(self) |
| 3486 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3487 | d = _dec_from_triple(self._sign, self._int, self._exp + int(other)) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3488 | d = d._fix(context) |
| 3489 | return d |
| 3490 | |
| 3491 | def shift(self, other, context=None): |
| 3492 | """Returns a shifted copy of self, value-of-other times.""" |
| 3493 | if context is None: |
| 3494 | context = getcontext() |
| 3495 | |
| 3496 | ans = self._check_nans(other, context) |
| 3497 | if ans: |
| 3498 | return ans |
| 3499 | |
| 3500 | if other._exp != 0: |
| 3501 | return context._raise_error(InvalidOperation) |
| 3502 | if not (-context.prec <= int(other) <= context.prec): |
| 3503 | return context._raise_error(InvalidOperation) |
| 3504 | |
| 3505 | if self._isinfinity(): |
| 3506 | return Decimal(self) |
| 3507 | |
| 3508 | # get values, pad if necessary |
| 3509 | torot = int(other) |
| 3510 | if not torot: |
| 3511 | return Decimal(self) |
| 3512 | rotdig = self._int |
| 3513 | topad = context.prec - len(rotdig) |
| 3514 | if topad: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3515 | rotdig = '0'*topad + rotdig |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3516 | |
| 3517 | # let's shift! |
| 3518 | if torot < 0: |
| 3519 | rotated = rotdig[:torot] |
| 3520 | else: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3521 | rotated = rotdig + '0'*torot |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3522 | rotated = rotated[-context.prec:] |
| 3523 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3524 | return _dec_from_triple(self._sign, |
| 3525 | rotated.lstrip('0') or '0', self._exp) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3526 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3527 | # Support for pickling, copy, and deepcopy |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3528 | def __reduce__(self): |
| 3529 | return (self.__class__, (str(self),)) |
| 3530 | |
| 3531 | def __copy__(self): |
| 3532 | if type(self) == Decimal: |
| 3533 | return self # I'm immutable; therefore I am my own clone |
| 3534 | return self.__class__(str(self)) |
| 3535 | |
| 3536 | def __deepcopy__(self, memo): |
| 3537 | if type(self) == Decimal: |
| 3538 | return self # My components are also immutable |
| 3539 | return self.__class__(str(self)) |
| 3540 | |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3541 | # PEP 3101 support. See also _parse_format_specifier and _format_align |
| 3542 | def __format__(self, specifier, context=None): |
| 3543 | """Format a Decimal instance according to the given specifier. |
| 3544 | |
| 3545 | The specifier should be a standard format specifier, with the |
| 3546 | form described in PEP 3101. Formatting types 'e', 'E', 'f', |
| 3547 | 'F', 'g', 'G', and '%' are supported. If the formatting type |
| 3548 | is omitted it defaults to 'g' or 'G', depending on the value |
| 3549 | of context.capitals. |
| 3550 | |
| 3551 | At this time the 'n' format specifier type (which is supposed |
| 3552 | to use the current locale) is not supported. |
| 3553 | """ |
| 3554 | |
| 3555 | # Note: PEP 3101 says that if the type is not present then |
| 3556 | # there should be at least one digit after the decimal point. |
| 3557 | # We take the liberty of ignoring this requirement for |
| 3558 | # Decimal---it's presumably there to make sure that |
| 3559 | # format(float, '') behaves similarly to str(float). |
| 3560 | if context is None: |
| 3561 | context = getcontext() |
| 3562 | |
| 3563 | spec = _parse_format_specifier(specifier) |
| 3564 | |
| 3565 | # special values don't care about the type or precision... |
| 3566 | if self._is_special: |
| 3567 | return _format_align(str(self), spec) |
| 3568 | |
| 3569 | # a type of None defaults to 'g' or 'G', depending on context |
| 3570 | # if type is '%', adjust exponent of self accordingly |
| 3571 | if spec['type'] is None: |
| 3572 | spec['type'] = ['g', 'G'][context.capitals] |
| 3573 | elif spec['type'] == '%': |
| 3574 | self = _dec_from_triple(self._sign, self._int, self._exp+2) |
| 3575 | |
| 3576 | # round if necessary, taking rounding mode from the context |
| 3577 | rounding = context.rounding |
| 3578 | precision = spec['precision'] |
| 3579 | if precision is not None: |
| 3580 | if spec['type'] in 'eE': |
| 3581 | self = self._round(precision+1, rounding) |
| 3582 | elif spec['type'] in 'gG': |
| 3583 | if len(self._int) > precision: |
| 3584 | self = self._round(precision, rounding) |
| 3585 | elif spec['type'] in 'fF%': |
| 3586 | self = self._rescale(-precision, rounding) |
| 3587 | # special case: zeros with a positive exponent can't be |
| 3588 | # represented in fixed point; rescale them to 0e0. |
| 3589 | elif not self and self._exp > 0 and spec['type'] in 'fF%': |
| 3590 | self = self._rescale(0, rounding) |
| 3591 | |
| 3592 | # figure out placement of the decimal point |
| 3593 | leftdigits = self._exp + len(self._int) |
| 3594 | if spec['type'] in 'fF%': |
| 3595 | dotplace = leftdigits |
| 3596 | elif spec['type'] in 'eE': |
| 3597 | if not self and precision is not None: |
| 3598 | dotplace = 1 - precision |
| 3599 | else: |
| 3600 | dotplace = 1 |
| 3601 | elif spec['type'] in 'gG': |
| 3602 | if self._exp <= 0 and leftdigits > -6: |
| 3603 | dotplace = leftdigits |
| 3604 | else: |
| 3605 | dotplace = 1 |
| 3606 | |
| 3607 | # figure out main part of numeric string... |
| 3608 | if dotplace <= 0: |
| 3609 | num = '0.' + '0'*(-dotplace) + self._int |
| 3610 | elif dotplace >= len(self._int): |
| 3611 | # make sure we're not padding a '0' with extra zeros on the right |
| 3612 | assert dotplace==len(self._int) or self._int != '0' |
| 3613 | num = self._int + '0'*(dotplace-len(self._int)) |
| 3614 | else: |
| 3615 | num = self._int[:dotplace] + '.' + self._int[dotplace:] |
| 3616 | |
| 3617 | # ...then the trailing exponent, or trailing '%' |
| 3618 | if leftdigits != dotplace or spec['type'] in 'eE': |
| 3619 | echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']] |
| 3620 | num = num + "{0}{1:+}".format(echar, leftdigits-dotplace) |
| 3621 | elif spec['type'] == '%': |
| 3622 | num = num + '%' |
| 3623 | |
| 3624 | # add sign |
| 3625 | if self._sign == 1: |
| 3626 | num = '-' + num |
| 3627 | return _format_align(num, spec) |
| 3628 | |
| 3629 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3630 | def _dec_from_triple(sign, coefficient, exponent, special=False): |
| 3631 | """Create a decimal instance directly, without any validation, |
| 3632 | normalization (e.g. removal of leading zeros) or argument |
| 3633 | conversion. |
| 3634 | |
| 3635 | This function is for *internal use only*. |
| 3636 | """ |
| 3637 | |
| 3638 | self = object.__new__(Decimal) |
| 3639 | self._sign = sign |
| 3640 | self._int = coefficient |
| 3641 | self._exp = exponent |
| 3642 | self._is_special = special |
| 3643 | |
| 3644 | return self |
| 3645 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3646 | ##### Context class ####################################################### |
Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 3647 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3648 | |
| 3649 | # get rounding method function: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3650 | rounding_functions = [name for name in Decimal.__dict__.keys() |
| 3651 | if name.startswith('_round_')] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3652 | for name in rounding_functions: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3653 | # 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] | 3654 | globalname = name[1:].upper() |
| 3655 | val = globals()[globalname] |
| 3656 | Decimal._pick_rounding_function[val] = name |
| 3657 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3658 | del name, val, globalname, rounding_functions |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3659 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 3660 | class _ContextManager(object): |
| 3661 | """Context manager class to support localcontext(). |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 3662 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 3663 | Sets a copy of the supplied context in __enter__() and restores |
| 3664 | the previous decimal context in __exit__() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 3665 | """ |
| 3666 | def __init__(self, new_context): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 3667 | self.new_context = new_context.copy() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 3668 | def __enter__(self): |
| 3669 | self.saved_context = getcontext() |
| 3670 | setcontext(self.new_context) |
| 3671 | return self.new_context |
| 3672 | def __exit__(self, t, v, tb): |
| 3673 | setcontext(self.saved_context) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 3674 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3675 | class Context(object): |
| 3676 | """Contains the context for a Decimal instance. |
| 3677 | |
| 3678 | Contains: |
| 3679 | prec - precision (for use in rounding, division, square roots..) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3680 | rounding - rounding type (how you round) |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3681 | traps - If traps[exception] = 1, then the exception is |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3682 | raised when it is caused. Otherwise, a value is |
| 3683 | substituted in. |
Raymond Hettinger | 86173da | 2008-02-01 20:38:12 +0000 | [diff] [blame] | 3684 | flags - When an exception is caused, flags[exception] is set. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3685 | (Whether or not the trap_enabler is set) |
| 3686 | Should be reset by user of Decimal instance. |
Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 3687 | Emin - Minimum exponent |
| 3688 | Emax - Maximum exponent |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3689 | capitals - If 1, 1*10^1 is printed as 1E+1. |
| 3690 | If 0, printed as 1e1 |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 3691 | _clamp - If 1, change exponents if too high (Default 0) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3692 | """ |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3693 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3694 | def __init__(self, prec=None, rounding=None, |
Raymond Hettinger | abf8a56 | 2004-10-12 09:12:16 +0000 | [diff] [blame] | 3695 | traps=None, flags=None, |
Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 3696 | Emin=None, Emax=None, |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 3697 | capitals=None, _clamp=0, |
Raymond Hettinger | abf8a56 | 2004-10-12 09:12:16 +0000 | [diff] [blame] | 3698 | _ignored_flags=None): |
| 3699 | if flags is None: |
| 3700 | flags = [] |
| 3701 | if _ignored_flags is None: |
| 3702 | _ignored_flags = [] |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3703 | if not isinstance(flags, dict): |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 3704 | flags = dict([(s, int(s in flags)) for s in _signals]) |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3705 | if traps is not None and not isinstance(traps, dict): |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 3706 | traps = dict([(s, int(s in traps)) for s in _signals]) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3707 | for name, val in locals().items(): |
| 3708 | if val is None: |
Raymond Hettinger | eb26084 | 2005-06-07 18:52:34 +0000 | [diff] [blame] | 3709 | setattr(self, name, _copy.copy(getattr(DefaultContext, name))) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3710 | else: |
| 3711 | setattr(self, name, val) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3712 | del self.self |
| 3713 | |
Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 3714 | def __repr__(self): |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3715 | """Show the current context.""" |
Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 3716 | s = [] |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3717 | s.append('Context(prec=%(prec)d, rounding=%(rounding)s, ' |
| 3718 | 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d' |
| 3719 | % vars(self)) |
| 3720 | names = [f.__name__ for f, v in self.flags.items() if v] |
| 3721 | s.append('flags=[' + ', '.join(names) + ']') |
| 3722 | names = [t.__name__ for t, v in self.traps.items() if v] |
| 3723 | s.append('traps=[' + ', '.join(names) + ']') |
Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 3724 | return ', '.join(s) + ')' |
| 3725 | |
Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 3726 | def clear_flags(self): |
| 3727 | """Reset all flags to zero""" |
| 3728 | for flag in self.flags: |
Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 3729 | self.flags[flag] = 0 |
Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 3730 | |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 3731 | def _shallow_copy(self): |
| 3732 | """Returns a shallow copy from self.""" |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 3733 | nc = Context(self.prec, self.rounding, self.traps, |
| 3734 | self.flags, self.Emin, self.Emax, |
| 3735 | self.capitals, self._clamp, self._ignored_flags) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3736 | return nc |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 3737 | |
| 3738 | def copy(self): |
| 3739 | """Returns a deep copy from self.""" |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3740 | nc = Context(self.prec, self.rounding, self.traps.copy(), |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 3741 | self.flags.copy(), self.Emin, self.Emax, |
| 3742 | self.capitals, self._clamp, self._ignored_flags) |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 3743 | return nc |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3744 | __copy__ = copy |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3745 | |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 3746 | def _raise_error(self, condition, explanation = None, *args): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3747 | """Handles an error |
| 3748 | |
| 3749 | If the flag is in _ignored_flags, returns the default response. |
Raymond Hettinger | 86173da | 2008-02-01 20:38:12 +0000 | [diff] [blame] | 3750 | Otherwise, it sets the flag, then, if the corresponding |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3751 | trap_enabler is set, it reaises the exception. Otherwise, it returns |
Raymond Hettinger | 86173da | 2008-02-01 20:38:12 +0000 | [diff] [blame] | 3752 | the default value after setting the flag. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3753 | """ |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 3754 | error = _condition_map.get(condition, condition) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3755 | if error in self._ignored_flags: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3756 | # Don't touch the flag |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3757 | return error().handle(self, *args) |
| 3758 | |
Raymond Hettinger | 86173da | 2008-02-01 20:38:12 +0000 | [diff] [blame] | 3759 | self.flags[error] = 1 |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3760 | if not self.traps[error]: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3761 | # The errors define how to handle themselves. |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 3762 | return condition().handle(self, *args) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3763 | |
| 3764 | # Errors should only be risked on copies of the context |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3765 | # self._ignored_flags = [] |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 3766 | raise error(explanation) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3767 | |
| 3768 | def _ignore_all_flags(self): |
| 3769 | """Ignore all flags, if they are raised""" |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 3770 | return self._ignore_flags(*_signals) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3771 | |
| 3772 | def _ignore_flags(self, *flags): |
| 3773 | """Ignore the flags, if they are raised""" |
| 3774 | # Do not mutate-- This way, copies of a context leave the original |
| 3775 | # alone. |
| 3776 | self._ignored_flags = (self._ignored_flags + list(flags)) |
| 3777 | return list(flags) |
| 3778 | |
| 3779 | def _regard_flags(self, *flags): |
| 3780 | """Stop ignoring the flags, if they are raised""" |
| 3781 | if flags and isinstance(flags[0], (tuple,list)): |
| 3782 | flags = flags[0] |
| 3783 | for flag in flags: |
| 3784 | self._ignored_flags.remove(flag) |
| 3785 | |
Nick Coghlan | d1abd25 | 2008-07-15 15:46:38 +0000 | [diff] [blame] | 3786 | # We inherit object.__hash__, so we must deny this explicitly |
| 3787 | __hash__ = None |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 3788 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3789 | def Etiny(self): |
| 3790 | """Returns Etiny (= Emin - prec + 1)""" |
| 3791 | return int(self.Emin - self.prec + 1) |
| 3792 | |
| 3793 | def Etop(self): |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 3794 | """Returns maximum exponent (= Emax - prec + 1)""" |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3795 | return int(self.Emax - self.prec + 1) |
| 3796 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3797 | def _set_rounding(self, type): |
| 3798 | """Sets the rounding type. |
| 3799 | |
| 3800 | Sets the rounding type, and returns the current (previous) |
| 3801 | rounding type. Often used like: |
| 3802 | |
| 3803 | context = context.copy() |
| 3804 | # so you don't change the calling context |
| 3805 | # if an error occurs in the middle. |
| 3806 | rounding = context._set_rounding(ROUND_UP) |
| 3807 | val = self.__sub__(other, context=context) |
| 3808 | context._set_rounding(rounding) |
| 3809 | |
| 3810 | This will make it round up for that operation. |
| 3811 | """ |
| 3812 | rounding = self.rounding |
| 3813 | self.rounding= type |
| 3814 | return rounding |
| 3815 | |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 3816 | def create_decimal(self, num='0'): |
Christian Heimes | a62da1d | 2008-01-12 19:39:10 +0000 | [diff] [blame] | 3817 | """Creates a new Decimal instance but using self as context. |
| 3818 | |
| 3819 | This method implements the to-number operation of the |
| 3820 | IBM Decimal specification.""" |
| 3821 | |
| 3822 | if isinstance(num, str) and num != num.strip(): |
| 3823 | return self._raise_error(ConversionSyntax, |
| 3824 | "no trailing or leading whitespace is " |
| 3825 | "permitted.") |
| 3826 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3827 | d = Decimal(num, context=self) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3828 | if d._isnan() and len(d._int) > self.prec - self._clamp: |
| 3829 | return self._raise_error(ConversionSyntax, |
| 3830 | "diagnostic info too long in NaN") |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 3831 | return d._fix(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3832 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3833 | # Methods |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3834 | def abs(self, a): |
| 3835 | """Returns the absolute value of the operand. |
| 3836 | |
| 3837 | If the operand is negative, the result is the same as using the minus |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3838 | operation on the operand. Otherwise, the result is the same as using |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3839 | the plus operation on the operand. |
| 3840 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3841 | >>> ExtendedContext.abs(Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3842 | Decimal('2.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3843 | >>> ExtendedContext.abs(Decimal('-100')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3844 | Decimal('100') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3845 | >>> ExtendedContext.abs(Decimal('101.5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3846 | Decimal('101.5') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3847 | >>> ExtendedContext.abs(Decimal('-101.5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3848 | Decimal('101.5') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3849 | """ |
| 3850 | return a.__abs__(context=self) |
| 3851 | |
| 3852 | def add(self, a, b): |
| 3853 | """Return the sum of the two operands. |
| 3854 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3855 | >>> ExtendedContext.add(Decimal('12'), Decimal('7.00')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3856 | Decimal('19.00') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3857 | >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3858 | Decimal('1.02E+4') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3859 | """ |
| 3860 | return a.__add__(b, context=self) |
| 3861 | |
| 3862 | def _apply(self, a): |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 3863 | return str(a._fix(self)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3864 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3865 | def canonical(self, a): |
| 3866 | """Returns the same Decimal object. |
| 3867 | |
| 3868 | As we do not have different encodings for the same number, the |
| 3869 | received object already is in its canonical form. |
| 3870 | |
| 3871 | >>> ExtendedContext.canonical(Decimal('2.50')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3872 | Decimal('2.50') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3873 | """ |
| 3874 | return a.canonical(context=self) |
| 3875 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3876 | def compare(self, a, b): |
| 3877 | """Compares values numerically. |
| 3878 | |
| 3879 | If the signs of the operands differ, a value representing each operand |
| 3880 | ('-1' if the operand is less than zero, '0' if the operand is zero or |
| 3881 | negative zero, or '1' if the operand is greater than zero) is used in |
| 3882 | place of that operand for the comparison instead of the actual |
| 3883 | operand. |
| 3884 | |
| 3885 | The comparison is then effected by subtracting the second operand from |
| 3886 | the first and then returning a value according to the result of the |
| 3887 | subtraction: '-1' if the result is less than zero, '0' if the result is |
| 3888 | zero or negative zero, or '1' if the result is greater than zero. |
| 3889 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3890 | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3891 | Decimal('-1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3892 | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3893 | Decimal('0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3894 | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3895 | Decimal('0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3896 | >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3897 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3898 | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3899 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3900 | >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3901 | Decimal('-1') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3902 | """ |
| 3903 | return a.compare(b, context=self) |
| 3904 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3905 | def compare_signal(self, a, b): |
| 3906 | """Compares the values of the two operands numerically. |
| 3907 | |
| 3908 | It's pretty much like compare(), but all NaNs signal, with signaling |
| 3909 | NaNs taking precedence over quiet NaNs. |
| 3910 | |
| 3911 | >>> c = ExtendedContext |
| 3912 | >>> c.compare_signal(Decimal('2.1'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3913 | Decimal('-1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3914 | >>> c.compare_signal(Decimal('2.1'), Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3915 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3916 | >>> c.flags[InvalidOperation] = 0 |
| 3917 | >>> print(c.flags[InvalidOperation]) |
| 3918 | 0 |
| 3919 | >>> c.compare_signal(Decimal('NaN'), Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3920 | Decimal('NaN') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3921 | >>> print(c.flags[InvalidOperation]) |
| 3922 | 1 |
| 3923 | >>> c.flags[InvalidOperation] = 0 |
| 3924 | >>> print(c.flags[InvalidOperation]) |
| 3925 | 0 |
| 3926 | >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3927 | Decimal('NaN') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3928 | >>> print(c.flags[InvalidOperation]) |
| 3929 | 1 |
| 3930 | """ |
| 3931 | return a.compare_signal(b, context=self) |
| 3932 | |
| 3933 | def compare_total(self, a, b): |
| 3934 | """Compares two operands using their abstract representation. |
| 3935 | |
| 3936 | This is not like the standard compare, which use their numerical |
| 3937 | value. Note that a total ordering is defined for all possible abstract |
| 3938 | representations. |
| 3939 | |
| 3940 | >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3941 | Decimal('-1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3942 | >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3943 | Decimal('-1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3944 | >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3945 | Decimal('-1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3946 | >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3947 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3948 | >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3949 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3950 | >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3951 | Decimal('-1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3952 | """ |
| 3953 | return a.compare_total(b) |
| 3954 | |
| 3955 | def compare_total_mag(self, a, b): |
| 3956 | """Compares two operands using their abstract representation ignoring sign. |
| 3957 | |
| 3958 | Like compare_total, but with operand's sign ignored and assumed to be 0. |
| 3959 | """ |
| 3960 | return a.compare_total_mag(b) |
| 3961 | |
| 3962 | def copy_abs(self, a): |
| 3963 | """Returns a copy of the operand with the sign set to 0. |
| 3964 | |
| 3965 | >>> ExtendedContext.copy_abs(Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3966 | Decimal('2.1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3967 | >>> ExtendedContext.copy_abs(Decimal('-100')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3968 | Decimal('100') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3969 | """ |
| 3970 | return a.copy_abs() |
| 3971 | |
| 3972 | def copy_decimal(self, a): |
| 3973 | """Returns a copy of the decimal objet. |
| 3974 | |
| 3975 | >>> ExtendedContext.copy_decimal(Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3976 | Decimal('2.1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3977 | >>> ExtendedContext.copy_decimal(Decimal('-1.00')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3978 | Decimal('-1.00') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3979 | """ |
| 3980 | return Decimal(a) |
| 3981 | |
| 3982 | def copy_negate(self, a): |
| 3983 | """Returns a copy of the operand with the sign inverted. |
| 3984 | |
| 3985 | >>> ExtendedContext.copy_negate(Decimal('101.5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3986 | Decimal('-101.5') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3987 | >>> ExtendedContext.copy_negate(Decimal('-101.5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3988 | Decimal('101.5') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3989 | """ |
| 3990 | return a.copy_negate() |
| 3991 | |
| 3992 | def copy_sign(self, a, b): |
| 3993 | """Copies the second operand's sign to the first one. |
| 3994 | |
| 3995 | In detail, it returns a copy of the first operand with the sign |
| 3996 | equal to the sign of the second operand. |
| 3997 | |
| 3998 | >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3999 | Decimal('1.50') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4000 | >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4001 | Decimal('1.50') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4002 | >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4003 | Decimal('-1.50') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4004 | >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4005 | Decimal('-1.50') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4006 | """ |
| 4007 | return a.copy_sign(b) |
| 4008 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4009 | def divide(self, a, b): |
| 4010 | """Decimal division in a specified context. |
| 4011 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4012 | >>> ExtendedContext.divide(Decimal('1'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4013 | Decimal('0.333333333') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4014 | >>> ExtendedContext.divide(Decimal('2'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4015 | Decimal('0.666666667') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4016 | >>> ExtendedContext.divide(Decimal('5'), Decimal('2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4017 | Decimal('2.5') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4018 | >>> ExtendedContext.divide(Decimal('1'), Decimal('10')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4019 | Decimal('0.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4020 | >>> ExtendedContext.divide(Decimal('12'), Decimal('12')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4021 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4022 | >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4023 | Decimal('4.00') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4024 | >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4025 | Decimal('1.20') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4026 | >>> ExtendedContext.divide(Decimal('1000'), Decimal('100')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4027 | Decimal('10') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4028 | >>> ExtendedContext.divide(Decimal('1000'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4029 | Decimal('1000') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4030 | >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4031 | Decimal('1.20E+6') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4032 | """ |
Neal Norwitz | bcc0db8 | 2006-03-24 08:14:36 +0000 | [diff] [blame] | 4033 | return a.__truediv__(b, context=self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4034 | |
| 4035 | def divide_int(self, a, b): |
| 4036 | """Divides two numbers and returns the integer part of the result. |
| 4037 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4038 | >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4039 | Decimal('0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4040 | >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4041 | Decimal('3') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4042 | >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4043 | Decimal('3') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4044 | """ |
| 4045 | return a.__floordiv__(b, context=self) |
| 4046 | |
| 4047 | def divmod(self, a, b): |
| 4048 | return a.__divmod__(b, context=self) |
| 4049 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4050 | def exp(self, a): |
| 4051 | """Returns e ** a. |
| 4052 | |
| 4053 | >>> c = ExtendedContext.copy() |
| 4054 | >>> c.Emin = -999 |
| 4055 | >>> c.Emax = 999 |
| 4056 | >>> c.exp(Decimal('-Infinity')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4057 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4058 | >>> c.exp(Decimal('-1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4059 | Decimal('0.367879441') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4060 | >>> c.exp(Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4061 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4062 | >>> c.exp(Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4063 | Decimal('2.71828183') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4064 | >>> c.exp(Decimal('0.693147181')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4065 | Decimal('2.00000000') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4066 | >>> c.exp(Decimal('+Infinity')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4067 | Decimal('Infinity') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4068 | """ |
| 4069 | return a.exp(context=self) |
| 4070 | |
| 4071 | def fma(self, a, b, c): |
| 4072 | """Returns a multiplied by b, plus c. |
| 4073 | |
| 4074 | The first two operands are multiplied together, using multiply, |
| 4075 | the third operand is then added to the result of that |
| 4076 | multiplication, using add, all with only one final rounding. |
| 4077 | |
| 4078 | >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4079 | Decimal('22') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4080 | >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4081 | Decimal('-8') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4082 | >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4083 | Decimal('1.38435736E+12') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4084 | """ |
| 4085 | return a.fma(b, c, context=self) |
| 4086 | |
| 4087 | def is_canonical(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4088 | """Return True if the operand is canonical; otherwise return False. |
| 4089 | |
| 4090 | Currently, the encoding of a Decimal instance is always |
| 4091 | canonical, so this method returns True for any Decimal. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4092 | |
| 4093 | >>> ExtendedContext.is_canonical(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4094 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4095 | """ |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4096 | return a.is_canonical() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4097 | |
| 4098 | def is_finite(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4099 | """Return True if the operand is finite; otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4100 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4101 | A Decimal instance is considered finite if it is neither |
| 4102 | infinite nor a NaN. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4103 | |
| 4104 | >>> ExtendedContext.is_finite(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4105 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4106 | >>> ExtendedContext.is_finite(Decimal('-0.3')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4107 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4108 | >>> ExtendedContext.is_finite(Decimal('0')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4109 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4110 | >>> ExtendedContext.is_finite(Decimal('Inf')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4111 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4112 | >>> ExtendedContext.is_finite(Decimal('NaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4113 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4114 | """ |
| 4115 | return a.is_finite() |
| 4116 | |
| 4117 | def is_infinite(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4118 | """Return True if the operand is infinite; otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4119 | |
| 4120 | >>> ExtendedContext.is_infinite(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4121 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4122 | >>> ExtendedContext.is_infinite(Decimal('-Inf')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4123 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4124 | >>> ExtendedContext.is_infinite(Decimal('NaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4125 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4126 | """ |
| 4127 | return a.is_infinite() |
| 4128 | |
| 4129 | def is_nan(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4130 | """Return True if the operand is a qNaN or sNaN; |
| 4131 | otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4132 | |
| 4133 | >>> ExtendedContext.is_nan(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4134 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4135 | >>> ExtendedContext.is_nan(Decimal('NaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4136 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4137 | >>> ExtendedContext.is_nan(Decimal('-sNaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4138 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4139 | """ |
| 4140 | return a.is_nan() |
| 4141 | |
| 4142 | def is_normal(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4143 | """Return True if the operand is a normal number; |
| 4144 | otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4145 | |
| 4146 | >>> c = ExtendedContext.copy() |
| 4147 | >>> c.Emin = -999 |
| 4148 | >>> c.Emax = 999 |
| 4149 | >>> c.is_normal(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4150 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4151 | >>> c.is_normal(Decimal('0.1E-999')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4152 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4153 | >>> c.is_normal(Decimal('0.00')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4154 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4155 | >>> c.is_normal(Decimal('-Inf')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4156 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4157 | >>> c.is_normal(Decimal('NaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4158 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4159 | """ |
| 4160 | return a.is_normal(context=self) |
| 4161 | |
| 4162 | def is_qnan(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4163 | """Return True if the operand is a quiet NaN; otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4164 | |
| 4165 | >>> ExtendedContext.is_qnan(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4166 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4167 | >>> ExtendedContext.is_qnan(Decimal('NaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4168 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4169 | >>> ExtendedContext.is_qnan(Decimal('sNaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4170 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4171 | """ |
| 4172 | return a.is_qnan() |
| 4173 | |
| 4174 | def is_signed(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4175 | """Return True if the operand is negative; otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4176 | |
| 4177 | >>> ExtendedContext.is_signed(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4178 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4179 | >>> ExtendedContext.is_signed(Decimal('-12')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4180 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4181 | >>> ExtendedContext.is_signed(Decimal('-0')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4182 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4183 | """ |
| 4184 | return a.is_signed() |
| 4185 | |
| 4186 | def is_snan(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4187 | """Return True if the operand is a signaling NaN; |
| 4188 | otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4189 | |
| 4190 | >>> ExtendedContext.is_snan(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4191 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4192 | >>> ExtendedContext.is_snan(Decimal('NaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4193 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4194 | >>> ExtendedContext.is_snan(Decimal('sNaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4195 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4196 | """ |
| 4197 | return a.is_snan() |
| 4198 | |
| 4199 | def is_subnormal(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4200 | """Return True if the operand is subnormal; otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4201 | |
| 4202 | >>> c = ExtendedContext.copy() |
| 4203 | >>> c.Emin = -999 |
| 4204 | >>> c.Emax = 999 |
| 4205 | >>> c.is_subnormal(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4206 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4207 | >>> c.is_subnormal(Decimal('0.1E-999')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4208 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4209 | >>> c.is_subnormal(Decimal('0.00')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4210 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4211 | >>> c.is_subnormal(Decimal('-Inf')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4212 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4213 | >>> c.is_subnormal(Decimal('NaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4214 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4215 | """ |
| 4216 | return a.is_subnormal(context=self) |
| 4217 | |
| 4218 | def is_zero(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4219 | """Return True if the operand is a zero; otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4220 | |
| 4221 | >>> ExtendedContext.is_zero(Decimal('0')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4222 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4223 | >>> ExtendedContext.is_zero(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4224 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4225 | >>> ExtendedContext.is_zero(Decimal('-0E+2')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4226 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4227 | """ |
| 4228 | return a.is_zero() |
| 4229 | |
| 4230 | def ln(self, a): |
| 4231 | """Returns the natural (base e) logarithm of the operand. |
| 4232 | |
| 4233 | >>> c = ExtendedContext.copy() |
| 4234 | >>> c.Emin = -999 |
| 4235 | >>> c.Emax = 999 |
| 4236 | >>> c.ln(Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4237 | Decimal('-Infinity') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4238 | >>> c.ln(Decimal('1.000')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4239 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4240 | >>> c.ln(Decimal('2.71828183')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4241 | Decimal('1.00000000') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4242 | >>> c.ln(Decimal('10')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4243 | Decimal('2.30258509') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4244 | >>> c.ln(Decimal('+Infinity')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4245 | Decimal('Infinity') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4246 | """ |
| 4247 | return a.ln(context=self) |
| 4248 | |
| 4249 | def log10(self, a): |
| 4250 | """Returns the base 10 logarithm of the operand. |
| 4251 | |
| 4252 | >>> c = ExtendedContext.copy() |
| 4253 | >>> c.Emin = -999 |
| 4254 | >>> c.Emax = 999 |
| 4255 | >>> c.log10(Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4256 | Decimal('-Infinity') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4257 | >>> c.log10(Decimal('0.001')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4258 | Decimal('-3') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4259 | >>> c.log10(Decimal('1.000')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4260 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4261 | >>> c.log10(Decimal('2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4262 | Decimal('0.301029996') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4263 | >>> c.log10(Decimal('10')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4264 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4265 | >>> c.log10(Decimal('70')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4266 | Decimal('1.84509804') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4267 | >>> c.log10(Decimal('+Infinity')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4268 | Decimal('Infinity') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4269 | """ |
| 4270 | return a.log10(context=self) |
| 4271 | |
| 4272 | def logb(self, a): |
| 4273 | """ Returns the exponent of the magnitude of the operand's MSD. |
| 4274 | |
| 4275 | The result is the integer which is the exponent of the magnitude |
| 4276 | of the most significant digit of the operand (as though the |
| 4277 | operand were truncated to a single digit while maintaining the |
| 4278 | value of that digit and without limiting the resulting exponent). |
| 4279 | |
| 4280 | >>> ExtendedContext.logb(Decimal('250')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4281 | Decimal('2') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4282 | >>> ExtendedContext.logb(Decimal('2.50')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4283 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4284 | >>> ExtendedContext.logb(Decimal('0.03')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4285 | Decimal('-2') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4286 | >>> ExtendedContext.logb(Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4287 | Decimal('-Infinity') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4288 | """ |
| 4289 | return a.logb(context=self) |
| 4290 | |
| 4291 | def logical_and(self, a, b): |
| 4292 | """Applies the logical operation 'and' between each operand's digits. |
| 4293 | |
| 4294 | The operands must be both logical numbers. |
| 4295 | |
| 4296 | >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4297 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4298 | >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4299 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4300 | >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4301 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4302 | >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4303 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4304 | >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4305 | Decimal('1000') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4306 | >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4307 | Decimal('10') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4308 | """ |
| 4309 | return a.logical_and(b, context=self) |
| 4310 | |
| 4311 | def logical_invert(self, a): |
| 4312 | """Invert all the digits in the operand. |
| 4313 | |
| 4314 | The operand must be a logical number. |
| 4315 | |
| 4316 | >>> ExtendedContext.logical_invert(Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4317 | Decimal('111111111') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4318 | >>> ExtendedContext.logical_invert(Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4319 | Decimal('111111110') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4320 | >>> ExtendedContext.logical_invert(Decimal('111111111')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4321 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4322 | >>> ExtendedContext.logical_invert(Decimal('101010101')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4323 | Decimal('10101010') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4324 | """ |
| 4325 | return a.logical_invert(context=self) |
| 4326 | |
| 4327 | def logical_or(self, a, b): |
| 4328 | """Applies the logical operation 'or' between each operand's digits. |
| 4329 | |
| 4330 | The operands must be both logical numbers. |
| 4331 | |
| 4332 | >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4333 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4334 | >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4335 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4336 | >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4337 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4338 | >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4339 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4340 | >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4341 | Decimal('1110') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4342 | >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4343 | Decimal('1110') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4344 | """ |
| 4345 | return a.logical_or(b, context=self) |
| 4346 | |
| 4347 | def logical_xor(self, a, b): |
| 4348 | """Applies the logical operation 'xor' between each operand's digits. |
| 4349 | |
| 4350 | The operands must be both logical numbers. |
| 4351 | |
| 4352 | >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4353 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4354 | >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4355 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4356 | >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4357 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4358 | >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4359 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4360 | >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4361 | Decimal('110') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4362 | >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4363 | Decimal('1101') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4364 | """ |
| 4365 | return a.logical_xor(b, context=self) |
| 4366 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4367 | def max(self, a,b): |
| 4368 | """max compares two values numerically and returns the maximum. |
| 4369 | |
| 4370 | If either operand is a NaN then the general rules apply. |
Christian Heimes | 679db4a | 2008-01-18 09:56:22 +0000 | [diff] [blame] | 4371 | Otherwise, the operands are compared as though by the compare |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 4372 | operation. If they are numerically equal then the left-hand operand |
| 4373 | is chosen as the result. Otherwise the maximum (closer to positive |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4374 | infinity) of the two operands is chosen as the result. |
| 4375 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4376 | >>> ExtendedContext.max(Decimal('3'), Decimal('2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4377 | Decimal('3') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4378 | >>> ExtendedContext.max(Decimal('-10'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4379 | Decimal('3') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4380 | >>> ExtendedContext.max(Decimal('1.0'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4381 | Decimal('1') |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 4382 | >>> ExtendedContext.max(Decimal('7'), Decimal('NaN')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4383 | Decimal('7') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4384 | """ |
| 4385 | return a.max(b, context=self) |
| 4386 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4387 | def max_mag(self, a, b): |
| 4388 | """Compares the values numerically with their sign ignored.""" |
| 4389 | return a.max_mag(b, context=self) |
| 4390 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4391 | def min(self, a,b): |
| 4392 | """min compares two values numerically and returns the minimum. |
| 4393 | |
| 4394 | If either operand is a NaN then the general rules apply. |
Christian Heimes | 679db4a | 2008-01-18 09:56:22 +0000 | [diff] [blame] | 4395 | Otherwise, the operands are compared as though by the compare |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 4396 | operation. If they are numerically equal then the left-hand operand |
| 4397 | is chosen as the result. Otherwise the minimum (closer to negative |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4398 | infinity) of the two operands is chosen as the result. |
| 4399 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4400 | >>> ExtendedContext.min(Decimal('3'), Decimal('2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4401 | Decimal('2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4402 | >>> ExtendedContext.min(Decimal('-10'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4403 | Decimal('-10') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4404 | >>> ExtendedContext.min(Decimal('1.0'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4405 | Decimal('1.0') |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 4406 | >>> ExtendedContext.min(Decimal('7'), Decimal('NaN')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4407 | Decimal('7') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4408 | """ |
| 4409 | return a.min(b, context=self) |
| 4410 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4411 | def min_mag(self, a, b): |
| 4412 | """Compares the values numerically with their sign ignored.""" |
| 4413 | return a.min_mag(b, context=self) |
| 4414 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4415 | def minus(self, a): |
| 4416 | """Minus corresponds to unary prefix minus in Python. |
| 4417 | |
| 4418 | The operation is evaluated using the same rules as subtract; the |
| 4419 | operation minus(a) is calculated as subtract('0', a) where the '0' |
| 4420 | has the same exponent as the operand. |
| 4421 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4422 | >>> ExtendedContext.minus(Decimal('1.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4423 | Decimal('-1.3') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4424 | >>> ExtendedContext.minus(Decimal('-1.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4425 | Decimal('1.3') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4426 | """ |
| 4427 | return a.__neg__(context=self) |
| 4428 | |
| 4429 | def multiply(self, a, b): |
| 4430 | """multiply multiplies two operands. |
| 4431 | |
| 4432 | If either operand is a special value then the general rules apply. |
| 4433 | Otherwise, the operands are multiplied together ('long multiplication'), |
| 4434 | resulting in a number which may be as long as the sum of the lengths |
| 4435 | of the two operands. |
| 4436 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4437 | >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4438 | Decimal('3.60') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4439 | >>> ExtendedContext.multiply(Decimal('7'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4440 | Decimal('21') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4441 | >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4442 | Decimal('0.72') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4443 | >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4444 | Decimal('-0.0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4445 | >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4446 | Decimal('4.28135971E+11') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4447 | """ |
| 4448 | return a.__mul__(b, context=self) |
| 4449 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4450 | def next_minus(self, a): |
| 4451 | """Returns the largest representable number smaller than a. |
| 4452 | |
| 4453 | >>> c = ExtendedContext.copy() |
| 4454 | >>> c.Emin = -999 |
| 4455 | >>> c.Emax = 999 |
| 4456 | >>> ExtendedContext.next_minus(Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4457 | Decimal('0.999999999') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4458 | >>> c.next_minus(Decimal('1E-1007')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4459 | Decimal('0E-1007') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4460 | >>> ExtendedContext.next_minus(Decimal('-1.00000003')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4461 | Decimal('-1.00000004') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4462 | >>> c.next_minus(Decimal('Infinity')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4463 | Decimal('9.99999999E+999') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4464 | """ |
| 4465 | return a.next_minus(context=self) |
| 4466 | |
| 4467 | def next_plus(self, a): |
| 4468 | """Returns the smallest representable number larger than a. |
| 4469 | |
| 4470 | >>> c = ExtendedContext.copy() |
| 4471 | >>> c.Emin = -999 |
| 4472 | >>> c.Emax = 999 |
| 4473 | >>> ExtendedContext.next_plus(Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4474 | Decimal('1.00000001') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4475 | >>> c.next_plus(Decimal('-1E-1007')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4476 | Decimal('-0E-1007') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4477 | >>> ExtendedContext.next_plus(Decimal('-1.00000003')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4478 | Decimal('-1.00000002') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4479 | >>> c.next_plus(Decimal('-Infinity')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4480 | Decimal('-9.99999999E+999') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4481 | """ |
| 4482 | return a.next_plus(context=self) |
| 4483 | |
| 4484 | def next_toward(self, a, b): |
| 4485 | """Returns the number closest to a, in direction towards b. |
| 4486 | |
| 4487 | The result is the closest representable number from the first |
| 4488 | operand (but not the first operand) that is in the direction |
| 4489 | towards the second operand, unless the operands have the same |
| 4490 | value. |
| 4491 | |
| 4492 | >>> c = ExtendedContext.copy() |
| 4493 | >>> c.Emin = -999 |
| 4494 | >>> c.Emax = 999 |
| 4495 | >>> c.next_toward(Decimal('1'), Decimal('2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4496 | Decimal('1.00000001') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4497 | >>> c.next_toward(Decimal('-1E-1007'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4498 | Decimal('-0E-1007') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4499 | >>> c.next_toward(Decimal('-1.00000003'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4500 | Decimal('-1.00000002') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4501 | >>> c.next_toward(Decimal('1'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4502 | Decimal('0.999999999') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4503 | >>> c.next_toward(Decimal('1E-1007'), Decimal('-100')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4504 | Decimal('0E-1007') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4505 | >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4506 | Decimal('-1.00000004') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4507 | >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4508 | Decimal('-0.00') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4509 | """ |
| 4510 | return a.next_toward(b, context=self) |
| 4511 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4512 | def normalize(self, a): |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 4513 | """normalize reduces an operand to its simplest form. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4514 | |
| 4515 | Essentially a plus operation with all trailing zeros removed from the |
| 4516 | result. |
| 4517 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4518 | >>> ExtendedContext.normalize(Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4519 | Decimal('2.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4520 | >>> ExtendedContext.normalize(Decimal('-2.0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4521 | Decimal('-2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4522 | >>> ExtendedContext.normalize(Decimal('1.200')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4523 | Decimal('1.2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4524 | >>> ExtendedContext.normalize(Decimal('-120')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4525 | Decimal('-1.2E+2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4526 | >>> ExtendedContext.normalize(Decimal('120.00')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4527 | Decimal('1.2E+2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4528 | >>> ExtendedContext.normalize(Decimal('0.00')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4529 | Decimal('0') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4530 | """ |
| 4531 | return a.normalize(context=self) |
| 4532 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4533 | def number_class(self, a): |
| 4534 | """Returns an indication of the class of the operand. |
| 4535 | |
| 4536 | The class is one of the following strings: |
| 4537 | -sNaN |
| 4538 | -NaN |
| 4539 | -Infinity |
| 4540 | -Normal |
| 4541 | -Subnormal |
| 4542 | -Zero |
| 4543 | +Zero |
| 4544 | +Subnormal |
| 4545 | +Normal |
| 4546 | +Infinity |
| 4547 | |
| 4548 | >>> c = Context(ExtendedContext) |
| 4549 | >>> c.Emin = -999 |
| 4550 | >>> c.Emax = 999 |
| 4551 | >>> c.number_class(Decimal('Infinity')) |
| 4552 | '+Infinity' |
| 4553 | >>> c.number_class(Decimal('1E-10')) |
| 4554 | '+Normal' |
| 4555 | >>> c.number_class(Decimal('2.50')) |
| 4556 | '+Normal' |
| 4557 | >>> c.number_class(Decimal('0.1E-999')) |
| 4558 | '+Subnormal' |
| 4559 | >>> c.number_class(Decimal('0')) |
| 4560 | '+Zero' |
| 4561 | >>> c.number_class(Decimal('-0')) |
| 4562 | '-Zero' |
| 4563 | >>> c.number_class(Decimal('-0.1E-999')) |
| 4564 | '-Subnormal' |
| 4565 | >>> c.number_class(Decimal('-1E-10')) |
| 4566 | '-Normal' |
| 4567 | >>> c.number_class(Decimal('-2.50')) |
| 4568 | '-Normal' |
| 4569 | >>> c.number_class(Decimal('-Infinity')) |
| 4570 | '-Infinity' |
| 4571 | >>> c.number_class(Decimal('NaN')) |
| 4572 | 'NaN' |
| 4573 | >>> c.number_class(Decimal('-NaN')) |
| 4574 | 'NaN' |
| 4575 | >>> c.number_class(Decimal('sNaN')) |
| 4576 | 'sNaN' |
| 4577 | """ |
| 4578 | return a.number_class(context=self) |
| 4579 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4580 | def plus(self, a): |
| 4581 | """Plus corresponds to unary prefix plus in Python. |
| 4582 | |
| 4583 | The operation is evaluated using the same rules as add; the |
| 4584 | operation plus(a) is calculated as add('0', a) where the '0' |
| 4585 | has the same exponent as the operand. |
| 4586 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4587 | >>> ExtendedContext.plus(Decimal('1.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4588 | Decimal('1.3') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4589 | >>> ExtendedContext.plus(Decimal('-1.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4590 | Decimal('-1.3') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4591 | """ |
| 4592 | return a.__pos__(context=self) |
| 4593 | |
| 4594 | def power(self, a, b, modulo=None): |
| 4595 | """Raises a to the power of b, to modulo if given. |
| 4596 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4597 | With two arguments, compute a**b. If a is negative then b |
| 4598 | must be integral. The result will be inexact unless b is |
| 4599 | integral and the result is finite and can be expressed exactly |
| 4600 | in 'precision' digits. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4601 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4602 | With three arguments, compute (a**b) % modulo. For the |
| 4603 | three argument form, the following restrictions on the |
| 4604 | arguments hold: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4605 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4606 | - all three arguments must be integral |
| 4607 | - b must be nonnegative |
| 4608 | - at least one of a or b must be nonzero |
| 4609 | - modulo must be nonzero and have at most 'precision' digits |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4610 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4611 | The result of pow(a, b, modulo) is identical to the result |
| 4612 | that would be obtained by computing (a**b) % modulo with |
| 4613 | unbounded precision, but is computed more efficiently. It is |
| 4614 | always exact. |
| 4615 | |
| 4616 | >>> c = ExtendedContext.copy() |
| 4617 | >>> c.Emin = -999 |
| 4618 | >>> c.Emax = 999 |
| 4619 | >>> c.power(Decimal('2'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4620 | Decimal('8') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4621 | >>> c.power(Decimal('-2'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4622 | Decimal('-8') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4623 | >>> c.power(Decimal('2'), Decimal('-3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4624 | Decimal('0.125') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4625 | >>> c.power(Decimal('1.7'), Decimal('8')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4626 | Decimal('69.7575744') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4627 | >>> c.power(Decimal('10'), Decimal('0.301029996')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4628 | Decimal('2.00000000') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4629 | >>> c.power(Decimal('Infinity'), Decimal('-1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4630 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4631 | >>> c.power(Decimal('Infinity'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4632 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4633 | >>> c.power(Decimal('Infinity'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4634 | Decimal('Infinity') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4635 | >>> c.power(Decimal('-Infinity'), Decimal('-1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4636 | Decimal('-0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4637 | >>> c.power(Decimal('-Infinity'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4638 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4639 | >>> c.power(Decimal('-Infinity'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4640 | Decimal('-Infinity') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4641 | >>> c.power(Decimal('-Infinity'), Decimal('2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4642 | Decimal('Infinity') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4643 | >>> c.power(Decimal('0'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4644 | Decimal('NaN') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4645 | |
| 4646 | >>> c.power(Decimal('3'), Decimal('7'), Decimal('16')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4647 | Decimal('11') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4648 | >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4649 | Decimal('-11') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4650 | >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4651 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4652 | >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4653 | Decimal('11') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4654 | >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4655 | Decimal('11729830') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4656 | >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4657 | Decimal('-0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4658 | >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4659 | Decimal('1') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4660 | """ |
| 4661 | return a.__pow__(b, modulo, context=self) |
| 4662 | |
| 4663 | def quantize(self, a, b): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 4664 | """Returns a value equal to 'a' (rounded), having the exponent of 'b'. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4665 | |
| 4666 | The coefficient of the result is derived from that of the left-hand |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 4667 | operand. It may be rounded using the current rounding setting (if the |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4668 | exponent is being increased), multiplied by a positive power of ten (if |
| 4669 | the exponent is being decreased), or is unchanged (if the exponent is |
| 4670 | already equal to that of the right-hand operand). |
| 4671 | |
| 4672 | Unlike other operations, if the length of the coefficient after the |
| 4673 | quantize operation would be greater than precision then an Invalid |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 4674 | operation condition is raised. This guarantees that, unless there is |
| 4675 | 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] | 4676 | equal to that of the right-hand operand. |
| 4677 | |
| 4678 | Also unlike other operations, quantize will never raise Underflow, even |
| 4679 | if the result is subnormal and inexact. |
| 4680 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4681 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4682 | Decimal('2.170') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4683 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4684 | Decimal('2.17') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4685 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4686 | Decimal('2.2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4687 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4688 | Decimal('2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4689 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4690 | Decimal('0E+1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4691 | >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4692 | Decimal('-Infinity') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4693 | >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4694 | Decimal('NaN') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4695 | >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4696 | Decimal('-0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4697 | >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4698 | Decimal('-0E+5') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4699 | >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4700 | Decimal('NaN') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4701 | >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4702 | Decimal('NaN') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4703 | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4704 | Decimal('217.0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4705 | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4706 | Decimal('217') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4707 | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4708 | Decimal('2.2E+2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4709 | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4710 | Decimal('2E+2') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4711 | """ |
| 4712 | return a.quantize(b, context=self) |
| 4713 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4714 | def radix(self): |
| 4715 | """Just returns 10, as this is Decimal, :) |
| 4716 | |
| 4717 | >>> ExtendedContext.radix() |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4718 | Decimal('10') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4719 | """ |
| 4720 | return Decimal(10) |
| 4721 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4722 | def remainder(self, a, b): |
| 4723 | """Returns the remainder from integer division. |
| 4724 | |
| 4725 | The result is the residue of the dividend after the operation of |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 4726 | calculating integer division as described for divide-integer, rounded |
| 4727 | to precision digits if necessary. The sign of the result, if |
| 4728 | non-zero, is the same as that of the original dividend. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4729 | |
| 4730 | This operation will fail under the same conditions as integer division |
| 4731 | (that is, if integer division on the same two operands would fail, the |
| 4732 | remainder cannot be calculated). |
| 4733 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4734 | >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4735 | Decimal('2.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4736 | >>> ExtendedContext.remainder(Decimal('10'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4737 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4738 | >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4739 | Decimal('-1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4740 | >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4741 | Decimal('0.2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4742 | >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4743 | Decimal('0.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4744 | >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4745 | Decimal('1.0') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4746 | """ |
| 4747 | return a.__mod__(b, context=self) |
| 4748 | |
| 4749 | def remainder_near(self, a, b): |
| 4750 | """Returns to be "a - b * n", where n is the integer nearest the exact |
| 4751 | value of "x / b" (if two integers are equally near then the even one |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 4752 | 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] | 4753 | sign of a. |
| 4754 | |
| 4755 | This operation will fail under the same conditions as integer division |
| 4756 | (that is, if integer division on the same two operands would fail, the |
| 4757 | remainder cannot be calculated). |
| 4758 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4759 | >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4760 | Decimal('-0.9') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4761 | >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4762 | Decimal('-2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4763 | >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4764 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4765 | >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4766 | Decimal('-1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4767 | >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4768 | Decimal('0.2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4769 | >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4770 | Decimal('0.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4771 | >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4772 | Decimal('-0.3') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4773 | """ |
| 4774 | return a.remainder_near(b, context=self) |
| 4775 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4776 | def rotate(self, a, b): |
| 4777 | """Returns a rotated copy of a, b times. |
| 4778 | |
| 4779 | The coefficient of the result is a rotated copy of the digits in |
| 4780 | the coefficient of the first operand. The number of places of |
| 4781 | rotation is taken from the absolute value of the second operand, |
| 4782 | with the rotation being to the left if the second operand is |
| 4783 | positive or to the right otherwise. |
| 4784 | |
| 4785 | >>> ExtendedContext.rotate(Decimal('34'), Decimal('8')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4786 | Decimal('400000003') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4787 | >>> ExtendedContext.rotate(Decimal('12'), Decimal('9')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4788 | Decimal('12') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4789 | >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4790 | Decimal('891234567') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4791 | >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4792 | Decimal('123456789') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4793 | >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4794 | Decimal('345678912') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4795 | """ |
| 4796 | return a.rotate(b, context=self) |
| 4797 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4798 | def same_quantum(self, a, b): |
| 4799 | """Returns True if the two operands have the same exponent. |
| 4800 | |
| 4801 | The result is never affected by either the sign or the coefficient of |
| 4802 | either operand. |
| 4803 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4804 | >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4805 | False |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4806 | >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4807 | True |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4808 | >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4809 | False |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4810 | >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4811 | True |
| 4812 | """ |
| 4813 | return a.same_quantum(b) |
| 4814 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4815 | def scaleb (self, a, b): |
| 4816 | """Returns the first operand after adding the second value its exp. |
| 4817 | |
| 4818 | >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4819 | Decimal('0.0750') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4820 | >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4821 | Decimal('7.50') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4822 | >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4823 | Decimal('7.50E+3') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4824 | """ |
| 4825 | return a.scaleb (b, context=self) |
| 4826 | |
| 4827 | def shift(self, a, b): |
| 4828 | """Returns a shifted copy of a, b times. |
| 4829 | |
| 4830 | The coefficient of the result is a shifted copy of the digits |
| 4831 | in the coefficient of the first operand. The number of places |
| 4832 | to shift is taken from the absolute value of the second operand, |
| 4833 | with the shift being to the left if the second operand is |
| 4834 | positive or to the right otherwise. Digits shifted into the |
| 4835 | coefficient are zeros. |
| 4836 | |
| 4837 | >>> ExtendedContext.shift(Decimal('34'), Decimal('8')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4838 | Decimal('400000000') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4839 | >>> ExtendedContext.shift(Decimal('12'), Decimal('9')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4840 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4841 | >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4842 | Decimal('1234567') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4843 | >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4844 | Decimal('123456789') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4845 | >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4846 | Decimal('345678900') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4847 | """ |
| 4848 | return a.shift(b, context=self) |
| 4849 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4850 | def sqrt(self, a): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 4851 | """Square root of a non-negative number to context precision. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4852 | |
| 4853 | If the result must be inexact, it is rounded using the round-half-even |
| 4854 | algorithm. |
| 4855 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4856 | >>> ExtendedContext.sqrt(Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4857 | Decimal('0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4858 | >>> ExtendedContext.sqrt(Decimal('-0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4859 | Decimal('-0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4860 | >>> ExtendedContext.sqrt(Decimal('0.39')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4861 | Decimal('0.624499800') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4862 | >>> ExtendedContext.sqrt(Decimal('100')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4863 | Decimal('10') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4864 | >>> ExtendedContext.sqrt(Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4865 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4866 | >>> ExtendedContext.sqrt(Decimal('1.0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4867 | Decimal('1.0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4868 | >>> ExtendedContext.sqrt(Decimal('1.00')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4869 | Decimal('1.0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4870 | >>> ExtendedContext.sqrt(Decimal('7')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4871 | Decimal('2.64575131') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4872 | >>> ExtendedContext.sqrt(Decimal('10')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4873 | Decimal('3.16227766') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4874 | >>> ExtendedContext.prec |
Raymond Hettinger | 6ea4845 | 2004-07-03 12:26:21 +0000 | [diff] [blame] | 4875 | 9 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4876 | """ |
| 4877 | return a.sqrt(context=self) |
| 4878 | |
| 4879 | def subtract(self, a, b): |
Georg Brandl | f33d01d | 2005-08-22 19:35:18 +0000 | [diff] [blame] | 4880 | """Return the difference between the two operands. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4881 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4882 | >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4883 | Decimal('0.23') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4884 | >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4885 | Decimal('0.00') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4886 | >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4887 | Decimal('-0.77') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4888 | """ |
| 4889 | return a.__sub__(b, context=self) |
| 4890 | |
| 4891 | def to_eng_string(self, a): |
| 4892 | """Converts a number to a string, using scientific notation. |
| 4893 | |
| 4894 | The operation is not affected by the context. |
| 4895 | """ |
| 4896 | return a.to_eng_string(context=self) |
| 4897 | |
| 4898 | def to_sci_string(self, a): |
| 4899 | """Converts a number to a string, using scientific notation. |
| 4900 | |
| 4901 | The operation is not affected by the context. |
| 4902 | """ |
| 4903 | return a.__str__(context=self) |
| 4904 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4905 | def to_integral_exact(self, a): |
| 4906 | """Rounds to an integer. |
| 4907 | |
| 4908 | When the operand has a negative exponent, the result is the same |
| 4909 | as using the quantize() operation using the given operand as the |
| 4910 | left-hand-operand, 1E+0 as the right-hand-operand, and the precision |
| 4911 | of the operand as the precision setting; Inexact and Rounded flags |
| 4912 | are allowed in this operation. The rounding mode is taken from the |
| 4913 | context. |
| 4914 | |
| 4915 | >>> ExtendedContext.to_integral_exact(Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4916 | Decimal('2') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4917 | >>> ExtendedContext.to_integral_exact(Decimal('100')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4918 | Decimal('100') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4919 | >>> ExtendedContext.to_integral_exact(Decimal('100.0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4920 | Decimal('100') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4921 | >>> ExtendedContext.to_integral_exact(Decimal('101.5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4922 | Decimal('102') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4923 | >>> ExtendedContext.to_integral_exact(Decimal('-101.5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4924 | Decimal('-102') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4925 | >>> ExtendedContext.to_integral_exact(Decimal('10E+5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4926 | Decimal('1.0E+6') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4927 | >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4928 | Decimal('7.89E+77') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4929 | >>> ExtendedContext.to_integral_exact(Decimal('-Inf')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4930 | Decimal('-Infinity') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4931 | """ |
| 4932 | return a.to_integral_exact(context=self) |
| 4933 | |
| 4934 | def to_integral_value(self, a): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4935 | """Rounds to an integer. |
| 4936 | |
| 4937 | When the operand has a negative exponent, the result is the same |
| 4938 | as using the quantize() operation using the given operand as the |
| 4939 | left-hand-operand, 1E+0 as the right-hand-operand, and the precision |
| 4940 | of the operand as the precision setting, except that no flags will |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 4941 | be set. The rounding mode is taken from the context. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4942 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4943 | >>> ExtendedContext.to_integral_value(Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4944 | Decimal('2') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4945 | >>> ExtendedContext.to_integral_value(Decimal('100')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4946 | Decimal('100') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4947 | >>> ExtendedContext.to_integral_value(Decimal('100.0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4948 | Decimal('100') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4949 | >>> ExtendedContext.to_integral_value(Decimal('101.5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4950 | Decimal('102') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4951 | >>> ExtendedContext.to_integral_value(Decimal('-101.5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4952 | Decimal('-102') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4953 | >>> ExtendedContext.to_integral_value(Decimal('10E+5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4954 | Decimal('1.0E+6') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4955 | >>> ExtendedContext.to_integral_value(Decimal('7.89E+77')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4956 | Decimal('7.89E+77') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4957 | >>> ExtendedContext.to_integral_value(Decimal('-Inf')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4958 | Decimal('-Infinity') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4959 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4960 | return a.to_integral_value(context=self) |
| 4961 | |
| 4962 | # the method name changed, but we provide also the old one, for compatibility |
| 4963 | to_integral = to_integral_value |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4964 | |
| 4965 | class _WorkRep(object): |
| 4966 | __slots__ = ('sign','int','exp') |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 4967 | # sign: 0 or 1 |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4968 | # int: int |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4969 | # exp: None, int, or string |
| 4970 | |
| 4971 | def __init__(self, value=None): |
| 4972 | if value is None: |
| 4973 | self.sign = None |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 4974 | self.int = 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4975 | self.exp = None |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 4976 | elif isinstance(value, Decimal): |
| 4977 | self.sign = value._sign |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 4978 | self.int = int(value._int) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4979 | self.exp = value._exp |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 4980 | else: |
| 4981 | # assert isinstance(value, tuple) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4982 | self.sign = value[0] |
| 4983 | self.int = value[1] |
| 4984 | self.exp = value[2] |
| 4985 | |
| 4986 | def __repr__(self): |
| 4987 | return "(%r, %r, %r)" % (self.sign, self.int, self.exp) |
| 4988 | |
| 4989 | __str__ = __repr__ |
| 4990 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4991 | |
| 4992 | |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 4993 | def _normalize(op1, op2, prec = 0): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4994 | """Normalizes op1, op2 to have the same exp and length of coefficient. |
| 4995 | |
| 4996 | Done during addition. |
| 4997 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4998 | if op1.exp < op2.exp: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4999 | tmp = op2 |
| 5000 | other = op1 |
| 5001 | else: |
| 5002 | tmp = op1 |
| 5003 | other = op2 |
| 5004 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5005 | # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1). |
| 5006 | # Then adding 10**exp to tmp has the same effect (after rounding) |
| 5007 | # as adding any positive quantity smaller than 10**exp; similarly |
| 5008 | # for subtraction. So if other is smaller than 10**exp we replace |
| 5009 | # it with 10**exp. This avoids tmp.exp - other.exp getting too large. |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 5010 | tmp_len = len(str(tmp.int)) |
| 5011 | other_len = len(str(other.int)) |
| 5012 | exp = tmp.exp + min(-1, tmp_len - prec - 2) |
| 5013 | if other_len + other.exp - 1 < exp: |
| 5014 | other.int = 1 |
| 5015 | other.exp = exp |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5016 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5017 | tmp.int *= 10 ** (tmp.exp - other.exp) |
| 5018 | tmp.exp = other.exp |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5019 | return op1, op2 |
| 5020 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5021 | ##### Integer arithmetic functions used by ln, log10, exp and __pow__ ##### |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5022 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5023 | # This function from Tim Peters was taken from here: |
| 5024 | # http://mail.python.org/pipermail/python-list/1999-July/007758.html |
| 5025 | # The correction being in the function definition is for speed, and |
| 5026 | # the whole function is not resolved with math.log because of avoiding |
| 5027 | # the use of floats. |
| 5028 | def _nbits(n, correction = { |
| 5029 | '0': 4, '1': 3, '2': 2, '3': 2, |
| 5030 | '4': 1, '5': 1, '6': 1, '7': 1, |
| 5031 | '8': 0, '9': 0, 'a': 0, 'b': 0, |
| 5032 | 'c': 0, 'd': 0, 'e': 0, 'f': 0}): |
| 5033 | """Number of bits in binary representation of the positive integer n, |
| 5034 | or 0 if n == 0. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5035 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5036 | if n < 0: |
| 5037 | raise ValueError("The argument to _nbits should be nonnegative.") |
| 5038 | hex_n = "%x" % n |
| 5039 | return 4*len(hex_n) - correction[hex_n[0]] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5040 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5041 | def _sqrt_nearest(n, a): |
| 5042 | """Closest integer to the square root of the positive integer n. a is |
| 5043 | an initial approximation to the square root. Any positive integer |
| 5044 | will do for a, but the closer a is to the square root of n the |
| 5045 | faster convergence will be. |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5046 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5047 | """ |
| 5048 | if n <= 0 or a <= 0: |
| 5049 | raise ValueError("Both arguments to _sqrt_nearest should be positive.") |
| 5050 | |
| 5051 | b=0 |
| 5052 | while a != b: |
| 5053 | b, a = a, a--n//a>>1 |
| 5054 | return a |
| 5055 | |
| 5056 | def _rshift_nearest(x, shift): |
| 5057 | """Given an integer x and a nonnegative integer shift, return closest |
| 5058 | integer to x / 2**shift; use round-to-even in case of a tie. |
| 5059 | |
| 5060 | """ |
| 5061 | b, q = 1 << shift, x >> shift |
| 5062 | return q + (2*(x & (b-1)) + (q&1) > b) |
| 5063 | |
| 5064 | def _div_nearest(a, b): |
| 5065 | """Closest integer to a/b, a and b positive integers; rounds to even |
| 5066 | in the case of a tie. |
| 5067 | |
| 5068 | """ |
| 5069 | q, r = divmod(a, b) |
| 5070 | return q + (2*r + (q&1) > b) |
| 5071 | |
| 5072 | def _ilog(x, M, L = 8): |
| 5073 | """Integer approximation to M*log(x/M), with absolute error boundable |
| 5074 | in terms only of x/M. |
| 5075 | |
| 5076 | Given positive integers x and M, return an integer approximation to |
| 5077 | M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference |
| 5078 | between the approximation and the exact result is at most 22. For |
| 5079 | L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In |
| 5080 | both cases these are upper bounds on the error; it will usually be |
| 5081 | much smaller.""" |
| 5082 | |
| 5083 | # The basic algorithm is the following: let log1p be the function |
| 5084 | # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use |
| 5085 | # the reduction |
| 5086 | # |
| 5087 | # log1p(y) = 2*log1p(y/(1+sqrt(1+y))) |
| 5088 | # |
| 5089 | # repeatedly until the argument to log1p is small (< 2**-L in |
| 5090 | # absolute value). For small y we can use the Taylor series |
| 5091 | # expansion |
| 5092 | # |
| 5093 | # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T |
| 5094 | # |
| 5095 | # truncating at T such that y**T is small enough. The whole |
| 5096 | # computation is carried out in a form of fixed-point arithmetic, |
| 5097 | # with a real number z being represented by an integer |
| 5098 | # approximation to z*M. To avoid loss of precision, the y below |
| 5099 | # is actually an integer approximation to 2**R*y*M, where R is the |
| 5100 | # number of reductions performed so far. |
| 5101 | |
| 5102 | y = x-M |
| 5103 | # argument reduction; R = number of reductions performed |
| 5104 | R = 0 |
| 5105 | while (R <= L and abs(y) << L-R >= M or |
| 5106 | R > L and abs(y) >> R-L >= M): |
| 5107 | y = _div_nearest((M*y) << 1, |
| 5108 | M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M)) |
| 5109 | R += 1 |
| 5110 | |
| 5111 | # Taylor series with T terms |
| 5112 | T = -int(-10*len(str(M))//(3*L)) |
| 5113 | yshift = _rshift_nearest(y, R) |
| 5114 | w = _div_nearest(M, T) |
| 5115 | for k in range(T-1, 0, -1): |
| 5116 | w = _div_nearest(M, k) - _div_nearest(yshift*w, M) |
| 5117 | |
| 5118 | return _div_nearest(w*y, M) |
| 5119 | |
| 5120 | def _dlog10(c, e, p): |
| 5121 | """Given integers c, e and p with c > 0, p >= 0, compute an integer |
| 5122 | approximation to 10**p * log10(c*10**e), with an absolute error of |
| 5123 | at most 1. Assumes that c*10**e is not exactly 1.""" |
| 5124 | |
| 5125 | # increase precision by 2; compensate for this by dividing |
| 5126 | # final result by 100 |
| 5127 | p += 2 |
| 5128 | |
| 5129 | # write c*10**e as d*10**f with either: |
| 5130 | # f >= 0 and 1 <= d <= 10, or |
| 5131 | # f <= 0 and 0.1 <= d <= 1. |
| 5132 | # Thus for c*10**e close to 1, f = 0 |
| 5133 | l = len(str(c)) |
| 5134 | f = e+l - (e+l >= 1) |
| 5135 | |
| 5136 | if p > 0: |
| 5137 | M = 10**p |
| 5138 | k = e+p-f |
| 5139 | if k >= 0: |
| 5140 | c *= 10**k |
| 5141 | else: |
| 5142 | c = _div_nearest(c, 10**-k) |
| 5143 | |
| 5144 | log_d = _ilog(c, M) # error < 5 + 22 = 27 |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5145 | log_10 = _log10_digits(p) # error < 1 |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5146 | log_d = _div_nearest(log_d*M, log_10) |
| 5147 | log_tenpower = f*M # exact |
| 5148 | else: |
| 5149 | log_d = 0 # error < 2.31 |
| 5150 | log_tenpower = div_nearest(f, 10**-p) # error < 0.5 |
| 5151 | |
| 5152 | return _div_nearest(log_tenpower+log_d, 100) |
| 5153 | |
| 5154 | def _dlog(c, e, p): |
| 5155 | """Given integers c, e and p with c > 0, compute an integer |
| 5156 | approximation to 10**p * log(c*10**e), with an absolute error of |
| 5157 | at most 1. Assumes that c*10**e is not exactly 1.""" |
| 5158 | |
| 5159 | # Increase precision by 2. The precision increase is compensated |
| 5160 | # for at the end with a division by 100. |
| 5161 | p += 2 |
| 5162 | |
| 5163 | # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10, |
| 5164 | # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e) |
| 5165 | # as 10**p * log(d) + 10**p*f * log(10). |
| 5166 | l = len(str(c)) |
| 5167 | f = e+l - (e+l >= 1) |
| 5168 | |
| 5169 | # compute approximation to 10**p*log(d), with error < 27 |
| 5170 | if p > 0: |
| 5171 | k = e+p-f |
| 5172 | if k >= 0: |
| 5173 | c *= 10**k |
| 5174 | else: |
| 5175 | c = _div_nearest(c, 10**-k) # error of <= 0.5 in c |
| 5176 | |
| 5177 | # _ilog magnifies existing error in c by a factor of at most 10 |
| 5178 | log_d = _ilog(c, 10**p) # error < 5 + 22 = 27 |
| 5179 | else: |
| 5180 | # p <= 0: just approximate the whole thing by 0; error < 2.31 |
| 5181 | log_d = 0 |
| 5182 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5183 | # compute approximation to f*10**p*log(10), with error < 11. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5184 | if f: |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5185 | extra = len(str(abs(f)))-1 |
| 5186 | if p + extra >= 0: |
| 5187 | # error in f * _log10_digits(p+extra) < |f| * 1 = |f| |
| 5188 | # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11 |
| 5189 | f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5190 | else: |
| 5191 | f_log_ten = 0 |
| 5192 | else: |
| 5193 | f_log_ten = 0 |
| 5194 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5195 | # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1 |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5196 | return _div_nearest(f_log_ten + log_d, 100) |
| 5197 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5198 | class _Log10Memoize(object): |
| 5199 | """Class to compute, store, and allow retrieval of, digits of the |
| 5200 | constant log(10) = 2.302585.... This constant is needed by |
| 5201 | Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__.""" |
| 5202 | def __init__(self): |
| 5203 | self.digits = "23025850929940456840179914546843642076011014886" |
| 5204 | |
| 5205 | def getdigits(self, p): |
| 5206 | """Given an integer p >= 0, return floor(10**p)*log(10). |
| 5207 | |
| 5208 | For example, self.getdigits(3) returns 2302. |
| 5209 | """ |
| 5210 | # digits are stored as a string, for quick conversion to |
| 5211 | # integer in the case that we've already computed enough |
| 5212 | # digits; the stored digits should always be correct |
| 5213 | # (truncated, not rounded to nearest). |
| 5214 | if p < 0: |
| 5215 | raise ValueError("p should be nonnegative") |
| 5216 | |
| 5217 | if p >= len(self.digits): |
| 5218 | # compute p+3, p+6, p+9, ... digits; continue until at |
| 5219 | # least one of the extra digits is nonzero |
| 5220 | extra = 3 |
| 5221 | while True: |
| 5222 | # compute p+extra digits, correct to within 1ulp |
| 5223 | M = 10**(p+extra+2) |
| 5224 | digits = str(_div_nearest(_ilog(10*M, M), 100)) |
| 5225 | if digits[-extra:] != '0'*extra: |
| 5226 | break |
| 5227 | extra += 3 |
| 5228 | # keep all reliable digits so far; remove trailing zeros |
| 5229 | # and next nonzero digit |
| 5230 | self.digits = digits.rstrip('0')[:-1] |
| 5231 | return int(self.digits[:p+1]) |
| 5232 | |
| 5233 | _log10_digits = _Log10Memoize().getdigits |
| 5234 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5235 | def _iexp(x, M, L=8): |
| 5236 | """Given integers x and M, M > 0, such that x/M is small in absolute |
| 5237 | value, compute an integer approximation to M*exp(x/M). For 0 <= |
| 5238 | x/M <= 2.4, the absolute error in the result is bounded by 60 (and |
| 5239 | is usually much smaller).""" |
| 5240 | |
| 5241 | # Algorithm: to compute exp(z) for a real number z, first divide z |
| 5242 | # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then |
| 5243 | # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor |
| 5244 | # series |
| 5245 | # |
| 5246 | # expm1(x) = x + x**2/2! + x**3/3! + ... |
| 5247 | # |
| 5248 | # Now use the identity |
| 5249 | # |
| 5250 | # expm1(2x) = expm1(x)*(expm1(x)+2) |
| 5251 | # |
| 5252 | # R times to compute the sequence expm1(z/2**R), |
| 5253 | # expm1(z/2**(R-1)), ... , exp(z/2), exp(z). |
| 5254 | |
| 5255 | # Find R such that x/2**R/M <= 2**-L |
| 5256 | R = _nbits((x<<L)//M) |
| 5257 | |
| 5258 | # Taylor series. (2**L)**T > M |
| 5259 | T = -int(-10*len(str(M))//(3*L)) |
| 5260 | y = _div_nearest(x, T) |
| 5261 | Mshift = M<<R |
| 5262 | for i in range(T-1, 0, -1): |
| 5263 | y = _div_nearest(x*(Mshift + y), Mshift * i) |
| 5264 | |
| 5265 | # Expansion |
| 5266 | for k in range(R-1, -1, -1): |
| 5267 | Mshift = M<<(k+2) |
| 5268 | y = _div_nearest(y*(y+Mshift), Mshift) |
| 5269 | |
| 5270 | return M+y |
| 5271 | |
| 5272 | def _dexp(c, e, p): |
| 5273 | """Compute an approximation to exp(c*10**e), with p decimal places of |
| 5274 | precision. |
| 5275 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5276 | Returns integers d, f such that: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5277 | |
| 5278 | 10**(p-1) <= d <= 10**p, and |
| 5279 | (d-1)*10**f < exp(c*10**e) < (d+1)*10**f |
| 5280 | |
| 5281 | In other words, d*10**f is an approximation to exp(c*10**e) with p |
| 5282 | digits of precision, and with an error in d of at most 1. This is |
| 5283 | almost, but not quite, the same as the error being < 1ulp: when d |
| 5284 | = 10**(p-1) the error could be up to 10 ulp.""" |
| 5285 | |
| 5286 | # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision |
| 5287 | p += 2 |
| 5288 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5289 | # compute log(10) with extra precision = adjusted exponent of c*10**e |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5290 | extra = max(0, e + len(str(c)) - 1) |
| 5291 | q = p + extra |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5292 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5293 | # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q), |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5294 | # rounding down |
| 5295 | shift = e+q |
| 5296 | if shift >= 0: |
| 5297 | cshift = c*10**shift |
| 5298 | else: |
| 5299 | cshift = c//10**-shift |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5300 | quot, rem = divmod(cshift, _log10_digits(q)) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5301 | |
| 5302 | # reduce remainder back to original precision |
| 5303 | rem = _div_nearest(rem, 10**extra) |
| 5304 | |
| 5305 | # error in result of _iexp < 120; error after division < 0.62 |
| 5306 | return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3 |
| 5307 | |
| 5308 | def _dpower(xc, xe, yc, ye, p): |
| 5309 | """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and |
| 5310 | y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that: |
| 5311 | |
| 5312 | 10**(p-1) <= c <= 10**p, and |
| 5313 | (c-1)*10**e < x**y < (c+1)*10**e |
| 5314 | |
| 5315 | in other words, c*10**e is an approximation to x**y with p digits |
| 5316 | of precision, and with an error in c of at most 1. (This is |
| 5317 | almost, but not quite, the same as the error being < 1ulp: when c |
| 5318 | == 10**(p-1) we can only guarantee error < 10ulp.) |
| 5319 | |
| 5320 | We assume that: x is positive and not equal to 1, and y is nonzero. |
| 5321 | """ |
| 5322 | |
| 5323 | # Find b such that 10**(b-1) <= |y| <= 10**b |
| 5324 | b = len(str(abs(yc))) + ye |
| 5325 | |
| 5326 | # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point |
| 5327 | lxc = _dlog(xc, xe, p+b+1) |
| 5328 | |
| 5329 | # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1) |
| 5330 | shift = ye-b |
| 5331 | if shift >= 0: |
| 5332 | pc = lxc*yc*10**shift |
| 5333 | else: |
| 5334 | pc = _div_nearest(lxc*yc, 10**-shift) |
| 5335 | |
| 5336 | if pc == 0: |
| 5337 | # we prefer a result that isn't exactly 1; this makes it |
| 5338 | # easier to compute a correctly rounded result in __pow__ |
| 5339 | if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1: |
| 5340 | coeff, exp = 10**(p-1)+1, 1-p |
| 5341 | else: |
| 5342 | coeff, exp = 10**p-1, -p |
| 5343 | else: |
| 5344 | coeff, exp = _dexp(pc, -(p+1), p+1) |
| 5345 | coeff = _div_nearest(coeff, 10) |
| 5346 | exp += 1 |
| 5347 | |
| 5348 | return coeff, exp |
| 5349 | |
| 5350 | def _log10_lb(c, correction = { |
| 5351 | '1': 100, '2': 70, '3': 53, '4': 40, '5': 31, |
| 5352 | '6': 23, '7': 16, '8': 10, '9': 5}): |
| 5353 | """Compute a lower bound for 100*log10(c) for a positive integer c.""" |
| 5354 | if c <= 0: |
| 5355 | raise ValueError("The argument to _log10_lb should be nonnegative.") |
| 5356 | str_c = str(c) |
| 5357 | return 100*len(str_c) - correction[str_c[0]] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5358 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 5359 | ##### Helper Functions #################################################### |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5360 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5361 | def _convert_other(other, raiseit=False): |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5362 | """Convert other to Decimal. |
| 5363 | |
| 5364 | Verifies that it's ok to use in an implicit construction. |
| 5365 | """ |
| 5366 | if isinstance(other, Decimal): |
| 5367 | return other |
Walter Dörwald | aa97f04 | 2007-05-03 21:05:51 +0000 | [diff] [blame] | 5368 | if isinstance(other, int): |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5369 | return Decimal(other) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5370 | if raiseit: |
| 5371 | raise TypeError("Unable to convert %s to Decimal" % other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 5372 | return NotImplemented |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5373 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 5374 | ##### Setup Specific Contexts ############################################ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5375 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5376 | # The default context prototype used by Context() |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 5377 | # Is mutable, so that new contexts can have different default values |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5378 | |
| 5379 | DefaultContext = Context( |
Raymond Hettinger | 6ea4845 | 2004-07-03 12:26:21 +0000 | [diff] [blame] | 5380 | prec=28, rounding=ROUND_HALF_EVEN, |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 5381 | traps=[DivisionByZero, Overflow, InvalidOperation], |
| 5382 | flags=[], |
Raymond Hettinger | 99148e7 | 2004-07-14 19:56:56 +0000 | [diff] [blame] | 5383 | Emax=999999999, |
| 5384 | Emin=-999999999, |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 5385 | capitals=1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5386 | ) |
| 5387 | |
| 5388 | # Pre-made alternate contexts offered by the specification |
| 5389 | # Don't change these; the user should be able to select these |
| 5390 | # contexts and be able to reproduce results from other implementations |
| 5391 | # of the spec. |
| 5392 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5393 | BasicContext = Context( |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5394 | prec=9, rounding=ROUND_HALF_UP, |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 5395 | traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow], |
| 5396 | flags=[], |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5397 | ) |
| 5398 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5399 | ExtendedContext = Context( |
Raymond Hettinger | 6ea4845 | 2004-07-03 12:26:21 +0000 | [diff] [blame] | 5400 | prec=9, rounding=ROUND_HALF_EVEN, |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 5401 | traps=[], |
| 5402 | flags=[], |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5403 | ) |
| 5404 | |
| 5405 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5406 | ##### crud for parsing strings ############################################# |
Christian Heimes | 23daade0 | 2008-02-25 12:39:23 +0000 | [diff] [blame] | 5407 | # |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5408 | # Regular expression used for parsing numeric strings. Additional |
| 5409 | # comments: |
| 5410 | # |
| 5411 | # 1. Uncomment the two '\s*' lines to allow leading and/or trailing |
| 5412 | # whitespace. But note that the specification disallows whitespace in |
| 5413 | # a numeric string. |
| 5414 | # |
| 5415 | # 2. For finite numbers (not infinities and NaNs) the body of the |
| 5416 | # number between the optional sign and the optional exponent must have |
| 5417 | # at least one decimal digit, possibly after the decimal point. The |
Antoine Pitrou | fd03645 | 2008-08-19 17:56:33 +0000 | [diff] [blame] | 5418 | # lookahead expression '(?=[0-9]|\.[0-9])' checks this. |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5419 | # |
| 5420 | # As the flag UNICODE is not enabled here, we're explicitly avoiding any |
| 5421 | # other meaning for \d than the numbers [0-9]. |
| 5422 | |
| 5423 | import re |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 5424 | _parser = re.compile(r""" # A numeric string consists of: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5425 | # \s* |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 5426 | (?P<sign>[-+])? # an optional sign, followed by either... |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5427 | ( |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 5428 | (?=[0-9]|\.[0-9]) # ...a number (with at least one digit) |
| 5429 | (?P<int>[0-9]*) # having a (possibly empty) integer part |
| 5430 | (\.(?P<frac>[0-9]*))? # followed by an optional fractional part |
| 5431 | (E(?P<exp>[-+]?[0-9]+))? # followed by an optional exponent, or... |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5432 | | |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 5433 | Inf(inity)? # ...an infinity, or... |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5434 | | |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 5435 | (?P<signal>s)? # ...an (optionally signaling) |
| 5436 | NaN # NaN |
| 5437 | (?P<diag>[0-9]*) # with (possibly empty) diagnostic info. |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5438 | ) |
| 5439 | # \s* |
Christian Heimes | a62da1d | 2008-01-12 19:39:10 +0000 | [diff] [blame] | 5440 | \Z |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5441 | """, re.VERBOSE | re.IGNORECASE).match |
| 5442 | |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 5443 | _all_zeros = re.compile('0*$').match |
| 5444 | _exact_half = re.compile('50*$').match |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 5445 | |
| 5446 | ##### PEP3101 support functions ############################################## |
| 5447 | # The functions parse_format_specifier and format_align have little to do |
| 5448 | # with the Decimal class, and could potentially be reused for other pure |
| 5449 | # Python numeric classes that want to implement __format__ |
| 5450 | # |
| 5451 | # A format specifier for Decimal looks like: |
| 5452 | # |
| 5453 | # [[fill]align][sign][0][minimumwidth][.precision][type] |
| 5454 | # |
| 5455 | |
| 5456 | _parse_format_specifier_regex = re.compile(r"""\A |
| 5457 | (?: |
| 5458 | (?P<fill>.)? |
| 5459 | (?P<align>[<>=^]) |
| 5460 | )? |
| 5461 | (?P<sign>[-+ ])? |
| 5462 | (?P<zeropad>0)? |
| 5463 | (?P<minimumwidth>(?!0)\d+)? |
| 5464 | (?:\.(?P<precision>0|(?!0)\d+))? |
| 5465 | (?P<type>[eEfFgG%])? |
| 5466 | \Z |
| 5467 | """, re.VERBOSE) |
| 5468 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5469 | del re |
| 5470 | |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 5471 | def _parse_format_specifier(format_spec): |
| 5472 | """Parse and validate a format specifier. |
| 5473 | |
| 5474 | Turns a standard numeric format specifier into a dict, with the |
| 5475 | following entries: |
| 5476 | |
| 5477 | fill: fill character to pad field to minimum width |
| 5478 | align: alignment type, either '<', '>', '=' or '^' |
| 5479 | sign: either '+', '-' or ' ' |
| 5480 | minimumwidth: nonnegative integer giving minimum width |
| 5481 | precision: nonnegative integer giving precision, or None |
| 5482 | type: one of the characters 'eEfFgG%', or None |
| 5483 | unicode: either True or False (always True for Python 3.x) |
| 5484 | |
| 5485 | """ |
| 5486 | m = _parse_format_specifier_regex.match(format_spec) |
| 5487 | if m is None: |
| 5488 | raise ValueError("Invalid format specifier: " + format_spec) |
| 5489 | |
| 5490 | # get the dictionary |
| 5491 | format_dict = m.groupdict() |
| 5492 | |
| 5493 | # defaults for fill and alignment |
| 5494 | fill = format_dict['fill'] |
| 5495 | align = format_dict['align'] |
| 5496 | if format_dict.pop('zeropad') is not None: |
| 5497 | # in the face of conflict, refuse the temptation to guess |
| 5498 | if fill is not None and fill != '0': |
| 5499 | raise ValueError("Fill character conflicts with '0'" |
| 5500 | " in format specifier: " + format_spec) |
| 5501 | if align is not None and align != '=': |
| 5502 | raise ValueError("Alignment conflicts with '0' in " |
| 5503 | "format specifier: " + format_spec) |
| 5504 | fill = '0' |
| 5505 | align = '=' |
| 5506 | format_dict['fill'] = fill or ' ' |
| 5507 | format_dict['align'] = align or '<' |
| 5508 | |
| 5509 | if format_dict['sign'] is None: |
| 5510 | format_dict['sign'] = '-' |
| 5511 | |
| 5512 | # turn minimumwidth and precision entries into integers. |
| 5513 | # minimumwidth defaults to 0; precision remains None if not given |
| 5514 | format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0') |
| 5515 | if format_dict['precision'] is not None: |
| 5516 | format_dict['precision'] = int(format_dict['precision']) |
| 5517 | |
| 5518 | # if format type is 'g' or 'G' then a precision of 0 makes little |
| 5519 | # sense; convert it to 1. Same if format type is unspecified. |
| 5520 | if format_dict['precision'] == 0: |
| 5521 | if format_dict['type'] in 'gG' or format_dict['type'] is None: |
| 5522 | format_dict['precision'] = 1 |
| 5523 | |
| 5524 | # record whether return type should be str or unicode |
Christian Heimes | 295f4fa | 2008-02-29 15:03:39 +0000 | [diff] [blame] | 5525 | format_dict['unicode'] = True |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 5526 | |
| 5527 | return format_dict |
| 5528 | |
| 5529 | def _format_align(body, spec_dict): |
| 5530 | """Given an unpadded, non-aligned numeric string, add padding and |
| 5531 | aligment to conform with the given format specifier dictionary (as |
| 5532 | output from parse_format_specifier). |
| 5533 | |
| 5534 | It's assumed that if body is negative then it starts with '-'. |
| 5535 | Any leading sign ('-' or '+') is stripped from the body before |
| 5536 | applying the alignment and padding rules, and replaced in the |
| 5537 | appropriate position. |
| 5538 | |
| 5539 | """ |
| 5540 | # figure out the sign; we only examine the first character, so if |
| 5541 | # body has leading whitespace the results may be surprising. |
| 5542 | if len(body) > 0 and body[0] in '-+': |
| 5543 | sign = body[0] |
| 5544 | body = body[1:] |
| 5545 | else: |
| 5546 | sign = '' |
| 5547 | |
| 5548 | if sign != '-': |
| 5549 | if spec_dict['sign'] in ' +': |
| 5550 | sign = spec_dict['sign'] |
| 5551 | else: |
| 5552 | sign = '' |
| 5553 | |
| 5554 | # how much extra space do we have to play with? |
| 5555 | minimumwidth = spec_dict['minimumwidth'] |
| 5556 | fill = spec_dict['fill'] |
| 5557 | padding = fill*(max(minimumwidth - (len(sign+body)), 0)) |
| 5558 | |
| 5559 | align = spec_dict['align'] |
| 5560 | if align == '<': |
| 5561 | result = padding + sign + body |
| 5562 | elif align == '>': |
| 5563 | result = sign + body + padding |
| 5564 | elif align == '=': |
| 5565 | result = sign + padding + body |
| 5566 | else: #align == '^' |
| 5567 | half = len(padding)//2 |
| 5568 | result = padding[:half] + sign + body + padding[half:] |
| 5569 | |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 5570 | return result |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5571 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 5572 | ##### Useful Constants (internal use only) ################################ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5573 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 5574 | # Reusable defaults |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5575 | Inf = Decimal('Inf') |
| 5576 | negInf = Decimal('-Inf') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5577 | NaN = Decimal('NaN') |
| 5578 | Dec_0 = Decimal(0) |
| 5579 | Dec_p1 = Decimal(1) |
| 5580 | Dec_n1 = Decimal(-1) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5581 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 5582 | # Infsign[sign] is infinity w/ that sign |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5583 | Infsign = (Inf, negInf) |
| 5584 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5585 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5586 | |
| 5587 | if __name__ == '__main__': |
| 5588 | import doctest, sys |
| 5589 | doctest.testmod(sys.modules[__name__]) |