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 | |
Facundo Batista | 6ab2479 | 2009-02-16 15:41:37 +0000 | [diff] [blame] | 10 | # This module should be kept in sync with the latest updates of the |
| 11 | # IBM specification as it evolves. Those updates will be treated |
Raymond Hettinger | 27dbcf2 | 2004-08-19 22:39:55 +0000 | [diff] [blame] | 12 | # as bug fixes (deviation from the spec is a compatibility, usability |
| 13 | # bug) and will be backported. At this point the spec is stabilizing |
| 14 | # and the updates are becoming fewer, smaller, and less significant. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 15 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 16 | """ |
Facundo Batista | 6ab2479 | 2009-02-16 15:41:37 +0000 | [diff] [blame] | 17 | This is an implementation of decimal floating point arithmetic based on |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 18 | the General Decimal Arithmetic Specification: |
| 19 | |
Raymond Hettinger | 960dc36 | 2009-04-21 03:43:15 +0000 | [diff] [blame] | 20 | http://speleotrove.com/decimal/decarith.html |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 21 | |
Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 22 | and IEEE standard 854-1987: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 23 | |
| 24 | www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html |
| 25 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 26 | Decimal floating point has finite precision with arbitrarily large bounds. |
| 27 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 28 | The purpose of this module is to support arithmetic using familiar |
| 29 | "schoolhouse" rules and to avoid some of the tricky representation |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 30 | issues associated with binary floating point. The package is especially |
| 31 | useful for financial applications or for contexts where users have |
| 32 | expectations that are at odds with binary floating point (for instance, |
| 33 | in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 34 | of the expected Decimal('0.00') returned by decimal floating point). |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 35 | |
| 36 | Here are some examples of using the decimal module: |
| 37 | |
| 38 | >>> from decimal import * |
Raymond Hettinger | bd7f76d | 2004-07-08 00:49:18 +0000 | [diff] [blame] | 39 | >>> setcontext(ExtendedContext) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 40 | >>> Decimal(0) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 41 | Decimal('0') |
| 42 | >>> Decimal('1') |
| 43 | Decimal('1') |
| 44 | >>> Decimal('-.0123') |
| 45 | Decimal('-0.0123') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 46 | >>> Decimal(123456) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 47 | Decimal('123456') |
| 48 | >>> Decimal('123.45e12345678901234567890') |
| 49 | Decimal('1.2345E+12345678901234567892') |
| 50 | >>> Decimal('1.33') + Decimal('1.27') |
| 51 | Decimal('2.60') |
| 52 | >>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41') |
| 53 | Decimal('-2.20') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 54 | >>> dig = Decimal(1) |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 55 | >>> print(dig / Decimal(3)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 56 | 0.333333333 |
| 57 | >>> getcontext().prec = 18 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 58 | >>> print(dig / Decimal(3)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 59 | 0.333333333333333333 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 60 | >>> print(dig.sqrt()) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 61 | 1 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 62 | >>> print(Decimal(3).sqrt()) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 63 | 1.73205080756887729 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 64 | >>> print(Decimal(3) ** 123) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 65 | 4.85192780976896427E+58 |
| 66 | >>> inf = Decimal(1) / Decimal(0) |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 67 | >>> print(inf) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 68 | Infinity |
| 69 | >>> neginf = Decimal(-1) / Decimal(0) |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 70 | >>> print(neginf) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 71 | -Infinity |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 72 | >>> print(neginf + inf) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 73 | NaN |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 74 | >>> print(neginf * inf) |
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(dig / 0) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 77 | Infinity |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 78 | >>> getcontext().traps[DivisionByZero] = 1 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 79 | >>> print(dig / 0) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 80 | Traceback (most recent call last): |
| 81 | ... |
| 82 | ... |
| 83 | ... |
Guido van Rossum | 6a2a2a0 | 2006-08-26 20:37:44 +0000 | [diff] [blame] | 84 | decimal.DivisionByZero: x / 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 85 | >>> c = Context() |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 86 | >>> c.traps[InvalidOperation] = 0 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 87 | >>> print(c.flags[InvalidOperation]) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 88 | 0 |
| 89 | >>> c.divide(Decimal(0), Decimal(0)) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 90 | Decimal('NaN') |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 91 | >>> c.traps[InvalidOperation] = 1 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 92 | >>> print(c.flags[InvalidOperation]) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 93 | 1 |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 94 | >>> c.flags[InvalidOperation] = 0 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 95 | >>> print(c.flags[InvalidOperation]) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 96 | 0 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 97 | >>> print(c.divide(Decimal(0), Decimal(0))) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 98 | Traceback (most recent call last): |
| 99 | ... |
| 100 | ... |
| 101 | ... |
Guido van Rossum | 6a2a2a0 | 2006-08-26 20:37:44 +0000 | [diff] [blame] | 102 | decimal.InvalidOperation: 0 / 0 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 103 | >>> print(c.flags[InvalidOperation]) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 104 | 1 |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 105 | >>> c.flags[InvalidOperation] = 0 |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 106 | >>> c.traps[InvalidOperation] = 0 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 107 | >>> print(c.divide(Decimal(0), Decimal(0))) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 108 | NaN |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 109 | >>> print(c.flags[InvalidOperation]) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 110 | 1 |
| 111 | >>> |
| 112 | """ |
| 113 | |
| 114 | __all__ = [ |
| 115 | # Two major classes |
| 116 | 'Decimal', 'Context', |
| 117 | |
| 118 | # Contexts |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 119 | 'DefaultContext', 'BasicContext', 'ExtendedContext', |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 120 | |
| 121 | # Exceptions |
Raymond Hettinger | d87ac8f | 2004-07-09 10:52:54 +0000 | [diff] [blame] | 122 | 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero', |
| 123 | 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow', |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 124 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 125 | # Constants for use in setting up contexts |
| 126 | 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING', |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 127 | 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP', |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 128 | |
| 129 | # Functions for manipulating contexts |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 130 | 'setcontext', 'getcontext', 'localcontext' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 131 | ] |
| 132 | |
Raymond Hettinger | 960dc36 | 2009-04-21 03:43:15 +0000 | [diff] [blame] | 133 | __version__ = '1.70' # Highest version of the spec this complies with |
| 134 | |
Raymond Hettinger | eb26084 | 2005-06-07 18:52:34 +0000 | [diff] [blame] | 135 | import copy as _copy |
Raymond Hettinger | 771ed76 | 2009-01-03 19:20:32 +0000 | [diff] [blame] | 136 | import math as _math |
Raymond Hettinger | 82417ca | 2009-02-03 03:54:28 +0000 | [diff] [blame] | 137 | import numbers as _numbers |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 138 | |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 139 | try: |
| 140 | from collections import namedtuple as _namedtuple |
| 141 | DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent') |
| 142 | except ImportError: |
| 143 | DecimalTuple = lambda *args: args |
| 144 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 145 | # Rounding |
Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 146 | ROUND_DOWN = 'ROUND_DOWN' |
| 147 | ROUND_HALF_UP = 'ROUND_HALF_UP' |
| 148 | ROUND_HALF_EVEN = 'ROUND_HALF_EVEN' |
| 149 | ROUND_CEILING = 'ROUND_CEILING' |
| 150 | ROUND_FLOOR = 'ROUND_FLOOR' |
| 151 | ROUND_UP = 'ROUND_UP' |
| 152 | ROUND_HALF_DOWN = 'ROUND_HALF_DOWN' |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 153 | ROUND_05UP = 'ROUND_05UP' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 154 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 155 | # Errors |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 156 | |
| 157 | class DecimalException(ArithmeticError): |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 158 | """Base exception class. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 159 | |
| 160 | Used exceptions derive from this. |
| 161 | If an exception derives from another exception besides this (such as |
| 162 | Underflow (Inexact, Rounded, Subnormal) that indicates that it is only |
| 163 | called if the others are present. This isn't actually used for |
| 164 | anything, though. |
| 165 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 166 | handle -- Called when context._raise_error is called and the |
| 167 | trap_enabler is set. First argument is self, second is the |
| 168 | context. More arguments can be given, those being after |
| 169 | the explanation in _raise_error (For example, |
| 170 | context._raise_error(NewError, '(-x)!', self._sign) would |
| 171 | call NewError().handle(context, self._sign).) |
| 172 | |
| 173 | To define a new exception, it should be sufficient to have it derive |
| 174 | from DecimalException. |
| 175 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 176 | def handle(self, context, *args): |
| 177 | pass |
| 178 | |
| 179 | |
| 180 | class Clamped(DecimalException): |
| 181 | """Exponent of a 0 changed to fit bounds. |
| 182 | |
| 183 | This occurs and signals clamped if the exponent of a result has been |
| 184 | altered in order to fit the constraints of a specific concrete |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 185 | representation. This may occur when the exponent of a zero result would |
| 186 | be outside the bounds of a representation, or when a large normal |
| 187 | number would have an encoded exponent that cannot be represented. In |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 188 | this latter case, the exponent is reduced to fit and the corresponding |
| 189 | number of zero digits are appended to the coefficient ("fold-down"). |
| 190 | """ |
| 191 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 192 | class InvalidOperation(DecimalException): |
| 193 | """An invalid operation was performed. |
| 194 | |
| 195 | Various bad things cause this: |
| 196 | |
| 197 | Something creates a signaling NaN |
| 198 | -INF + INF |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 199 | 0 * (+-)INF |
| 200 | (+-)INF / (+-)INF |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 201 | x % 0 |
| 202 | (+-)INF % x |
| 203 | x._rescale( non-integer ) |
| 204 | sqrt(-x) , x > 0 |
| 205 | 0 ** 0 |
| 206 | x ** (non-integer) |
| 207 | x ** (+-)INF |
| 208 | An operand is invalid |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 209 | |
| 210 | The result of the operation after these is a quiet positive NaN, |
| 211 | except when the cause is a signaling NaN, in which case the result is |
| 212 | also a quiet NaN, but with the original sign, and an optional |
| 213 | diagnostic information. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 214 | """ |
| 215 | def handle(self, context, *args): |
| 216 | if args: |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 217 | ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True) |
| 218 | return ans._fix_nan(context) |
Mark Dickinson | f923641 | 2009-01-02 23:23:21 +0000 | [diff] [blame] | 219 | return _NaN |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 220 | |
| 221 | class ConversionSyntax(InvalidOperation): |
| 222 | """Trying to convert badly formed string. |
| 223 | |
| 224 | This occurs and signals invalid-operation if an string is being |
| 225 | converted to a number and it does not conform to the numeric string |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 226 | syntax. The result is [0,qNaN]. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 227 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 228 | def handle(self, context, *args): |
Mark Dickinson | f923641 | 2009-01-02 23:23:21 +0000 | [diff] [blame] | 229 | return _NaN |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 230 | |
| 231 | class DivisionByZero(DecimalException, ZeroDivisionError): |
| 232 | """Division by 0. |
| 233 | |
| 234 | This occurs and signals division-by-zero if division of a finite number |
| 235 | by zero was attempted (during a divide-integer or divide operation, or a |
| 236 | power operation with negative right-hand operand), and the dividend was |
| 237 | not zero. |
| 238 | |
| 239 | The result of the operation is [sign,inf], where sign is the exclusive |
| 240 | or of the signs of the operands for divide, or is 1 for an odd power of |
| 241 | -0, for power. |
| 242 | """ |
| 243 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 244 | def handle(self, context, sign, *args): |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 245 | return _SignedInfinity[sign] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 246 | |
| 247 | class DivisionImpossible(InvalidOperation): |
| 248 | """Cannot perform the division adequately. |
| 249 | |
| 250 | This occurs and signals invalid-operation if the integer result of a |
| 251 | divide-integer or remainder operation had too many digits (would be |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 252 | longer than precision). The result is [0,qNaN]. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 253 | """ |
| 254 | |
| 255 | def handle(self, context, *args): |
Mark Dickinson | f923641 | 2009-01-02 23:23:21 +0000 | [diff] [blame] | 256 | return _NaN |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 257 | |
| 258 | class DivisionUndefined(InvalidOperation, ZeroDivisionError): |
| 259 | """Undefined result of division. |
| 260 | |
| 261 | This occurs and signals invalid-operation if division by zero was |
| 262 | attempted (during a divide-integer, divide, or remainder operation), and |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 263 | the dividend is also zero. The result is [0,qNaN]. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 264 | """ |
| 265 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 266 | def handle(self, context, *args): |
Mark Dickinson | f923641 | 2009-01-02 23:23:21 +0000 | [diff] [blame] | 267 | return _NaN |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 268 | |
| 269 | class Inexact(DecimalException): |
| 270 | """Had to round, losing information. |
| 271 | |
| 272 | This occurs and signals inexact whenever the result of an operation is |
| 273 | not exact (that is, it needed to be rounded and any discarded digits |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 274 | were non-zero), or if an overflow or underflow condition occurs. The |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 275 | result in all cases is unchanged. |
| 276 | |
| 277 | The inexact signal may be tested (or trapped) to determine if a given |
| 278 | operation (or sequence of operations) was inexact. |
| 279 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 280 | |
| 281 | class InvalidContext(InvalidOperation): |
| 282 | """Invalid context. Unknown rounding, for example. |
| 283 | |
| 284 | This occurs and signals invalid-operation if an invalid context was |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 285 | detected during an operation. This can occur if contexts are not checked |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 286 | on creation and either the precision exceeds the capability of the |
| 287 | underlying concrete representation or an unknown or unsupported rounding |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 288 | was specified. These aspects of the context need only be checked when |
| 289 | the values are required to be used. The result is [0,qNaN]. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 290 | """ |
| 291 | |
| 292 | def handle(self, context, *args): |
Mark Dickinson | f923641 | 2009-01-02 23:23:21 +0000 | [diff] [blame] | 293 | return _NaN |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 294 | |
| 295 | class Rounded(DecimalException): |
| 296 | """Number got rounded (not necessarily changed during rounding). |
| 297 | |
| 298 | This occurs and signals rounded whenever the result of an operation is |
| 299 | rounded (that is, some zero or non-zero digits were discarded from the |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 300 | coefficient), or if an overflow or underflow condition occurs. The |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 301 | result in all cases is unchanged. |
| 302 | |
| 303 | The rounded signal may be tested (or trapped) to determine if a given |
| 304 | operation (or sequence of operations) caused a loss of precision. |
| 305 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 306 | |
| 307 | class Subnormal(DecimalException): |
| 308 | """Exponent < Emin before rounding. |
| 309 | |
| 310 | This occurs and signals subnormal whenever the result of a conversion or |
| 311 | operation is subnormal (that is, its adjusted exponent is less than |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 312 | Emin, before any rounding). The result in all cases is unchanged. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 313 | |
| 314 | The subnormal signal may be tested (or trapped) to determine if a given |
| 315 | or operation (or sequence of operations) yielded a subnormal result. |
| 316 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 317 | |
| 318 | class Overflow(Inexact, Rounded): |
| 319 | """Numerical overflow. |
| 320 | |
| 321 | This occurs and signals overflow if the adjusted exponent of a result |
| 322 | (from a conversion or from an operation that is not an attempt to divide |
| 323 | by zero), after rounding, would be greater than the largest value that |
| 324 | can be handled by the implementation (the value Emax). |
| 325 | |
| 326 | The result depends on the rounding mode: |
| 327 | |
| 328 | For round-half-up and round-half-even (and for round-half-down and |
| 329 | round-up, if implemented), the result of the operation is [sign,inf], |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 330 | where sign is the sign of the intermediate result. For round-down, the |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 331 | result is the largest finite number that can be represented in the |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 332 | current precision, with the sign of the intermediate result. For |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 333 | round-ceiling, the result is the same as for round-down if the sign of |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 334 | the intermediate result is 1, or is [0,inf] otherwise. For round-floor, |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 335 | the result is the same as for round-down if the sign of the intermediate |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 336 | result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 337 | will also be raised. |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 338 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 339 | |
| 340 | def handle(self, context, sign, *args): |
| 341 | if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN, |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 342 | ROUND_HALF_DOWN, ROUND_UP): |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 343 | return _SignedInfinity[sign] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 344 | if sign == 0: |
| 345 | if context.rounding == ROUND_CEILING: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 346 | return _SignedInfinity[sign] |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 347 | return _dec_from_triple(sign, '9'*context.prec, |
| 348 | context.Emax-context.prec+1) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 349 | if sign == 1: |
| 350 | if context.rounding == ROUND_FLOOR: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 351 | return _SignedInfinity[sign] |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 352 | return _dec_from_triple(sign, '9'*context.prec, |
| 353 | context.Emax-context.prec+1) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 354 | |
| 355 | |
| 356 | class Underflow(Inexact, Rounded, Subnormal): |
| 357 | """Numerical underflow with result rounded to 0. |
| 358 | |
| 359 | This occurs and signals underflow if a result is inexact and the |
| 360 | adjusted exponent of the result would be smaller (more negative) than |
| 361 | the smallest value that can be handled by the implementation (the value |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 362 | Emin). That is, the result is both inexact and subnormal. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 363 | |
| 364 | The result after an underflow will be a subnormal number rounded, if |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 365 | necessary, so that its exponent is not less than Etiny. This may result |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 366 | in 0 with the sign of the intermediate result and an exponent of Etiny. |
| 367 | |
| 368 | In all cases, Inexact, Rounded, and Subnormal will also be raised. |
| 369 | """ |
| 370 | |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 371 | # List of public traps and flags |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 372 | _signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded, |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 373 | Underflow, InvalidOperation, Subnormal] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 374 | |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 375 | # Map conditions (per the spec) to signals |
| 376 | _condition_map = {ConversionSyntax:InvalidOperation, |
| 377 | DivisionImpossible:InvalidOperation, |
| 378 | DivisionUndefined:InvalidOperation, |
| 379 | InvalidContext:InvalidOperation} |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 380 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 381 | ##### Context Functions ################################################## |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 382 | |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 383 | # The getcontext() and setcontext() function manage access to a thread-local |
| 384 | # current context. Py2.4 offers direct support for thread locals. If that |
Georg Brandl | f992640 | 2008-06-13 06:32:25 +0000 | [diff] [blame] | 385 | # is not available, use threading.current_thread() which is slower but will |
Raymond Hettinger | 7e71fa5 | 2004-12-18 19:07:19 +0000 | [diff] [blame] | 386 | # work for older Pythons. If threads are not part of the build, create a |
| 387 | # mock threading object with threading.local() returning the module namespace. |
| 388 | |
| 389 | try: |
| 390 | import threading |
| 391 | except ImportError: |
| 392 | # Python was compiled without threads; create a mock object instead |
| 393 | import sys |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 394 | class MockThreading(object): |
Raymond Hettinger | 7e71fa5 | 2004-12-18 19:07:19 +0000 | [diff] [blame] | 395 | def local(self, sys=sys): |
| 396 | return sys.modules[__name__] |
| 397 | threading = MockThreading() |
| 398 | del sys, MockThreading |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 399 | |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 400 | try: |
| 401 | threading.local |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 402 | |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 403 | except AttributeError: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 404 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 405 | # To fix reloading, force it to create a new context |
| 406 | # Old contexts have different exceptions in their dicts, making problems. |
Georg Brandl | f992640 | 2008-06-13 06:32:25 +0000 | [diff] [blame] | 407 | if hasattr(threading.current_thread(), '__decimal_context__'): |
| 408 | del threading.current_thread().__decimal_context__ |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 409 | |
| 410 | def setcontext(context): |
| 411 | """Set this thread's context to context.""" |
| 412 | if context in (DefaultContext, BasicContext, ExtendedContext): |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 413 | context = context.copy() |
Raymond Hettinger | 61992ef | 2004-08-06 23:42:16 +0000 | [diff] [blame] | 414 | context.clear_flags() |
Georg Brandl | f992640 | 2008-06-13 06:32:25 +0000 | [diff] [blame] | 415 | threading.current_thread().__decimal_context__ = context |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 416 | |
| 417 | def getcontext(): |
| 418 | """Returns this thread's context. |
| 419 | |
| 420 | If this thread does not yet have a context, returns |
| 421 | a new context and sets this thread's context. |
| 422 | New contexts are copies of DefaultContext. |
| 423 | """ |
| 424 | try: |
Georg Brandl | f992640 | 2008-06-13 06:32:25 +0000 | [diff] [blame] | 425 | return threading.current_thread().__decimal_context__ |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 426 | except AttributeError: |
| 427 | context = Context() |
Georg Brandl | f992640 | 2008-06-13 06:32:25 +0000 | [diff] [blame] | 428 | threading.current_thread().__decimal_context__ = context |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 429 | return context |
| 430 | |
| 431 | else: |
| 432 | |
| 433 | local = threading.local() |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 434 | if hasattr(local, '__decimal_context__'): |
| 435 | del local.__decimal_context__ |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 436 | |
| 437 | def getcontext(_local=local): |
| 438 | """Returns this thread's context. |
| 439 | |
| 440 | If this thread does not yet have a context, returns |
| 441 | a new context and sets this thread's context. |
| 442 | New contexts are copies of DefaultContext. |
| 443 | """ |
| 444 | try: |
| 445 | return _local.__decimal_context__ |
| 446 | except AttributeError: |
| 447 | context = Context() |
| 448 | _local.__decimal_context__ = context |
| 449 | return context |
| 450 | |
| 451 | def setcontext(context, _local=local): |
| 452 | """Set this thread's context to context.""" |
| 453 | if context in (DefaultContext, BasicContext, ExtendedContext): |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 454 | context = context.copy() |
Raymond Hettinger | 61992ef | 2004-08-06 23:42:16 +0000 | [diff] [blame] | 455 | context.clear_flags() |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 456 | _local.__decimal_context__ = context |
| 457 | |
| 458 | del threading, local # Don't contaminate the namespace |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 459 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 460 | def localcontext(ctx=None): |
| 461 | """Return a context manager for a copy of the supplied context |
| 462 | |
| 463 | Uses a copy of the current context if no context is specified |
| 464 | The returned context manager creates a local decimal context |
| 465 | in a with statement: |
| 466 | def sin(x): |
| 467 | with localcontext() as ctx: |
| 468 | ctx.prec += 2 |
| 469 | # Rest of sin calculation algorithm |
| 470 | # uses a precision 2 greater than normal |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 471 | return +s # Convert result to normal precision |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 472 | |
| 473 | def sin(x): |
| 474 | with localcontext(ExtendedContext): |
| 475 | # Rest of sin calculation algorithm |
| 476 | # uses the Extended Context from the |
| 477 | # General Decimal Arithmetic Specification |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 478 | return +s # Convert result to normal context |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 479 | |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 480 | >>> setcontext(DefaultContext) |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 481 | >>> print(getcontext().prec) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 482 | 28 |
| 483 | >>> with localcontext(): |
| 484 | ... ctx = getcontext() |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 485 | ... ctx.prec += 2 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 486 | ... print(ctx.prec) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 487 | ... |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 488 | 30 |
| 489 | >>> with localcontext(ExtendedContext): |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 490 | ... print(getcontext().prec) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 491 | ... |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 492 | 9 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 493 | >>> print(getcontext().prec) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 494 | 28 |
| 495 | """ |
| 496 | if ctx is None: ctx = getcontext() |
| 497 | return _ContextManager(ctx) |
| 498 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 499 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 500 | ##### Decimal class ####################################################### |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 501 | |
Raymond Hettinger | a0fd888 | 2009-01-20 07:24:44 +0000 | [diff] [blame] | 502 | # Do not subclass Decimal from numbers.Real and do not register it as such |
| 503 | # (because Decimals are not interoperable with floats). See the notes in |
| 504 | # numbers.py for more detail. |
| 505 | |
| 506 | class Decimal(object): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 507 | """Floating point class for decimal arithmetic.""" |
| 508 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 509 | __slots__ = ('_exp','_int','_sign', '_is_special') |
| 510 | # Generally, the value of the Decimal instance is given by |
| 511 | # (-1)**_sign * _int * 10**_exp |
| 512 | # Special values are signified by _is_special == True |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 513 | |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 514 | # We're immutable, so use __new__ not __init__ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 515 | def __new__(cls, value="0", context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 516 | """Create a decimal point instance. |
| 517 | |
| 518 | >>> Decimal('3.14') # string input |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 519 | Decimal('3.14') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 520 | >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 521 | Decimal('3.14') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 522 | >>> Decimal(314) # int |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 523 | Decimal('314') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 524 | >>> Decimal(Decimal(314)) # another decimal instance |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 525 | Decimal('314') |
Christian Heimes | a62da1d | 2008-01-12 19:39:10 +0000 | [diff] [blame] | 526 | >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 527 | Decimal('3.14') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 528 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 529 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 530 | # Note that the coefficient, self._int, is actually stored as |
| 531 | # a string rather than as a tuple of digits. This speeds up |
| 532 | # the "digits to integer" and "integer to digits" conversions |
| 533 | # that are used in almost every arithmetic operation on |
| 534 | # Decimals. This is an internal detail: the as_tuple function |
| 535 | # and the Decimal constructor still deal with tuples of |
| 536 | # digits. |
| 537 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 538 | self = object.__new__(cls) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 539 | |
Christian Heimes | d59c64c | 2007-11-30 19:27:20 +0000 | [diff] [blame] | 540 | # From a string |
| 541 | # REs insist on real strings, so we can too. |
| 542 | if isinstance(value, str): |
Christian Heimes | a62da1d | 2008-01-12 19:39:10 +0000 | [diff] [blame] | 543 | m = _parser(value.strip()) |
Christian Heimes | d59c64c | 2007-11-30 19:27:20 +0000 | [diff] [blame] | 544 | if m is None: |
| 545 | if context is None: |
| 546 | context = getcontext() |
| 547 | return context._raise_error(ConversionSyntax, |
| 548 | "Invalid literal for Decimal: %r" % value) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 549 | |
Christian Heimes | d59c64c | 2007-11-30 19:27:20 +0000 | [diff] [blame] | 550 | if m.group('sign') == "-": |
| 551 | self._sign = 1 |
| 552 | else: |
| 553 | self._sign = 0 |
| 554 | intpart = m.group('int') |
| 555 | if intpart is not None: |
| 556 | # finite number |
Mark Dickinson | 345adc4 | 2009-08-02 10:14:23 +0000 | [diff] [blame] | 557 | fracpart = m.group('frac') or '' |
Christian Heimes | d59c64c | 2007-11-30 19:27:20 +0000 | [diff] [blame] | 558 | exp = int(m.group('exp') or '0') |
Mark Dickinson | 345adc4 | 2009-08-02 10:14:23 +0000 | [diff] [blame] | 559 | self._int = str(int(intpart+fracpart)) |
| 560 | self._exp = exp - len(fracpart) |
Christian Heimes | d59c64c | 2007-11-30 19:27:20 +0000 | [diff] [blame] | 561 | self._is_special = False |
| 562 | else: |
| 563 | diag = m.group('diag') |
| 564 | if diag is not None: |
| 565 | # NaN |
Mark Dickinson | 345adc4 | 2009-08-02 10:14:23 +0000 | [diff] [blame] | 566 | self._int = str(int(diag or '0')).lstrip('0') |
Christian Heimes | d59c64c | 2007-11-30 19:27:20 +0000 | [diff] [blame] | 567 | if m.group('signal'): |
| 568 | self._exp = 'N' |
| 569 | else: |
| 570 | self._exp = 'n' |
| 571 | else: |
| 572 | # infinity |
| 573 | self._int = '0' |
| 574 | self._exp = 'F' |
| 575 | self._is_special = True |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 576 | return self |
| 577 | |
| 578 | # From an integer |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 579 | if isinstance(value, int): |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 580 | if value >= 0: |
| 581 | self._sign = 0 |
| 582 | else: |
| 583 | self._sign = 1 |
| 584 | self._exp = 0 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 585 | self._int = str(abs(value)) |
Christian Heimes | d59c64c | 2007-11-30 19:27:20 +0000 | [diff] [blame] | 586 | self._is_special = False |
| 587 | return self |
| 588 | |
| 589 | # From another decimal |
| 590 | if isinstance(value, Decimal): |
| 591 | self._exp = value._exp |
| 592 | self._sign = value._sign |
| 593 | self._int = value._int |
| 594 | self._is_special = value._is_special |
| 595 | return self |
| 596 | |
| 597 | # From an internal working value |
| 598 | if isinstance(value, _WorkRep): |
| 599 | self._sign = value.sign |
| 600 | self._int = str(value.int) |
| 601 | self._exp = int(value.exp) |
| 602 | self._is_special = False |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 603 | return self |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 604 | |
| 605 | # tuple/list conversion (possibly from as_tuple()) |
| 606 | if isinstance(value, (list,tuple)): |
| 607 | if len(value) != 3: |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 608 | raise ValueError('Invalid tuple size in creation of Decimal ' |
| 609 | 'from list or tuple. The list or tuple ' |
| 610 | 'should have exactly three elements.') |
| 611 | # process sign. The isinstance test rejects floats |
| 612 | if not (isinstance(value[0], int) and value[0] in (0,1)): |
| 613 | raise ValueError("Invalid sign. The first value in the tuple " |
| 614 | "should be an integer; either 0 for a " |
| 615 | "positive number or 1 for a negative number.") |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 616 | self._sign = value[0] |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 617 | if value[2] == 'F': |
| 618 | # infinity: value[1] is ignored |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 619 | self._int = '0' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 620 | self._exp = value[2] |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 621 | self._is_special = True |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 622 | else: |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 623 | # process and validate the digits in value[1] |
| 624 | digits = [] |
| 625 | for digit in value[1]: |
| 626 | if isinstance(digit, int) and 0 <= digit <= 9: |
| 627 | # skip leading zeros |
| 628 | if digits or digit != 0: |
| 629 | digits.append(digit) |
| 630 | else: |
| 631 | raise ValueError("The second value in the tuple must " |
| 632 | "be composed of integers in the range " |
| 633 | "0 through 9.") |
| 634 | if value[2] in ('n', 'N'): |
| 635 | # NaN: digits form the diagnostic |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 636 | self._int = ''.join(map(str, digits)) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 637 | self._exp = value[2] |
| 638 | self._is_special = True |
| 639 | elif isinstance(value[2], int): |
| 640 | # finite number: digits give the coefficient |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 641 | self._int = ''.join(map(str, digits or [0])) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 642 | self._exp = value[2] |
| 643 | self._is_special = False |
| 644 | else: |
| 645 | raise ValueError("The third value in the tuple must " |
| 646 | "be an integer, or one of the " |
| 647 | "strings 'F', 'n', 'N'.") |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 648 | return self |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 649 | |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 650 | if isinstance(value, float): |
Raymond Hettinger | 9679859 | 2010-04-02 16:58:27 +0000 | [diff] [blame] | 651 | value = Decimal.from_float(value) |
| 652 | self._exp = value._exp |
| 653 | self._sign = value._sign |
| 654 | self._int = value._int |
| 655 | self._is_special = value._is_special |
| 656 | return self |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 657 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 658 | raise TypeError("Cannot convert %r to Decimal" % value) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 659 | |
Mark Dickinson | ba298e4 | 2009-01-04 21:17:43 +0000 | [diff] [blame] | 660 | # @classmethod, but @decorator is not valid Python 2.3 syntax, so |
| 661 | # don't use it (see notes on Py2.3 compatibility at top of file) |
Raymond Hettinger | 771ed76 | 2009-01-03 19:20:32 +0000 | [diff] [blame] | 662 | def from_float(cls, f): |
| 663 | """Converts a float to a decimal number, exactly. |
| 664 | |
| 665 | Note that Decimal.from_float(0.1) is not the same as Decimal('0.1'). |
| 666 | Since 0.1 is not exactly representable in binary floating point, the |
| 667 | value is stored as the nearest representable value which is |
| 668 | 0x1.999999999999ap-4. The exact equivalent of the value in decimal |
| 669 | is 0.1000000000000000055511151231257827021181583404541015625. |
| 670 | |
| 671 | >>> Decimal.from_float(0.1) |
| 672 | Decimal('0.1000000000000000055511151231257827021181583404541015625') |
| 673 | >>> Decimal.from_float(float('nan')) |
| 674 | Decimal('NaN') |
| 675 | >>> Decimal.from_float(float('inf')) |
| 676 | Decimal('Infinity') |
| 677 | >>> Decimal.from_float(-float('inf')) |
| 678 | Decimal('-Infinity') |
| 679 | >>> Decimal.from_float(-0.0) |
| 680 | Decimal('-0') |
| 681 | |
| 682 | """ |
| 683 | if isinstance(f, int): # handle integer inputs |
| 684 | return cls(f) |
| 685 | if _math.isinf(f) or _math.isnan(f): # raises TypeError if not a float |
| 686 | return cls(repr(f)) |
Mark Dickinson | ba298e4 | 2009-01-04 21:17:43 +0000 | [diff] [blame] | 687 | if _math.copysign(1.0, f) == 1.0: |
| 688 | sign = 0 |
| 689 | else: |
| 690 | sign = 1 |
Raymond Hettinger | 771ed76 | 2009-01-03 19:20:32 +0000 | [diff] [blame] | 691 | n, d = abs(f).as_integer_ratio() |
| 692 | k = d.bit_length() - 1 |
| 693 | result = _dec_from_triple(sign, str(n*5**k), -k) |
Mark Dickinson | ba298e4 | 2009-01-04 21:17:43 +0000 | [diff] [blame] | 694 | if cls is Decimal: |
| 695 | return result |
| 696 | else: |
| 697 | return cls(result) |
| 698 | from_float = classmethod(from_float) |
Raymond Hettinger | 771ed76 | 2009-01-03 19:20:32 +0000 | [diff] [blame] | 699 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 700 | def _isnan(self): |
| 701 | """Returns whether the number is not actually one. |
| 702 | |
| 703 | 0 if a number |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 704 | 1 if NaN |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 705 | 2 if sNaN |
| 706 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 707 | if self._is_special: |
| 708 | exp = self._exp |
| 709 | if exp == 'n': |
| 710 | return 1 |
| 711 | elif exp == 'N': |
| 712 | return 2 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 713 | return 0 |
| 714 | |
| 715 | def _isinfinity(self): |
| 716 | """Returns whether the number is infinite |
| 717 | |
| 718 | 0 if finite or not a number |
| 719 | 1 if +INF |
| 720 | -1 if -INF |
| 721 | """ |
| 722 | if self._exp == 'F': |
| 723 | if self._sign: |
| 724 | return -1 |
| 725 | return 1 |
| 726 | return 0 |
| 727 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 728 | def _check_nans(self, other=None, context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 729 | """Returns whether the number is not actually one. |
| 730 | |
| 731 | if self, other are sNaN, signal |
| 732 | if self, other are NaN return nan |
| 733 | return 0 |
| 734 | |
| 735 | Done before operations. |
| 736 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 737 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 738 | self_is_nan = self._isnan() |
| 739 | if other is None: |
| 740 | other_is_nan = False |
| 741 | else: |
| 742 | other_is_nan = other._isnan() |
| 743 | |
| 744 | if self_is_nan or other_is_nan: |
| 745 | if context is None: |
| 746 | context = getcontext() |
| 747 | |
| 748 | if self_is_nan == 2: |
| 749 | return context._raise_error(InvalidOperation, 'sNaN', |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 750 | self) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 751 | if other_is_nan == 2: |
| 752 | return context._raise_error(InvalidOperation, 'sNaN', |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 753 | other) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 754 | if self_is_nan: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 755 | return self._fix_nan(context) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 756 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 757 | return other._fix_nan(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 758 | return 0 |
| 759 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 760 | def _compare_check_nans(self, other, context): |
| 761 | """Version of _check_nans used for the signaling comparisons |
| 762 | compare_signal, __le__, __lt__, __ge__, __gt__. |
| 763 | |
| 764 | Signal InvalidOperation if either self or other is a (quiet |
| 765 | or signaling) NaN. Signaling NaNs take precedence over quiet |
| 766 | NaNs. |
| 767 | |
| 768 | Return 0 if neither operand is a NaN. |
| 769 | |
| 770 | """ |
| 771 | if context is None: |
| 772 | context = getcontext() |
| 773 | |
| 774 | if self._is_special or other._is_special: |
| 775 | if self.is_snan(): |
| 776 | return context._raise_error(InvalidOperation, |
| 777 | 'comparison involving sNaN', |
| 778 | self) |
| 779 | elif other.is_snan(): |
| 780 | return context._raise_error(InvalidOperation, |
| 781 | 'comparison involving sNaN', |
| 782 | other) |
| 783 | elif self.is_qnan(): |
| 784 | return context._raise_error(InvalidOperation, |
| 785 | 'comparison involving NaN', |
| 786 | self) |
| 787 | elif other.is_qnan(): |
| 788 | return context._raise_error(InvalidOperation, |
| 789 | 'comparison involving NaN', |
| 790 | other) |
| 791 | return 0 |
| 792 | |
Jack Diederich | 4dafcc4 | 2006-11-28 19:15:13 +0000 | [diff] [blame] | 793 | def __bool__(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 794 | """Return True if self is nonzero; otherwise return False. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 795 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 796 | NaNs and infinities are considered nonzero. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 797 | """ |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 798 | return self._is_special or self._int != '0' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 799 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 800 | def _cmp(self, other): |
| 801 | """Compare the two non-NaN decimal instances self and other. |
| 802 | |
| 803 | Returns -1 if self < other, 0 if self == other and 1 |
| 804 | if self > other. This routine is for internal use only.""" |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 805 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 806 | if self._is_special or other._is_special: |
Mark Dickinson | e6aad75 | 2009-01-25 10:48:51 +0000 | [diff] [blame] | 807 | self_inf = self._isinfinity() |
| 808 | other_inf = other._isinfinity() |
| 809 | if self_inf == other_inf: |
| 810 | return 0 |
| 811 | elif self_inf < other_inf: |
| 812 | return -1 |
| 813 | else: |
| 814 | return 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 815 | |
Mark Dickinson | e6aad75 | 2009-01-25 10:48:51 +0000 | [diff] [blame] | 816 | # check for zeros; Decimal('0') == Decimal('-0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 817 | if not self: |
| 818 | if not other: |
| 819 | return 0 |
| 820 | else: |
| 821 | return -((-1)**other._sign) |
| 822 | if not other: |
| 823 | return (-1)**self._sign |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 824 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 825 | # If different signs, neg one is less |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 826 | if other._sign < self._sign: |
| 827 | return -1 |
| 828 | if self._sign < other._sign: |
| 829 | return 1 |
| 830 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 831 | self_adjusted = self.adjusted() |
| 832 | other_adjusted = other.adjusted() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 833 | if self_adjusted == other_adjusted: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 834 | self_padded = self._int + '0'*(self._exp - other._exp) |
| 835 | other_padded = other._int + '0'*(other._exp - self._exp) |
Mark Dickinson | e6aad75 | 2009-01-25 10:48:51 +0000 | [diff] [blame] | 836 | if self_padded == other_padded: |
| 837 | return 0 |
| 838 | elif self_padded < other_padded: |
| 839 | return -(-1)**self._sign |
| 840 | else: |
| 841 | return (-1)**self._sign |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 842 | elif self_adjusted > other_adjusted: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 843 | return (-1)**self._sign |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 844 | else: # self_adjusted < other_adjusted |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 845 | return -((-1)**self._sign) |
| 846 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 847 | # Note: The Decimal standard doesn't cover rich comparisons for |
| 848 | # Decimals. In particular, the specification is silent on the |
| 849 | # subject of what should happen for a comparison involving a NaN. |
| 850 | # We take the following approach: |
| 851 | # |
Mark Dickinson | ac256ab | 2010-04-03 11:08:14 +0000 | [diff] [blame] | 852 | # == comparisons involving a quiet NaN always return False |
| 853 | # != comparisons involving a quiet NaN always return True |
| 854 | # == or != comparisons involving a signaling NaN signal |
| 855 | # InvalidOperation, and return False or True as above if the |
| 856 | # InvalidOperation is not trapped. |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 857 | # <, >, <= and >= comparisons involving a (quiet or signaling) |
| 858 | # NaN signal InvalidOperation, and return False if the |
Christian Heimes | 3feef61 | 2008-02-11 06:19:17 +0000 | [diff] [blame] | 859 | # InvalidOperation is not trapped. |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 860 | # |
| 861 | # This behavior is designed to conform as closely as possible to |
| 862 | # that specified by IEEE 754. |
| 863 | |
Mark Dickinson | ac256ab | 2010-04-03 11:08:14 +0000 | [diff] [blame] | 864 | def __eq__(self, other, context=None): |
| 865 | other = _convert_other(other, allow_float=True) |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 866 | if other is NotImplemented: |
| 867 | return other |
Mark Dickinson | ac256ab | 2010-04-03 11:08:14 +0000 | [diff] [blame] | 868 | if self._check_nans(other, context): |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 869 | return False |
| 870 | return self._cmp(other) == 0 |
Raymond Hettinger | 0aeac10 | 2004-07-05 22:53:03 +0000 | [diff] [blame] | 871 | |
Mark Dickinson | ac256ab | 2010-04-03 11:08:14 +0000 | [diff] [blame] | 872 | def __ne__(self, other, context=None): |
| 873 | other = _convert_other(other, allow_float=True) |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 874 | if other is NotImplemented: |
| 875 | return other |
Mark Dickinson | ac256ab | 2010-04-03 11:08:14 +0000 | [diff] [blame] | 876 | if self._check_nans(other, context): |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 877 | return True |
| 878 | return self._cmp(other) != 0 |
Raymond Hettinger | 0aeac10 | 2004-07-05 22:53:03 +0000 | [diff] [blame] | 879 | |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 880 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 881 | def __lt__(self, other, context=None): |
Mark Dickinson | ac256ab | 2010-04-03 11:08:14 +0000 | [diff] [blame] | 882 | other = _convert_other(other, allow_float=True) |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 883 | if other is NotImplemented: |
| 884 | return other |
| 885 | ans = self._compare_check_nans(other, context) |
| 886 | if ans: |
| 887 | return False |
| 888 | return self._cmp(other) < 0 |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 889 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 890 | def __le__(self, other, context=None): |
Mark Dickinson | ac256ab | 2010-04-03 11:08:14 +0000 | [diff] [blame] | 891 | other = _convert_other(other, allow_float=True) |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 892 | if other is NotImplemented: |
| 893 | return other |
| 894 | ans = self._compare_check_nans(other, context) |
| 895 | if ans: |
| 896 | return False |
| 897 | return self._cmp(other) <= 0 |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 898 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 899 | def __gt__(self, other, context=None): |
Mark Dickinson | ac256ab | 2010-04-03 11:08:14 +0000 | [diff] [blame] | 900 | other = _convert_other(other, allow_float=True) |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 901 | if other is NotImplemented: |
| 902 | return other |
| 903 | ans = self._compare_check_nans(other, context) |
| 904 | if ans: |
| 905 | return False |
| 906 | return self._cmp(other) > 0 |
| 907 | |
| 908 | def __ge__(self, other, context=None): |
Mark Dickinson | ac256ab | 2010-04-03 11:08:14 +0000 | [diff] [blame] | 909 | other = _convert_other(other, allow_float=True) |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 910 | if other is NotImplemented: |
| 911 | return other |
| 912 | ans = self._compare_check_nans(other, context) |
| 913 | if ans: |
| 914 | return False |
| 915 | return self._cmp(other) >= 0 |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 916 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 917 | def compare(self, other, context=None): |
| 918 | """Compares one to another. |
| 919 | |
| 920 | -1 => a < b |
| 921 | 0 => a = b |
| 922 | 1 => a > b |
| 923 | NaN => one is NaN |
| 924 | Like __cmp__, but returns Decimal instances. |
| 925 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 926 | other = _convert_other(other, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 927 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 928 | # Compare(NaN, NaN) = NaN |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 929 | if (self._is_special or other and other._is_special): |
| 930 | ans = self._check_nans(other, context) |
| 931 | if ans: |
| 932 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 933 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 934 | return Decimal(self._cmp(other)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 935 | |
| 936 | def __hash__(self): |
| 937 | """x.__hash__() <==> hash(x)""" |
| 938 | # Decimal integers must hash the same as the ints |
Christian Heimes | 2380ac7 | 2008-01-09 00:17:24 +0000 | [diff] [blame] | 939 | # |
| 940 | # The hash of a nonspecial noninteger Decimal must depend only |
| 941 | # on the value of that Decimal, and not on its representation. |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 942 | # For example: hash(Decimal('100E-1')) == hash(Decimal('10')). |
Mark Dickinson | ac256ab | 2010-04-03 11:08:14 +0000 | [diff] [blame] | 943 | |
| 944 | # Equality comparisons involving signaling nans can raise an |
| 945 | # exception; since equality checks are implicitly and |
| 946 | # unpredictably used when checking set and dict membership, we |
| 947 | # prevent signaling nans from being used as set elements or |
| 948 | # dict keys by making __hash__ raise an exception. |
Raymond Hettinger | bea3f6f | 2005-03-15 04:59:17 +0000 | [diff] [blame] | 949 | if self._is_special: |
Mark Dickinson | ac256ab | 2010-04-03 11:08:14 +0000 | [diff] [blame] | 950 | if self.is_snan(): |
| 951 | raise TypeError('Cannot hash a signaling NaN value.') |
| 952 | elif self.is_nan(): |
| 953 | # 0 to match hash(float('nan')) |
| 954 | return 0 |
| 955 | else: |
| 956 | # values chosen to match hash(float('inf')) and |
| 957 | # hash(float('-inf')). |
| 958 | if self._sign: |
| 959 | return -271828 |
| 960 | else: |
| 961 | return 314159 |
| 962 | |
| 963 | # In Python 2.7, we're allowing comparisons (but not |
| 964 | # arithmetic operations) between floats and Decimals; so if |
| 965 | # a Decimal instance is exactly representable as a float then |
| 966 | # its hash should match that of the float. |
| 967 | self_as_float = float(self) |
| 968 | if Decimal.from_float(self_as_float) == self: |
| 969 | return hash(self_as_float) |
| 970 | |
Thomas Wouters | 8ce81f7 | 2007-09-20 18:22:40 +0000 | [diff] [blame] | 971 | if self._isinteger(): |
| 972 | op = _WorkRep(self.to_integral_value()) |
| 973 | # to make computation feasible for Decimals with large |
| 974 | # exponent, we use the fact that hash(n) == hash(m) for |
| 975 | # any two nonzero integers n and m such that (i) n and m |
| 976 | # have the same sign, and (ii) n is congruent to m modulo |
| 977 | # 2**64-1. So we can replace hash((-1)**s*c*10**e) with |
| 978 | # hash((-1)**s*c*pow(10, e, 2**64-1). |
| 979 | 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] | 980 | # The value of a nonzero nonspecial Decimal instance is |
| 981 | # faithfully represented by the triple consisting of its sign, |
| 982 | # its adjusted exponent, and its coefficient with trailing |
| 983 | # zeros removed. |
| 984 | return hash((self._sign, |
| 985 | self._exp+len(self._int), |
| 986 | self._int.rstrip('0'))) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 987 | |
| 988 | def as_tuple(self): |
| 989 | """Represents the number as a triple tuple. |
| 990 | |
| 991 | To show the internals exactly as they are. |
| 992 | """ |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 993 | return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 994 | |
| 995 | def __repr__(self): |
| 996 | """Represents the number as an instance of Decimal.""" |
| 997 | # Invariant: eval(repr(d)) == d |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 998 | return "Decimal('%s')" % str(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 999 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1000 | def __str__(self, eng=False, context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1001 | """Return string representation of the number in scientific notation. |
| 1002 | |
| 1003 | Captures all of the information in the underlying representation. |
| 1004 | """ |
| 1005 | |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1006 | sign = ['', '-'][self._sign] |
Raymond Hettinger | e5a0a96 | 2005-06-20 09:49:42 +0000 | [diff] [blame] | 1007 | if self._is_special: |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1008 | if self._exp == 'F': |
| 1009 | return sign + 'Infinity' |
| 1010 | elif self._exp == 'n': |
| 1011 | return sign + 'NaN' + self._int |
| 1012 | else: # self._exp == 'N' |
| 1013 | return sign + 'sNaN' + self._int |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1014 | |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1015 | # number of digits of self._int to left of decimal point |
| 1016 | leftdigits = self._exp + len(self._int) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1017 | |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1018 | # dotplace is number of digits of self._int to the left of the |
| 1019 | # decimal point in the mantissa of the output string (that is, |
| 1020 | # after adjusting the exponent) |
| 1021 | if self._exp <= 0 and leftdigits > -6: |
| 1022 | # no exponent required |
| 1023 | dotplace = leftdigits |
| 1024 | elif not eng: |
| 1025 | # usual scientific notation: 1 digit on left of the point |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1026 | dotplace = 1 |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1027 | elif self._int == '0': |
| 1028 | # engineering notation, zero |
| 1029 | dotplace = (leftdigits + 1) % 3 - 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1030 | else: |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1031 | # engineering notation, nonzero |
| 1032 | dotplace = (leftdigits - 1) % 3 + 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1033 | |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1034 | if dotplace <= 0: |
| 1035 | intpart = '0' |
| 1036 | fracpart = '.' + '0'*(-dotplace) + self._int |
| 1037 | elif dotplace >= len(self._int): |
| 1038 | intpart = self._int+'0'*(dotplace-len(self._int)) |
| 1039 | fracpart = '' |
| 1040 | else: |
| 1041 | intpart = self._int[:dotplace] |
| 1042 | fracpart = '.' + self._int[dotplace:] |
| 1043 | if leftdigits == dotplace: |
| 1044 | exp = '' |
| 1045 | else: |
| 1046 | if context is None: |
| 1047 | context = getcontext() |
| 1048 | exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace) |
| 1049 | |
| 1050 | return sign + intpart + fracpart + exp |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1051 | |
| 1052 | def to_eng_string(self, context=None): |
| 1053 | """Convert to engineering-type string. |
| 1054 | |
| 1055 | Engineering notation has an exponent which is a multiple of 3, so there |
| 1056 | are up to 3 digits left of the decimal place. |
| 1057 | |
| 1058 | Same rules for when in exponential and when as a value as in __str__. |
| 1059 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1060 | return self.__str__(eng=True, context=context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1061 | |
| 1062 | def __neg__(self, context=None): |
| 1063 | """Returns a copy with the sign switched. |
| 1064 | |
| 1065 | Rounds, if it has reason. |
| 1066 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1067 | if self._is_special: |
| 1068 | ans = self._check_nans(context=context) |
| 1069 | if ans: |
| 1070 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1071 | |
| 1072 | if not self: |
| 1073 | # -Decimal('0') is Decimal('0'), not Decimal('-0') |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 1074 | ans = self.copy_abs() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1075 | else: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1076 | ans = self.copy_negate() |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1077 | |
| 1078 | if context is None: |
| 1079 | context = getcontext() |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1080 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1081 | |
| 1082 | def __pos__(self, context=None): |
| 1083 | """Returns a copy, unless it is a sNaN. |
| 1084 | |
| 1085 | Rounds the number (if more then precision digits) |
| 1086 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1087 | if self._is_special: |
| 1088 | ans = self._check_nans(context=context) |
| 1089 | if ans: |
| 1090 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1091 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1092 | if not self: |
| 1093 | # + (-0) = 0 |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 1094 | ans = self.copy_abs() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1095 | else: |
| 1096 | ans = Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1097 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1098 | if context is None: |
| 1099 | context = getcontext() |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1100 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1101 | |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1102 | def __abs__(self, round=True, context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1103 | """Returns the absolute value of self. |
| 1104 | |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1105 | If the keyword argument 'round' is false, do not round. The |
| 1106 | expression self.__abs__(round=False) is equivalent to |
| 1107 | self.copy_abs(). |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1108 | """ |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1109 | if not round: |
| 1110 | return self.copy_abs() |
| 1111 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1112 | if self._is_special: |
| 1113 | ans = self._check_nans(context=context) |
| 1114 | if ans: |
| 1115 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1116 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1117 | if self._sign: |
| 1118 | ans = self.__neg__(context=context) |
| 1119 | else: |
| 1120 | ans = self.__pos__(context=context) |
| 1121 | |
| 1122 | return ans |
| 1123 | |
| 1124 | def __add__(self, other, context=None): |
| 1125 | """Returns self + other. |
| 1126 | |
| 1127 | -INF + INF (or the reverse) cause InvalidOperation errors. |
| 1128 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1129 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1130 | if other is NotImplemented: |
| 1131 | return other |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1132 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1133 | if context is None: |
| 1134 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1135 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1136 | if self._is_special or other._is_special: |
| 1137 | ans = self._check_nans(other, context) |
| 1138 | if ans: |
| 1139 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1140 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1141 | if self._isinfinity(): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1142 | # If both INF, same sign => same as both, opposite => error. |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1143 | if self._sign != other._sign and other._isinfinity(): |
| 1144 | return context._raise_error(InvalidOperation, '-INF + INF') |
| 1145 | return Decimal(self) |
| 1146 | if other._isinfinity(): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1147 | return Decimal(other) # Can't both be infinity here |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1148 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1149 | exp = min(self._exp, other._exp) |
| 1150 | negativezero = 0 |
| 1151 | if context.rounding == ROUND_FLOOR and self._sign != other._sign: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1152 | # 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] | 1153 | negativezero = 1 |
| 1154 | |
| 1155 | if not self and not other: |
| 1156 | sign = min(self._sign, other._sign) |
| 1157 | if negativezero: |
| 1158 | sign = 1 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1159 | ans = _dec_from_triple(sign, '0', exp) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1160 | ans = ans._fix(context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1161 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1162 | if not self: |
Facundo Batista | 99b5548 | 2004-10-26 23:38:46 +0000 | [diff] [blame] | 1163 | exp = max(exp, other._exp - context.prec-1) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1164 | ans = other._rescale(exp, context.rounding) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1165 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1166 | return ans |
| 1167 | if not other: |
Facundo Batista | 99b5548 | 2004-10-26 23:38:46 +0000 | [diff] [blame] | 1168 | exp = max(exp, self._exp - context.prec-1) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1169 | ans = self._rescale(exp, context.rounding) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1170 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1171 | return ans |
| 1172 | |
| 1173 | op1 = _WorkRep(self) |
| 1174 | op2 = _WorkRep(other) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1175 | op1, op2 = _normalize(op1, op2, context.prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1176 | |
| 1177 | result = _WorkRep() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1178 | if op1.sign != op2.sign: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1179 | # Equal and opposite |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1180 | if op1.int == op2.int: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1181 | ans = _dec_from_triple(negativezero, '0', exp) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1182 | ans = ans._fix(context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1183 | return ans |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1184 | if op1.int < op2.int: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1185 | op1, op2 = op2, op1 |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1186 | # OK, now abs(op1) > abs(op2) |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1187 | if op1.sign == 1: |
| 1188 | result.sign = 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1189 | op1.sign, op2.sign = op2.sign, op1.sign |
| 1190 | else: |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1191 | result.sign = 0 |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1192 | # So we know the sign, and op1 > 0. |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1193 | elif op1.sign == 1: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1194 | result.sign = 1 |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1195 | op1.sign, op2.sign = (0, 0) |
| 1196 | else: |
| 1197 | result.sign = 0 |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1198 | # Now, op1 > abs(op2) > 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1199 | |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1200 | if op2.sign == 0: |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1201 | result.int = op1.int + op2.int |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1202 | else: |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1203 | result.int = op1.int - op2.int |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1204 | |
| 1205 | result.exp = op1.exp |
| 1206 | ans = Decimal(result) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1207 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1208 | return ans |
| 1209 | |
| 1210 | __radd__ = __add__ |
| 1211 | |
| 1212 | def __sub__(self, other, context=None): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1213 | """Return self - other""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1214 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1215 | if other is NotImplemented: |
| 1216 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1217 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1218 | if self._is_special or other._is_special: |
| 1219 | ans = self._check_nans(other, context=context) |
| 1220 | if ans: |
| 1221 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1222 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1223 | # self - other is computed as self + other.copy_negate() |
| 1224 | return self.__add__(other.copy_negate(), context=context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1225 | |
| 1226 | def __rsub__(self, other, context=None): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1227 | """Return other - self""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1228 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1229 | if other is NotImplemented: |
| 1230 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1231 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1232 | return other.__sub__(self, context=context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1233 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1234 | def __mul__(self, other, context=None): |
| 1235 | """Return self * other. |
| 1236 | |
| 1237 | (+-) INF * 0 (or its reverse) raise InvalidOperation. |
| 1238 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1239 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1240 | if other is NotImplemented: |
| 1241 | return other |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1242 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1243 | if context is None: |
| 1244 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1245 | |
Raymond Hettinger | d87ac8f | 2004-07-09 10:52:54 +0000 | [diff] [blame] | 1246 | resultsign = self._sign ^ other._sign |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1247 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1248 | if self._is_special or other._is_special: |
| 1249 | ans = self._check_nans(other, context) |
| 1250 | if ans: |
| 1251 | return ans |
| 1252 | |
| 1253 | if self._isinfinity(): |
| 1254 | if not other: |
| 1255 | return context._raise_error(InvalidOperation, '(+-)INF * 0') |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 1256 | return _SignedInfinity[resultsign] |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1257 | |
| 1258 | if other._isinfinity(): |
| 1259 | if not self: |
| 1260 | return context._raise_error(InvalidOperation, '0 * (+-)INF') |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 1261 | return _SignedInfinity[resultsign] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1262 | |
| 1263 | resultexp = self._exp + other._exp |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1264 | |
| 1265 | # Special case for multiplying by zero |
| 1266 | if not self or not other: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1267 | ans = _dec_from_triple(resultsign, '0', resultexp) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1268 | # Fixing in case the exponent is out of bounds |
| 1269 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1270 | return ans |
| 1271 | |
| 1272 | # Special case for multiplying by power of 10 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1273 | if self._int == '1': |
| 1274 | ans = _dec_from_triple(resultsign, other._int, resultexp) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1275 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1276 | return ans |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1277 | if other._int == '1': |
| 1278 | ans = _dec_from_triple(resultsign, self._int, resultexp) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1279 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1280 | return ans |
| 1281 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1282 | op1 = _WorkRep(self) |
| 1283 | op2 = _WorkRep(other) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1284 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1285 | ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1286 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1287 | |
| 1288 | return ans |
| 1289 | __rmul__ = __mul__ |
| 1290 | |
Neal Norwitz | bcc0db8 | 2006-03-24 08:14:36 +0000 | [diff] [blame] | 1291 | def __truediv__(self, other, context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1292 | """Return self / other.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1293 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1294 | if other is NotImplemented: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1295 | return NotImplemented |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1296 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1297 | if context is None: |
| 1298 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1299 | |
Raymond Hettinger | d87ac8f | 2004-07-09 10:52:54 +0000 | [diff] [blame] | 1300 | sign = self._sign ^ other._sign |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1301 | |
| 1302 | if self._is_special or other._is_special: |
| 1303 | ans = self._check_nans(other, context) |
| 1304 | if ans: |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1305 | return ans |
| 1306 | |
| 1307 | if self._isinfinity() and other._isinfinity(): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1308 | return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1309 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1310 | if self._isinfinity(): |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 1311 | return _SignedInfinity[sign] |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1312 | |
| 1313 | if other._isinfinity(): |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1314 | context._raise_error(Clamped, 'Division by infinity') |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1315 | return _dec_from_triple(sign, '0', context.Etiny()) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1316 | |
| 1317 | # Special cases for zeroes |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1318 | if not other: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1319 | if not self: |
| 1320 | return context._raise_error(DivisionUndefined, '0 / 0') |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1321 | return context._raise_error(DivisionByZero, 'x / 0', sign) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1322 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1323 | if not self: |
| 1324 | exp = self._exp - other._exp |
| 1325 | coeff = 0 |
| 1326 | else: |
| 1327 | # OK, so neither = 0, INF or NaN |
| 1328 | shift = len(other._int) - len(self._int) + context.prec + 1 |
| 1329 | exp = self._exp - other._exp - shift |
| 1330 | op1 = _WorkRep(self) |
| 1331 | op2 = _WorkRep(other) |
| 1332 | if shift >= 0: |
| 1333 | coeff, remainder = divmod(op1.int * 10**shift, op2.int) |
| 1334 | else: |
| 1335 | coeff, remainder = divmod(op1.int, op2.int * 10**-shift) |
| 1336 | if remainder: |
| 1337 | # result is not exact; adjust to ensure correct rounding |
| 1338 | if coeff % 5 == 0: |
| 1339 | coeff += 1 |
| 1340 | else: |
| 1341 | # result is exact; get as close to ideal exponent as possible |
| 1342 | ideal_exp = self._exp - other._exp |
| 1343 | while exp < ideal_exp and coeff % 10 == 0: |
| 1344 | coeff //= 10 |
| 1345 | exp += 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1346 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1347 | ans = _dec_from_triple(sign, str(coeff), exp) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1348 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1349 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1350 | def _divide(self, other, context): |
| 1351 | """Return (self // other, self % other), to context.prec precision. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1352 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1353 | Assumes that neither self nor other is a NaN, that self is not |
| 1354 | infinite and that other is nonzero. |
| 1355 | """ |
| 1356 | sign = self._sign ^ other._sign |
| 1357 | if other._isinfinity(): |
| 1358 | ideal_exp = self._exp |
| 1359 | else: |
| 1360 | ideal_exp = min(self._exp, other._exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1361 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1362 | expdiff = self.adjusted() - other.adjusted() |
| 1363 | if not self or other._isinfinity() or expdiff <= -2: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1364 | return (_dec_from_triple(sign, '0', 0), |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1365 | self._rescale(ideal_exp, context.rounding)) |
| 1366 | if expdiff <= context.prec: |
| 1367 | op1 = _WorkRep(self) |
| 1368 | op2 = _WorkRep(other) |
| 1369 | if op1.exp >= op2.exp: |
| 1370 | op1.int *= 10**(op1.exp - op2.exp) |
| 1371 | else: |
| 1372 | op2.int *= 10**(op2.exp - op1.exp) |
| 1373 | q, r = divmod(op1.int, op2.int) |
| 1374 | if q < 10**context.prec: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1375 | return (_dec_from_triple(sign, str(q), 0), |
| 1376 | _dec_from_triple(self._sign, str(r), ideal_exp)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1377 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1378 | # Here the quotient is too large to be representable |
| 1379 | ans = context._raise_error(DivisionImpossible, |
| 1380 | 'quotient too large in //, % or divmod') |
| 1381 | return ans, ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1382 | |
Neal Norwitz | bcc0db8 | 2006-03-24 08:14:36 +0000 | [diff] [blame] | 1383 | def __rtruediv__(self, other, context=None): |
| 1384 | """Swaps self/other and returns __truediv__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1385 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1386 | if other is NotImplemented: |
| 1387 | return other |
Neal Norwitz | bcc0db8 | 2006-03-24 08:14:36 +0000 | [diff] [blame] | 1388 | return other.__truediv__(self, context=context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1389 | |
| 1390 | def __divmod__(self, other, context=None): |
| 1391 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1392 | Return (self // other, self % other) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1393 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1394 | other = _convert_other(other) |
| 1395 | if other is NotImplemented: |
| 1396 | return other |
| 1397 | |
| 1398 | if context is None: |
| 1399 | context = getcontext() |
| 1400 | |
| 1401 | ans = self._check_nans(other, context) |
| 1402 | if ans: |
| 1403 | return (ans, ans) |
| 1404 | |
| 1405 | sign = self._sign ^ other._sign |
| 1406 | if self._isinfinity(): |
| 1407 | if other._isinfinity(): |
| 1408 | ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)') |
| 1409 | return ans, ans |
| 1410 | else: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 1411 | return (_SignedInfinity[sign], |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1412 | context._raise_error(InvalidOperation, 'INF % x')) |
| 1413 | |
| 1414 | if not other: |
| 1415 | if not self: |
| 1416 | ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)') |
| 1417 | return ans, ans |
| 1418 | else: |
| 1419 | return (context._raise_error(DivisionByZero, 'x // 0', sign), |
| 1420 | context._raise_error(InvalidOperation, 'x % 0')) |
| 1421 | |
| 1422 | quotient, remainder = self._divide(other, context) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1423 | remainder = remainder._fix(context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1424 | return quotient, remainder |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1425 | |
| 1426 | def __rdivmod__(self, other, context=None): |
| 1427 | """Swaps self/other and returns __divmod__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1428 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1429 | if other is NotImplemented: |
| 1430 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1431 | return other.__divmod__(self, context=context) |
| 1432 | |
| 1433 | def __mod__(self, other, context=None): |
| 1434 | """ |
| 1435 | self % other |
| 1436 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1437 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1438 | if other is NotImplemented: |
| 1439 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1440 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1441 | if context is None: |
| 1442 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1443 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1444 | ans = self._check_nans(other, context) |
| 1445 | if ans: |
| 1446 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1447 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1448 | if self._isinfinity(): |
| 1449 | return context._raise_error(InvalidOperation, 'INF % x') |
| 1450 | elif not other: |
| 1451 | if self: |
| 1452 | return context._raise_error(InvalidOperation, 'x % 0') |
| 1453 | else: |
| 1454 | return context._raise_error(DivisionUndefined, '0 % 0') |
| 1455 | |
| 1456 | remainder = self._divide(other, context)[1] |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1457 | remainder = remainder._fix(context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1458 | return remainder |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1459 | |
| 1460 | def __rmod__(self, other, context=None): |
| 1461 | """Swaps self/other and returns __mod__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1462 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1463 | if other is NotImplemented: |
| 1464 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1465 | return other.__mod__(self, context=context) |
| 1466 | |
| 1467 | def remainder_near(self, other, context=None): |
| 1468 | """ |
| 1469 | Remainder nearest to 0- abs(remainder-near) <= other/2 |
| 1470 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1471 | if context is None: |
| 1472 | context = getcontext() |
| 1473 | |
| 1474 | other = _convert_other(other, raiseit=True) |
| 1475 | |
| 1476 | ans = self._check_nans(other, context) |
| 1477 | if ans: |
| 1478 | return ans |
| 1479 | |
| 1480 | # self == +/-infinity -> InvalidOperation |
| 1481 | if self._isinfinity(): |
| 1482 | return context._raise_error(InvalidOperation, |
| 1483 | 'remainder_near(infinity, x)') |
| 1484 | |
| 1485 | # other == 0 -> either InvalidOperation or DivisionUndefined |
| 1486 | if not other: |
| 1487 | if self: |
| 1488 | return context._raise_error(InvalidOperation, |
| 1489 | 'remainder_near(x, 0)') |
| 1490 | else: |
| 1491 | return context._raise_error(DivisionUndefined, |
| 1492 | 'remainder_near(0, 0)') |
| 1493 | |
| 1494 | # other = +/-infinity -> remainder = self |
| 1495 | if other._isinfinity(): |
| 1496 | ans = Decimal(self) |
| 1497 | return ans._fix(context) |
| 1498 | |
| 1499 | # self = 0 -> remainder = self, with ideal exponent |
| 1500 | ideal_exponent = min(self._exp, other._exp) |
| 1501 | if not self: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1502 | ans = _dec_from_triple(self._sign, '0', ideal_exponent) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1503 | return ans._fix(context) |
| 1504 | |
| 1505 | # catch most cases of large or small quotient |
| 1506 | expdiff = self.adjusted() - other.adjusted() |
| 1507 | if expdiff >= context.prec + 1: |
| 1508 | # expdiff >= prec+1 => abs(self/other) > 10**prec |
| 1509 | return context._raise_error(DivisionImpossible) |
| 1510 | if expdiff <= -2: |
| 1511 | # expdiff <= -2 => abs(self/other) < 0.1 |
| 1512 | ans = self._rescale(ideal_exponent, context.rounding) |
| 1513 | return ans._fix(context) |
| 1514 | |
| 1515 | # adjust both arguments to have the same exponent, then divide |
| 1516 | op1 = _WorkRep(self) |
| 1517 | op2 = _WorkRep(other) |
| 1518 | if op1.exp >= op2.exp: |
| 1519 | op1.int *= 10**(op1.exp - op2.exp) |
| 1520 | else: |
| 1521 | op2.int *= 10**(op2.exp - op1.exp) |
| 1522 | q, r = divmod(op1.int, op2.int) |
| 1523 | # remainder is r*10**ideal_exponent; other is +/-op2.int * |
| 1524 | # 10**ideal_exponent. Apply correction to ensure that |
| 1525 | # abs(remainder) <= abs(other)/2 |
| 1526 | if 2*r + (q&1) > op2.int: |
| 1527 | r -= op2.int |
| 1528 | q += 1 |
| 1529 | |
| 1530 | if q >= 10**context.prec: |
| 1531 | return context._raise_error(DivisionImpossible) |
| 1532 | |
| 1533 | # result has same sign as self unless r is negative |
| 1534 | sign = self._sign |
| 1535 | if r < 0: |
| 1536 | sign = 1-sign |
| 1537 | r = -r |
| 1538 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1539 | ans = _dec_from_triple(sign, str(r), ideal_exponent) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1540 | return ans._fix(context) |
| 1541 | |
| 1542 | def __floordiv__(self, other, context=None): |
| 1543 | """self // other""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1544 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1545 | if other is NotImplemented: |
| 1546 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1547 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1548 | if context is None: |
| 1549 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1550 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1551 | ans = self._check_nans(other, context) |
| 1552 | if ans: |
| 1553 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1554 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1555 | if self._isinfinity(): |
| 1556 | if other._isinfinity(): |
| 1557 | return context._raise_error(InvalidOperation, 'INF // INF') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1558 | else: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 1559 | return _SignedInfinity[self._sign ^ other._sign] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1560 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1561 | if not other: |
| 1562 | if self: |
| 1563 | return context._raise_error(DivisionByZero, 'x // 0', |
| 1564 | self._sign ^ other._sign) |
| 1565 | else: |
| 1566 | return context._raise_error(DivisionUndefined, '0 // 0') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1567 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1568 | return self._divide(other, context)[0] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1569 | |
| 1570 | def __rfloordiv__(self, other, context=None): |
| 1571 | """Swaps self/other and returns __floordiv__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1572 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1573 | if other is NotImplemented: |
| 1574 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1575 | return other.__floordiv__(self, context=context) |
| 1576 | |
| 1577 | def __float__(self): |
| 1578 | """Float representation.""" |
| 1579 | return float(str(self)) |
| 1580 | |
| 1581 | def __int__(self): |
Brett Cannon | 46b0802 | 2005-03-01 03:12:26 +0000 | [diff] [blame] | 1582 | """Converts self to an int, truncating if necessary.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1583 | if self._is_special: |
| 1584 | if self._isnan(): |
Mark Dickinson | 825fce3 | 2009-09-07 18:08:12 +0000 | [diff] [blame] | 1585 | raise ValueError("Cannot convert NaN to integer") |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1586 | elif self._isinfinity(): |
Mark Dickinson | 825fce3 | 2009-09-07 18:08:12 +0000 | [diff] [blame] | 1587 | raise OverflowError("Cannot convert infinity to integer") |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1588 | s = (-1)**self._sign |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1589 | if self._exp >= 0: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1590 | return s*int(self._int)*10**self._exp |
Raymond Hettinger | 605ed02 | 2004-11-24 07:28:48 +0000 | [diff] [blame] | 1591 | else: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1592 | return s*int(self._int[:self._exp] or '0') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1593 | |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 1594 | __trunc__ = __int__ |
| 1595 | |
Christian Heimes | 0bd4e11 | 2008-02-12 22:59:25 +0000 | [diff] [blame] | 1596 | def real(self): |
| 1597 | return self |
Mark Dickinson | 315a20a | 2009-01-04 21:34:18 +0000 | [diff] [blame] | 1598 | real = property(real) |
Christian Heimes | 0bd4e11 | 2008-02-12 22:59:25 +0000 | [diff] [blame] | 1599 | |
Christian Heimes | 0bd4e11 | 2008-02-12 22:59:25 +0000 | [diff] [blame] | 1600 | def imag(self): |
| 1601 | return Decimal(0) |
Mark Dickinson | 315a20a | 2009-01-04 21:34:18 +0000 | [diff] [blame] | 1602 | imag = property(imag) |
Christian Heimes | 0bd4e11 | 2008-02-12 22:59:25 +0000 | [diff] [blame] | 1603 | |
| 1604 | def conjugate(self): |
| 1605 | return self |
| 1606 | |
| 1607 | def __complex__(self): |
| 1608 | return complex(float(self)) |
| 1609 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1610 | def _fix_nan(self, context): |
| 1611 | """Decapitate the payload of a NaN to fit the context""" |
| 1612 | payload = self._int |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1613 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1614 | # maximum length of payload is precision if _clamp=0, |
| 1615 | # precision-1 if _clamp=1. |
| 1616 | max_payload_len = context.prec - context._clamp |
| 1617 | if len(payload) > max_payload_len: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1618 | payload = payload[len(payload)-max_payload_len:].lstrip('0') |
| 1619 | return _dec_from_triple(self._sign, payload, self._exp, True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1620 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1621 | |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1622 | def _fix(self, context): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1623 | """Round if it is necessary to keep self within prec precision. |
| 1624 | |
| 1625 | Rounds and fixes the exponent. Does not raise on a sNaN. |
| 1626 | |
| 1627 | Arguments: |
| 1628 | self - Decimal instance |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1629 | context - context used. |
| 1630 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1631 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1632 | if self._is_special: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1633 | if self._isnan(): |
| 1634 | # decapitate payload if necessary |
| 1635 | return self._fix_nan(context) |
| 1636 | else: |
| 1637 | # self is +/-Infinity; return unaltered |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1638 | return Decimal(self) |
| 1639 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1640 | # if self is zero then exponent should be between Etiny and |
| 1641 | # Emax if _clamp==0, and between Etiny and Etop if _clamp==1. |
| 1642 | Etiny = context.Etiny() |
| 1643 | Etop = context.Etop() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1644 | if not self: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1645 | exp_max = [context.Emax, Etop][context._clamp] |
| 1646 | new_exp = min(max(self._exp, Etiny), exp_max) |
| 1647 | if new_exp != self._exp: |
| 1648 | context._raise_error(Clamped) |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1649 | return _dec_from_triple(self._sign, '0', new_exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1650 | else: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1651 | return Decimal(self) |
| 1652 | |
| 1653 | # exp_min is the smallest allowable exponent of the result, |
| 1654 | # equal to max(self.adjusted()-context.prec+1, Etiny) |
| 1655 | exp_min = len(self._int) + self._exp - context.prec |
| 1656 | if exp_min > Etop: |
| 1657 | # overflow: exp_min > Etop iff self.adjusted() > Emax |
| 1658 | context._raise_error(Inexact) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1659 | context._raise_error(Rounded) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1660 | return context._raise_error(Overflow, 'above Emax', self._sign) |
| 1661 | self_is_subnormal = exp_min < Etiny |
| 1662 | if self_is_subnormal: |
| 1663 | context._raise_error(Subnormal) |
| 1664 | exp_min = Etiny |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1665 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1666 | # round if self has too many digits |
| 1667 | if self._exp < exp_min: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1668 | context._raise_error(Rounded) |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1669 | digits = len(self._int) + self._exp - exp_min |
| 1670 | if digits < 0: |
| 1671 | self = _dec_from_triple(self._sign, '1', exp_min-1) |
| 1672 | digits = 0 |
| 1673 | this_function = getattr(self, self._pick_rounding_function[context.rounding]) |
| 1674 | changed = this_function(digits) |
| 1675 | coeff = self._int[:digits] or '0' |
| 1676 | if changed == 1: |
| 1677 | coeff = str(int(coeff)+1) |
| 1678 | ans = _dec_from_triple(self._sign, coeff, exp_min) |
| 1679 | |
| 1680 | if changed: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1681 | context._raise_error(Inexact) |
| 1682 | if self_is_subnormal: |
| 1683 | context._raise_error(Underflow) |
| 1684 | if not ans: |
| 1685 | # raise Clamped on underflow to 0 |
| 1686 | context._raise_error(Clamped) |
| 1687 | elif len(ans._int) == context.prec+1: |
| 1688 | # we get here only if rescaling rounds the |
| 1689 | # cofficient up to exactly 10**context.prec |
| 1690 | if ans._exp < Etop: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1691 | ans = _dec_from_triple(ans._sign, |
| 1692 | ans._int[:-1], ans._exp+1) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1693 | else: |
| 1694 | # Inexact and Rounded have already been raised |
| 1695 | ans = context._raise_error(Overflow, 'above Emax', |
| 1696 | self._sign) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1697 | return ans |
| 1698 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1699 | # fold down if _clamp == 1 and self has too few digits |
| 1700 | if context._clamp == 1 and self._exp > Etop: |
| 1701 | context._raise_error(Clamped) |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1702 | self_padded = self._int + '0'*(self._exp - Etop) |
| 1703 | return _dec_from_triple(self._sign, self_padded, Etop) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1704 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1705 | # here self was representable to begin with; return unchanged |
| 1706 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1707 | |
| 1708 | _pick_rounding_function = {} |
| 1709 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1710 | # for each of the rounding functions below: |
| 1711 | # self is a finite, nonzero Decimal |
| 1712 | # prec is an integer satisfying 0 <= prec < len(self._int) |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1713 | # |
| 1714 | # each function returns either -1, 0, or 1, as follows: |
| 1715 | # 1 indicates that self should be rounded up (away from zero) |
| 1716 | # 0 indicates that self should be truncated, and that all the |
| 1717 | # digits to be truncated are zeros (so the value is unchanged) |
| 1718 | # -1 indicates that there are nonzero digits to be truncated |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1719 | |
| 1720 | def _round_down(self, prec): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1721 | """Also known as round-towards-0, truncate.""" |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1722 | if _all_zeros(self._int, prec): |
| 1723 | return 0 |
| 1724 | else: |
| 1725 | return -1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1726 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1727 | def _round_up(self, prec): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1728 | """Rounds away from 0.""" |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1729 | return -self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1730 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1731 | def _round_half_up(self, prec): |
| 1732 | """Rounds 5 up (away from 0)""" |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1733 | if self._int[prec] in '56789': |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1734 | return 1 |
| 1735 | elif _all_zeros(self._int, prec): |
| 1736 | return 0 |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1737 | else: |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1738 | return -1 |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1739 | |
| 1740 | def _round_half_down(self, prec): |
| 1741 | """Round 5 down""" |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1742 | if _exact_half(self._int, prec): |
| 1743 | return -1 |
| 1744 | else: |
| 1745 | return self._round_half_up(prec) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1746 | |
| 1747 | def _round_half_even(self, prec): |
| 1748 | """Round 5 to even, rest to nearest.""" |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1749 | if _exact_half(self._int, prec) and \ |
| 1750 | (prec == 0 or self._int[prec-1] in '02468'): |
| 1751 | return -1 |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1752 | else: |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1753 | return self._round_half_up(prec) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1754 | |
| 1755 | def _round_ceiling(self, prec): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1756 | """Rounds up (not away from 0 if negative.)""" |
| 1757 | if self._sign: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1758 | return self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1759 | else: |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1760 | return -self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1761 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1762 | def _round_floor(self, prec): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1763 | """Rounds down (not towards 0 if negative)""" |
| 1764 | if not self._sign: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1765 | return self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1766 | else: |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1767 | return -self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1768 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1769 | def _round_05up(self, prec): |
| 1770 | """Round down unless digit prec-1 is 0 or 5.""" |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1771 | if prec and self._int[prec-1] not in '05': |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1772 | return self._round_down(prec) |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1773 | else: |
| 1774 | return -self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1775 | |
Mark Dickinson | b27406c | 2008-05-09 13:42:33 +0000 | [diff] [blame] | 1776 | def __round__(self, n=None): |
| 1777 | """Round self to the nearest integer, or to a given precision. |
| 1778 | |
| 1779 | If only one argument is supplied, round a finite Decimal |
| 1780 | instance self to the nearest integer. If self is infinite or |
| 1781 | a NaN then a Python exception is raised. If self is finite |
| 1782 | and lies exactly halfway between two integers then it is |
| 1783 | rounded to the integer with even last digit. |
| 1784 | |
| 1785 | >>> round(Decimal('123.456')) |
| 1786 | 123 |
| 1787 | >>> round(Decimal('-456.789')) |
| 1788 | -457 |
| 1789 | >>> round(Decimal('-3.0')) |
| 1790 | -3 |
| 1791 | >>> round(Decimal('2.5')) |
| 1792 | 2 |
| 1793 | >>> round(Decimal('3.5')) |
| 1794 | 4 |
| 1795 | >>> round(Decimal('Inf')) |
| 1796 | Traceback (most recent call last): |
| 1797 | ... |
Mark Dickinson | b27406c | 2008-05-09 13:42:33 +0000 | [diff] [blame] | 1798 | OverflowError: cannot round an infinity |
| 1799 | >>> round(Decimal('NaN')) |
| 1800 | Traceback (most recent call last): |
| 1801 | ... |
Mark Dickinson | b27406c | 2008-05-09 13:42:33 +0000 | [diff] [blame] | 1802 | ValueError: cannot round a NaN |
| 1803 | |
| 1804 | If a second argument n is supplied, self is rounded to n |
| 1805 | decimal places using the rounding mode for the current |
| 1806 | context. |
| 1807 | |
| 1808 | For an integer n, round(self, -n) is exactly equivalent to |
| 1809 | self.quantize(Decimal('1En')). |
| 1810 | |
| 1811 | >>> round(Decimal('123.456'), 0) |
| 1812 | Decimal('123') |
| 1813 | >>> round(Decimal('123.456'), 2) |
| 1814 | Decimal('123.46') |
| 1815 | >>> round(Decimal('123.456'), -2) |
| 1816 | Decimal('1E+2') |
| 1817 | >>> round(Decimal('-Infinity'), 37) |
| 1818 | Decimal('NaN') |
| 1819 | >>> round(Decimal('sNaN123'), 0) |
| 1820 | Decimal('NaN123') |
| 1821 | |
| 1822 | """ |
| 1823 | if n is not None: |
| 1824 | # two-argument form: use the equivalent quantize call |
| 1825 | if not isinstance(n, int): |
| 1826 | raise TypeError('Second argument to round should be integral') |
| 1827 | exp = _dec_from_triple(0, '1', -n) |
| 1828 | return self.quantize(exp) |
| 1829 | |
| 1830 | # one-argument form |
| 1831 | if self._is_special: |
| 1832 | if self.is_nan(): |
| 1833 | raise ValueError("cannot round a NaN") |
| 1834 | else: |
| 1835 | raise OverflowError("cannot round an infinity") |
| 1836 | return int(self._rescale(0, ROUND_HALF_EVEN)) |
| 1837 | |
| 1838 | def __floor__(self): |
| 1839 | """Return the floor of self, as an integer. |
| 1840 | |
| 1841 | For a finite Decimal instance self, return the greatest |
| 1842 | integer n such that n <= self. If self is infinite or a NaN |
| 1843 | then a Python exception is raised. |
| 1844 | |
| 1845 | """ |
| 1846 | if self._is_special: |
| 1847 | if self.is_nan(): |
| 1848 | raise ValueError("cannot round a NaN") |
| 1849 | else: |
| 1850 | raise OverflowError("cannot round an infinity") |
| 1851 | return int(self._rescale(0, ROUND_FLOOR)) |
| 1852 | |
| 1853 | def __ceil__(self): |
| 1854 | """Return the ceiling of self, as an integer. |
| 1855 | |
| 1856 | For a finite Decimal instance self, return the least integer n |
| 1857 | such that n >= self. If self is infinite or a NaN then a |
| 1858 | Python exception is raised. |
| 1859 | |
| 1860 | """ |
| 1861 | if self._is_special: |
| 1862 | if self.is_nan(): |
| 1863 | raise ValueError("cannot round a NaN") |
| 1864 | else: |
| 1865 | raise OverflowError("cannot round an infinity") |
| 1866 | return int(self._rescale(0, ROUND_CEILING)) |
| 1867 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1868 | def fma(self, other, third, context=None): |
| 1869 | """Fused multiply-add. |
| 1870 | |
| 1871 | Returns self*other+third with no rounding of the intermediate |
| 1872 | product self*other. |
| 1873 | |
| 1874 | self and other are multiplied together, with no rounding of |
| 1875 | the result. The third operand is then added to the result, |
| 1876 | and a single final rounding is performed. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1877 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1878 | |
| 1879 | other = _convert_other(other, raiseit=True) |
Christian Heimes | 8b0facf | 2007-12-04 19:30:01 +0000 | [diff] [blame] | 1880 | |
| 1881 | # compute product; raise InvalidOperation if either operand is |
| 1882 | # a signaling NaN or if the product is zero times infinity. |
| 1883 | if self._is_special or other._is_special: |
| 1884 | if context is None: |
| 1885 | context = getcontext() |
| 1886 | if self._exp == 'N': |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 1887 | return context._raise_error(InvalidOperation, 'sNaN', self) |
Christian Heimes | 8b0facf | 2007-12-04 19:30:01 +0000 | [diff] [blame] | 1888 | if other._exp == 'N': |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 1889 | return context._raise_error(InvalidOperation, 'sNaN', other) |
Christian Heimes | 8b0facf | 2007-12-04 19:30:01 +0000 | [diff] [blame] | 1890 | if self._exp == 'n': |
| 1891 | product = self |
| 1892 | elif other._exp == 'n': |
| 1893 | product = other |
| 1894 | elif self._exp == 'F': |
| 1895 | if not other: |
| 1896 | return context._raise_error(InvalidOperation, |
| 1897 | 'INF * 0 in fma') |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 1898 | product = _SignedInfinity[self._sign ^ other._sign] |
Christian Heimes | 8b0facf | 2007-12-04 19:30:01 +0000 | [diff] [blame] | 1899 | elif other._exp == 'F': |
| 1900 | if not self: |
| 1901 | return context._raise_error(InvalidOperation, |
| 1902 | '0 * INF in fma') |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 1903 | product = _SignedInfinity[self._sign ^ other._sign] |
Christian Heimes | 8b0facf | 2007-12-04 19:30:01 +0000 | [diff] [blame] | 1904 | else: |
| 1905 | product = _dec_from_triple(self._sign ^ other._sign, |
| 1906 | str(int(self._int) * int(other._int)), |
| 1907 | self._exp + other._exp) |
| 1908 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1909 | third = _convert_other(third, raiseit=True) |
Christian Heimes | 8b0facf | 2007-12-04 19:30:01 +0000 | [diff] [blame] | 1910 | return product.__add__(third, context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1911 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1912 | def _power_modulo(self, other, modulo, context=None): |
| 1913 | """Three argument version of __pow__""" |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1914 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1915 | # if can't convert other and modulo to Decimal, raise |
| 1916 | # TypeError; there's no point returning NotImplemented (no |
| 1917 | # equivalent of __rpow__ for three argument pow) |
| 1918 | other = _convert_other(other, raiseit=True) |
| 1919 | modulo = _convert_other(modulo, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1920 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1921 | if context is None: |
| 1922 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1923 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1924 | # deal with NaNs: if there are any sNaNs then first one wins, |
| 1925 | # (i.e. behaviour for NaNs is identical to that of fma) |
| 1926 | self_is_nan = self._isnan() |
| 1927 | other_is_nan = other._isnan() |
| 1928 | modulo_is_nan = modulo._isnan() |
| 1929 | if self_is_nan or other_is_nan or modulo_is_nan: |
| 1930 | if self_is_nan == 2: |
| 1931 | return context._raise_error(InvalidOperation, 'sNaN', |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 1932 | self) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1933 | if other_is_nan == 2: |
| 1934 | return context._raise_error(InvalidOperation, 'sNaN', |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 1935 | other) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1936 | if modulo_is_nan == 2: |
| 1937 | return context._raise_error(InvalidOperation, 'sNaN', |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 1938 | modulo) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1939 | if self_is_nan: |
| 1940 | return self._fix_nan(context) |
| 1941 | if other_is_nan: |
| 1942 | return other._fix_nan(context) |
| 1943 | return modulo._fix_nan(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1944 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1945 | # check inputs: we apply same restrictions as Python's pow() |
| 1946 | if not (self._isinteger() and |
| 1947 | other._isinteger() and |
| 1948 | modulo._isinteger()): |
| 1949 | return context._raise_error(InvalidOperation, |
| 1950 | 'pow() 3rd argument not allowed ' |
| 1951 | 'unless all arguments are integers') |
| 1952 | if other < 0: |
| 1953 | return context._raise_error(InvalidOperation, |
| 1954 | 'pow() 2nd argument cannot be ' |
| 1955 | 'negative when 3rd argument specified') |
| 1956 | if not modulo: |
| 1957 | return context._raise_error(InvalidOperation, |
| 1958 | 'pow() 3rd argument cannot be 0') |
| 1959 | |
| 1960 | # additional restriction for decimal: the modulus must be less |
| 1961 | # than 10**prec in absolute value |
| 1962 | if modulo.adjusted() >= context.prec: |
| 1963 | return context._raise_error(InvalidOperation, |
| 1964 | 'insufficient precision: pow() 3rd ' |
| 1965 | 'argument must not have more than ' |
| 1966 | 'precision digits') |
| 1967 | |
| 1968 | # define 0**0 == NaN, for consistency with two-argument pow |
| 1969 | # (even though it hurts!) |
| 1970 | if not other and not self: |
| 1971 | return context._raise_error(InvalidOperation, |
| 1972 | 'at least one of pow() 1st argument ' |
| 1973 | 'and 2nd argument must be nonzero ;' |
| 1974 | '0**0 is not defined') |
| 1975 | |
| 1976 | # compute sign of result |
| 1977 | if other._iseven(): |
| 1978 | sign = 0 |
| 1979 | else: |
| 1980 | sign = self._sign |
| 1981 | |
| 1982 | # convert modulo to a Python integer, and self and other to |
| 1983 | # Decimal integers (i.e. force their exponents to be >= 0) |
| 1984 | modulo = abs(int(modulo)) |
| 1985 | base = _WorkRep(self.to_integral_value()) |
| 1986 | exponent = _WorkRep(other.to_integral_value()) |
| 1987 | |
| 1988 | # compute result using integer pow() |
| 1989 | base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo |
| 1990 | for i in range(exponent.exp): |
| 1991 | base = pow(base, 10, modulo) |
| 1992 | base = pow(base, exponent.int, modulo) |
| 1993 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1994 | return _dec_from_triple(sign, str(base), 0) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1995 | |
| 1996 | def _power_exact(self, other, p): |
| 1997 | """Attempt to compute self**other exactly. |
| 1998 | |
| 1999 | Given Decimals self and other and an integer p, attempt to |
| 2000 | compute an exact result for the power self**other, with p |
| 2001 | digits of precision. Return None if self**other is not |
| 2002 | exactly representable in p digits. |
| 2003 | |
| 2004 | Assumes that elimination of special cases has already been |
| 2005 | performed: self and other must both be nonspecial; self must |
| 2006 | be positive and not numerically equal to 1; other must be |
| 2007 | nonzero. For efficiency, other._exp should not be too large, |
| 2008 | so that 10**abs(other._exp) is a feasible calculation.""" |
| 2009 | |
| 2010 | # In the comments below, we write x for the value of self and |
| 2011 | # y for the value of other. Write x = xc*10**xe and y = |
| 2012 | # yc*10**ye. |
| 2013 | |
| 2014 | # The main purpose of this method is to identify the *failure* |
| 2015 | # of x**y to be exactly representable with as little effort as |
| 2016 | # possible. So we look for cheap and easy tests that |
| 2017 | # eliminate the possibility of x**y being exact. Only if all |
| 2018 | # these tests are passed do we go on to actually compute x**y. |
| 2019 | |
| 2020 | # Here's the main idea. First normalize both x and y. We |
| 2021 | # express y as a rational m/n, with m and n relatively prime |
| 2022 | # and n>0. Then for x**y to be exactly representable (at |
| 2023 | # *any* precision), xc must be the nth power of a positive |
| 2024 | # integer and xe must be divisible by n. If m is negative |
| 2025 | # then additionally xc must be a power of either 2 or 5, hence |
| 2026 | # a power of 2**n or 5**n. |
| 2027 | # |
| 2028 | # There's a limit to how small |y| can be: if y=m/n as above |
| 2029 | # then: |
| 2030 | # |
| 2031 | # (1) if xc != 1 then for the result to be representable we |
| 2032 | # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So |
| 2033 | # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <= |
| 2034 | # 2**(1/|y|), hence xc**|y| < 2 and the result is not |
| 2035 | # representable. |
| 2036 | # |
| 2037 | # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if |
| 2038 | # |y| < 1/|xe| then the result is not representable. |
| 2039 | # |
| 2040 | # Note that since x is not equal to 1, at least one of (1) and |
| 2041 | # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) < |
| 2042 | # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye. |
| 2043 | # |
| 2044 | # There's also a limit to how large y can be, at least if it's |
| 2045 | # positive: the normalized result will have coefficient xc**y, |
| 2046 | # so if it's representable then xc**y < 10**p, and y < |
| 2047 | # p/log10(xc). Hence if y*log10(xc) >= p then the result is |
| 2048 | # not exactly representable. |
| 2049 | |
| 2050 | # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye, |
| 2051 | # so |y| < 1/xe and the result is not representable. |
| 2052 | # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y| |
| 2053 | # < 1/nbits(xc). |
| 2054 | |
| 2055 | x = _WorkRep(self) |
| 2056 | xc, xe = x.int, x.exp |
| 2057 | while xc % 10 == 0: |
| 2058 | xc //= 10 |
| 2059 | xe += 1 |
| 2060 | |
| 2061 | y = _WorkRep(other) |
| 2062 | yc, ye = y.int, y.exp |
| 2063 | while yc % 10 == 0: |
| 2064 | yc //= 10 |
| 2065 | ye += 1 |
| 2066 | |
| 2067 | # case where xc == 1: result is 10**(xe*y), with xe*y |
| 2068 | # required to be an integer |
| 2069 | if xc == 1: |
| 2070 | if ye >= 0: |
| 2071 | exponent = xe*yc*10**ye |
| 2072 | else: |
| 2073 | exponent, remainder = divmod(xe*yc, 10**-ye) |
| 2074 | if remainder: |
| 2075 | return None |
| 2076 | if y.sign == 1: |
| 2077 | exponent = -exponent |
| 2078 | # if other is a nonnegative integer, use ideal exponent |
| 2079 | if other._isinteger() and other._sign == 0: |
| 2080 | ideal_exponent = self._exp*int(other) |
| 2081 | zeros = min(exponent-ideal_exponent, p-1) |
| 2082 | else: |
| 2083 | zeros = 0 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2084 | return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2085 | |
| 2086 | # case where y is negative: xc must be either a power |
| 2087 | # of 2 or a power of 5. |
| 2088 | if y.sign == 1: |
| 2089 | last_digit = xc % 10 |
| 2090 | if last_digit in (2,4,6,8): |
| 2091 | # quick test for power of 2 |
| 2092 | if xc & -xc != xc: |
| 2093 | return None |
| 2094 | # now xc is a power of 2; e is its exponent |
| 2095 | e = _nbits(xc)-1 |
| 2096 | # find e*y and xe*y; both must be integers |
| 2097 | if ye >= 0: |
| 2098 | y_as_int = yc*10**ye |
| 2099 | e = e*y_as_int |
| 2100 | xe = xe*y_as_int |
| 2101 | else: |
| 2102 | ten_pow = 10**-ye |
| 2103 | e, remainder = divmod(e*yc, ten_pow) |
| 2104 | if remainder: |
| 2105 | return None |
| 2106 | xe, remainder = divmod(xe*yc, ten_pow) |
| 2107 | if remainder: |
| 2108 | return None |
| 2109 | |
| 2110 | if e*65 >= p*93: # 93/65 > log(10)/log(5) |
| 2111 | return None |
| 2112 | xc = 5**e |
| 2113 | |
| 2114 | elif last_digit == 5: |
| 2115 | # e >= log_5(xc) if xc is a power of 5; we have |
| 2116 | # equality all the way up to xc=5**2658 |
| 2117 | e = _nbits(xc)*28//65 |
| 2118 | xc, remainder = divmod(5**e, xc) |
| 2119 | if remainder: |
| 2120 | return None |
| 2121 | while xc % 5 == 0: |
| 2122 | xc //= 5 |
| 2123 | e -= 1 |
| 2124 | if ye >= 0: |
| 2125 | y_as_integer = yc*10**ye |
| 2126 | e = e*y_as_integer |
| 2127 | xe = xe*y_as_integer |
| 2128 | else: |
| 2129 | ten_pow = 10**-ye |
| 2130 | e, remainder = divmod(e*yc, ten_pow) |
| 2131 | if remainder: |
| 2132 | return None |
| 2133 | xe, remainder = divmod(xe*yc, ten_pow) |
| 2134 | if remainder: |
| 2135 | return None |
| 2136 | if e*3 >= p*10: # 10/3 > log(10)/log(2) |
| 2137 | return None |
| 2138 | xc = 2**e |
| 2139 | else: |
| 2140 | return None |
| 2141 | |
| 2142 | if xc >= 10**p: |
| 2143 | return None |
| 2144 | xe = -e-xe |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2145 | return _dec_from_triple(0, str(xc), xe) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2146 | |
| 2147 | # now y is positive; find m and n such that y = m/n |
| 2148 | if ye >= 0: |
| 2149 | m, n = yc*10**ye, 1 |
| 2150 | else: |
| 2151 | if xe != 0 and len(str(abs(yc*xe))) <= -ye: |
| 2152 | return None |
| 2153 | xc_bits = _nbits(xc) |
| 2154 | if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye: |
| 2155 | return None |
| 2156 | m, n = yc, 10**(-ye) |
| 2157 | while m % 2 == n % 2 == 0: |
| 2158 | m //= 2 |
| 2159 | n //= 2 |
| 2160 | while m % 5 == n % 5 == 0: |
| 2161 | m //= 5 |
| 2162 | n //= 5 |
| 2163 | |
| 2164 | # compute nth root of xc*10**xe |
| 2165 | if n > 1: |
| 2166 | # if 1 < xc < 2**n then xc isn't an nth power |
| 2167 | if xc != 1 and xc_bits <= n: |
| 2168 | return None |
| 2169 | |
| 2170 | xe, rem = divmod(xe, n) |
| 2171 | if rem != 0: |
| 2172 | return None |
| 2173 | |
| 2174 | # compute nth root of xc using Newton's method |
| 2175 | a = 1 << -(-_nbits(xc)//n) # initial estimate |
| 2176 | while True: |
| 2177 | q, r = divmod(xc, a**(n-1)) |
| 2178 | if a <= q: |
| 2179 | break |
| 2180 | else: |
| 2181 | a = (a*(n-1) + q)//n |
| 2182 | if not (a == q and r == 0): |
| 2183 | return None |
| 2184 | xc = a |
| 2185 | |
| 2186 | # now xc*10**xe is the nth root of the original xc*10**xe |
| 2187 | # compute mth power of xc*10**xe |
| 2188 | |
| 2189 | # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m > |
| 2190 | # 10**p and the result is not representable. |
| 2191 | if xc > 1 and m > p*100//_log10_lb(xc): |
| 2192 | return None |
| 2193 | xc = xc**m |
| 2194 | xe *= m |
| 2195 | if xc > 10**p: |
| 2196 | return None |
| 2197 | |
| 2198 | # by this point the result *is* exactly representable |
| 2199 | # adjust the exponent to get as close as possible to the ideal |
| 2200 | # exponent, if necessary |
| 2201 | str_xc = str(xc) |
| 2202 | if other._isinteger() and other._sign == 0: |
| 2203 | ideal_exponent = self._exp*int(other) |
| 2204 | zeros = min(xe-ideal_exponent, p-len(str_xc)) |
| 2205 | else: |
| 2206 | zeros = 0 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2207 | return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2208 | |
| 2209 | def __pow__(self, other, modulo=None, context=None): |
| 2210 | """Return self ** other [ % modulo]. |
| 2211 | |
| 2212 | With two arguments, compute self**other. |
| 2213 | |
| 2214 | With three arguments, compute (self**other) % modulo. For the |
| 2215 | three argument form, the following restrictions on the |
| 2216 | arguments hold: |
| 2217 | |
| 2218 | - all three arguments must be integral |
| 2219 | - other must be nonnegative |
| 2220 | - either self or other (or both) must be nonzero |
| 2221 | - modulo must be nonzero and must have at most p digits, |
| 2222 | where p is the context precision. |
| 2223 | |
| 2224 | If any of these restrictions is violated the InvalidOperation |
| 2225 | flag is raised. |
| 2226 | |
| 2227 | The result of pow(self, other, modulo) is identical to the |
| 2228 | result that would be obtained by computing (self**other) % |
| 2229 | modulo with unbounded precision, but is computed more |
| 2230 | efficiently. It is always exact. |
| 2231 | """ |
| 2232 | |
| 2233 | if modulo is not None: |
| 2234 | return self._power_modulo(other, modulo, context) |
| 2235 | |
| 2236 | other = _convert_other(other) |
| 2237 | if other is NotImplemented: |
| 2238 | return other |
| 2239 | |
| 2240 | if context is None: |
| 2241 | context = getcontext() |
| 2242 | |
| 2243 | # either argument is a NaN => result is NaN |
| 2244 | ans = self._check_nans(other, context) |
| 2245 | if ans: |
| 2246 | return ans |
| 2247 | |
| 2248 | # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity) |
| 2249 | if not other: |
| 2250 | if not self: |
| 2251 | return context._raise_error(InvalidOperation, '0 ** 0') |
| 2252 | else: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2253 | return _One |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2254 | |
| 2255 | # result has sign 1 iff self._sign is 1 and other is an odd integer |
| 2256 | result_sign = 0 |
| 2257 | if self._sign == 1: |
| 2258 | if other._isinteger(): |
| 2259 | if not other._iseven(): |
| 2260 | result_sign = 1 |
| 2261 | else: |
| 2262 | # -ve**noninteger = NaN |
| 2263 | # (-0)**noninteger = 0**noninteger |
| 2264 | if self: |
| 2265 | return context._raise_error(InvalidOperation, |
| 2266 | 'x ** y with x negative and y not an integer') |
| 2267 | # negate self, without doing any unwanted rounding |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2268 | self = self.copy_negate() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2269 | |
| 2270 | # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity |
| 2271 | if not self: |
| 2272 | if other._sign == 0: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2273 | return _dec_from_triple(result_sign, '0', 0) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2274 | else: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2275 | return _SignedInfinity[result_sign] |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2276 | |
| 2277 | # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2278 | if self._isinfinity(): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2279 | if other._sign == 0: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2280 | return _SignedInfinity[result_sign] |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2281 | else: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2282 | return _dec_from_triple(result_sign, '0', 0) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2283 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2284 | # 1**other = 1, but the choice of exponent and the flags |
| 2285 | # depend on the exponent of self, and on whether other is a |
| 2286 | # positive integer, a negative integer, or neither |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2287 | if self == _One: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2288 | if other._isinteger(): |
| 2289 | # exp = max(self._exp*max(int(other), 0), |
| 2290 | # 1-context.prec) but evaluating int(other) directly |
| 2291 | # is dangerous until we know other is small (other |
| 2292 | # could be 1e999999999) |
| 2293 | if other._sign == 1: |
| 2294 | multiplier = 0 |
| 2295 | elif other > context.prec: |
| 2296 | multiplier = context.prec |
| 2297 | else: |
| 2298 | multiplier = int(other) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2299 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2300 | exp = self._exp * multiplier |
| 2301 | if exp < 1-context.prec: |
| 2302 | exp = 1-context.prec |
| 2303 | context._raise_error(Rounded) |
| 2304 | else: |
| 2305 | context._raise_error(Inexact) |
| 2306 | context._raise_error(Rounded) |
| 2307 | exp = 1-context.prec |
| 2308 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2309 | return _dec_from_triple(result_sign, '1'+'0'*-exp, exp) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2310 | |
| 2311 | # compute adjusted exponent of self |
| 2312 | self_adj = self.adjusted() |
| 2313 | |
| 2314 | # self ** infinity is infinity if self > 1, 0 if self < 1 |
| 2315 | # self ** -infinity is infinity if self < 1, 0 if self > 1 |
| 2316 | if other._isinfinity(): |
| 2317 | if (other._sign == 0) == (self_adj < 0): |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2318 | return _dec_from_triple(result_sign, '0', 0) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2319 | else: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2320 | return _SignedInfinity[result_sign] |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2321 | |
| 2322 | # from here on, the result always goes through the call |
| 2323 | # to _fix at the end of this function. |
| 2324 | ans = None |
| 2325 | |
| 2326 | # crude test to catch cases of extreme overflow/underflow. If |
| 2327 | # log10(self)*other >= 10**bound and bound >= len(str(Emax)) |
| 2328 | # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence |
| 2329 | # self**other >= 10**(Emax+1), so overflow occurs. The test |
| 2330 | # for underflow is similar. |
| 2331 | bound = self._log10_exp_bound() + other.adjusted() |
| 2332 | if (self_adj >= 0) == (other._sign == 0): |
| 2333 | # self > 1 and other +ve, or self < 1 and other -ve |
| 2334 | # possibility of overflow |
| 2335 | if bound >= len(str(context.Emax)): |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2336 | ans = _dec_from_triple(result_sign, '1', context.Emax+1) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2337 | else: |
| 2338 | # self > 1 and other -ve, or self < 1 and other +ve |
| 2339 | # possibility of underflow to 0 |
| 2340 | Etiny = context.Etiny() |
| 2341 | if bound >= len(str(-Etiny)): |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2342 | ans = _dec_from_triple(result_sign, '1', Etiny-1) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2343 | |
| 2344 | # try for an exact result with precision +1 |
| 2345 | if ans is None: |
| 2346 | ans = self._power_exact(other, context.prec + 1) |
| 2347 | if ans is not None and result_sign == 1: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2348 | ans = _dec_from_triple(1, ans._int, ans._exp) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2349 | |
| 2350 | # usual case: inexact result, x**y computed directly as exp(y*log(x)) |
| 2351 | if ans is None: |
| 2352 | p = context.prec |
| 2353 | x = _WorkRep(self) |
| 2354 | xc, xe = x.int, x.exp |
| 2355 | y = _WorkRep(other) |
| 2356 | yc, ye = y.int, y.exp |
| 2357 | if y.sign == 1: |
| 2358 | yc = -yc |
| 2359 | |
| 2360 | # compute correctly rounded result: start with precision +3, |
| 2361 | # then increase precision until result is unambiguously roundable |
| 2362 | extra = 3 |
| 2363 | while True: |
| 2364 | coeff, exp = _dpower(xc, xe, yc, ye, p+extra) |
| 2365 | if coeff % (5*10**(len(str(coeff))-p-1)): |
| 2366 | break |
| 2367 | extra += 3 |
| 2368 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2369 | ans = _dec_from_triple(result_sign, str(coeff), exp) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2370 | |
| 2371 | # the specification says that for non-integer other we need to |
| 2372 | # raise Inexact, even when the result is actually exact. In |
| 2373 | # the same way, we need to raise Underflow here if the result |
| 2374 | # is subnormal. (The call to _fix will take care of raising |
| 2375 | # Rounded and Subnormal, as usual.) |
| 2376 | if not other._isinteger(): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2377 | context._raise_error(Inexact) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2378 | # pad with zeros up to length context.prec+1 if necessary |
| 2379 | if len(ans._int) <= context.prec: |
| 2380 | expdiff = context.prec+1 - len(ans._int) |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2381 | ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff, |
| 2382 | ans._exp-expdiff) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2383 | if ans.adjusted() < context.Emin: |
| 2384 | context._raise_error(Underflow) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2385 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2386 | # unlike exp, ln and log10, the power function respects the |
| 2387 | # rounding mode; no need to use ROUND_HALF_EVEN here |
| 2388 | ans = ans._fix(context) |
| 2389 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2390 | |
| 2391 | def __rpow__(self, other, context=None): |
| 2392 | """Swaps self/other and returns __pow__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2393 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 2394 | if other is NotImplemented: |
| 2395 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2396 | return other.__pow__(self, context=context) |
| 2397 | |
| 2398 | def normalize(self, context=None): |
| 2399 | """Normalize- strip trailing 0s, change anything equal to 0 to 0e0""" |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2400 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2401 | if context is None: |
| 2402 | context = getcontext() |
| 2403 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2404 | if self._is_special: |
| 2405 | ans = self._check_nans(context=context) |
| 2406 | if ans: |
| 2407 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2408 | |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 2409 | dup = self._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2410 | if dup._isinfinity(): |
| 2411 | return dup |
| 2412 | |
| 2413 | if not dup: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2414 | return _dec_from_triple(dup._sign, '0', 0) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2415 | exp_max = [context.Emax, context.Etop()][context._clamp] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2416 | end = len(dup._int) |
| 2417 | exp = dup._exp |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2418 | while dup._int[end-1] == '0' and exp < exp_max: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2419 | exp += 1 |
| 2420 | end -= 1 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2421 | return _dec_from_triple(dup._sign, dup._int[:end], exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2422 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2423 | def quantize(self, exp, rounding=None, context=None, watchexp=True): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2424 | """Quantize self so its exponent is the same as that of exp. |
| 2425 | |
| 2426 | Similar to self._rescale(exp._exp) but with error checking. |
| 2427 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2428 | exp = _convert_other(exp, raiseit=True) |
| 2429 | |
| 2430 | if context is None: |
| 2431 | context = getcontext() |
| 2432 | if rounding is None: |
| 2433 | rounding = context.rounding |
| 2434 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2435 | if self._is_special or exp._is_special: |
| 2436 | ans = self._check_nans(exp, context) |
| 2437 | if ans: |
| 2438 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2439 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2440 | if exp._isinfinity() or self._isinfinity(): |
| 2441 | if exp._isinfinity() and self._isinfinity(): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2442 | return Decimal(self) # if both are inf, it is OK |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2443 | return context._raise_error(InvalidOperation, |
| 2444 | 'quantize with one INF') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2445 | |
| 2446 | # if we're not watching exponents, do a simple rescale |
| 2447 | if not watchexp: |
| 2448 | ans = self._rescale(exp._exp, rounding) |
| 2449 | # raise Inexact and Rounded where appropriate |
| 2450 | if ans._exp > self._exp: |
| 2451 | context._raise_error(Rounded) |
| 2452 | if ans != self: |
| 2453 | context._raise_error(Inexact) |
| 2454 | return ans |
| 2455 | |
| 2456 | # exp._exp should be between Etiny and Emax |
| 2457 | if not (context.Etiny() <= exp._exp <= context.Emax): |
| 2458 | return context._raise_error(InvalidOperation, |
| 2459 | 'target exponent out of bounds in quantize') |
| 2460 | |
| 2461 | if not self: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2462 | ans = _dec_from_triple(self._sign, '0', exp._exp) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2463 | return ans._fix(context) |
| 2464 | |
| 2465 | self_adjusted = self.adjusted() |
| 2466 | if self_adjusted > context.Emax: |
| 2467 | return context._raise_error(InvalidOperation, |
| 2468 | 'exponent of quantize result too large for current context') |
| 2469 | if self_adjusted - exp._exp + 1 > context.prec: |
| 2470 | return context._raise_error(InvalidOperation, |
| 2471 | 'quantize result has too many digits for current context') |
| 2472 | |
| 2473 | ans = self._rescale(exp._exp, rounding) |
| 2474 | if ans.adjusted() > context.Emax: |
| 2475 | return context._raise_error(InvalidOperation, |
| 2476 | 'exponent of quantize result too large for current context') |
| 2477 | if len(ans._int) > context.prec: |
| 2478 | return context._raise_error(InvalidOperation, |
| 2479 | 'quantize result has too many digits for current context') |
| 2480 | |
| 2481 | # raise appropriate flags |
| 2482 | if ans._exp > self._exp: |
| 2483 | context._raise_error(Rounded) |
| 2484 | if ans != self: |
| 2485 | context._raise_error(Inexact) |
| 2486 | if ans and ans.adjusted() < context.Emin: |
| 2487 | context._raise_error(Subnormal) |
| 2488 | |
| 2489 | # call to fix takes care of any necessary folddown |
| 2490 | ans = ans._fix(context) |
| 2491 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2492 | |
| 2493 | def same_quantum(self, other): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2494 | """Return True if self and other have the same exponent; otherwise |
| 2495 | return False. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2496 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2497 | If either operand is a special value, the following rules are used: |
| 2498 | * return True if both operands are infinities |
| 2499 | * return True if both operands are NaNs |
| 2500 | * otherwise, return False. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2501 | """ |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2502 | other = _convert_other(other, raiseit=True) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2503 | if self._is_special or other._is_special: |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2504 | return (self.is_nan() and other.is_nan() or |
| 2505 | self.is_infinite() and other.is_infinite()) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2506 | return self._exp == other._exp |
| 2507 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2508 | def _rescale(self, exp, rounding): |
| 2509 | """Rescale self so that the exponent is exp, either by padding with zeros |
| 2510 | or by truncating digits, using the given rounding mode. |
| 2511 | |
| 2512 | Specials are returned without change. This operation is |
| 2513 | quiet: it raises no flags, and uses no information from the |
| 2514 | context. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2515 | |
| 2516 | exp = exp to scale to (an integer) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2517 | rounding = rounding mode |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2518 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2519 | if self._is_special: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2520 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2521 | if not self: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2522 | return _dec_from_triple(self._sign, '0', exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2523 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2524 | if self._exp >= exp: |
| 2525 | # pad answer with zeros if necessary |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2526 | return _dec_from_triple(self._sign, |
| 2527 | self._int + '0'*(self._exp - exp), exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2528 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2529 | # too many digits; round and lose data. If self.adjusted() < |
| 2530 | # exp-1, replace self by 10**(exp-1) before rounding |
| 2531 | digits = len(self._int) + self._exp - exp |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2532 | if digits < 0: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2533 | self = _dec_from_triple(self._sign, '1', exp-1) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2534 | digits = 0 |
| 2535 | this_function = getattr(self, self._pick_rounding_function[rounding]) |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 2536 | changed = this_function(digits) |
| 2537 | coeff = self._int[:digits] or '0' |
| 2538 | if changed == 1: |
| 2539 | coeff = str(int(coeff)+1) |
| 2540 | return _dec_from_triple(self._sign, coeff, exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2541 | |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 2542 | def _round(self, places, rounding): |
| 2543 | """Round a nonzero, nonspecial Decimal to a fixed number of |
| 2544 | significant figures, using the given rounding mode. |
| 2545 | |
| 2546 | Infinities, NaNs and zeros are returned unaltered. |
| 2547 | |
| 2548 | This operation is quiet: it raises no flags, and uses no |
| 2549 | information from the context. |
| 2550 | |
| 2551 | """ |
| 2552 | if places <= 0: |
| 2553 | raise ValueError("argument should be at least 1 in _round") |
| 2554 | if self._is_special or not self: |
| 2555 | return Decimal(self) |
| 2556 | ans = self._rescale(self.adjusted()+1-places, rounding) |
| 2557 | # it can happen that the rescale alters the adjusted exponent; |
| 2558 | # for example when rounding 99.97 to 3 significant figures. |
| 2559 | # When this happens we end up with an extra 0 at the end of |
| 2560 | # the number; a second rescale fixes this. |
| 2561 | if ans.adjusted() != self.adjusted(): |
| 2562 | ans = ans._rescale(ans.adjusted()+1-places, rounding) |
| 2563 | return ans |
| 2564 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2565 | def to_integral_exact(self, rounding=None, context=None): |
| 2566 | """Rounds to a nearby integer. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2567 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2568 | If no rounding mode is specified, take the rounding mode from |
| 2569 | the context. This method raises the Rounded and Inexact flags |
| 2570 | when appropriate. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2571 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2572 | See also: to_integral_value, which does exactly the same as |
| 2573 | this method except that it doesn't raise Inexact or Rounded. |
| 2574 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2575 | if self._is_special: |
| 2576 | ans = self._check_nans(context=context) |
| 2577 | if ans: |
| 2578 | return ans |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2579 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2580 | if self._exp >= 0: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2581 | return Decimal(self) |
| 2582 | if not self: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2583 | return _dec_from_triple(self._sign, '0', 0) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2584 | if context is None: |
| 2585 | context = getcontext() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2586 | if rounding is None: |
| 2587 | rounding = context.rounding |
| 2588 | context._raise_error(Rounded) |
| 2589 | ans = self._rescale(0, rounding) |
| 2590 | if ans != self: |
| 2591 | context._raise_error(Inexact) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2592 | return ans |
| 2593 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2594 | def to_integral_value(self, rounding=None, context=None): |
| 2595 | """Rounds to the nearest integer, without raising inexact, rounded.""" |
| 2596 | if context is None: |
| 2597 | context = getcontext() |
| 2598 | if rounding is None: |
| 2599 | rounding = context.rounding |
| 2600 | if self._is_special: |
| 2601 | ans = self._check_nans(context=context) |
| 2602 | if ans: |
| 2603 | return ans |
| 2604 | return Decimal(self) |
| 2605 | if self._exp >= 0: |
| 2606 | return Decimal(self) |
| 2607 | else: |
| 2608 | return self._rescale(0, rounding) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2609 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2610 | # the method name changed, but we provide also the old one, for compatibility |
| 2611 | to_integral = to_integral_value |
| 2612 | |
| 2613 | def sqrt(self, context=None): |
| 2614 | """Return the square root of self.""" |
Christian Heimes | 0348fb6 | 2008-03-26 12:55:56 +0000 | [diff] [blame] | 2615 | if context is None: |
| 2616 | context = getcontext() |
| 2617 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2618 | if self._is_special: |
| 2619 | ans = self._check_nans(context=context) |
| 2620 | if ans: |
| 2621 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2622 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2623 | if self._isinfinity() and self._sign == 0: |
| 2624 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2625 | |
| 2626 | if not self: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2627 | # exponent = self._exp // 2. sqrt(-0) = -0 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2628 | ans = _dec_from_triple(self._sign, '0', self._exp // 2) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2629 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2630 | |
| 2631 | if self._sign == 1: |
| 2632 | return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0') |
| 2633 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2634 | # At this point self represents a positive number. Let p be |
| 2635 | # the desired precision and express self in the form c*100**e |
| 2636 | # with c a positive real number and e an integer, c and e |
| 2637 | # being chosen so that 100**(p-1) <= c < 100**p. Then the |
| 2638 | # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1) |
| 2639 | # <= sqrt(c) < 10**p, so the closest representable Decimal at |
| 2640 | # precision p is n*10**e where n = round_half_even(sqrt(c)), |
| 2641 | # the closest integer to sqrt(c) with the even integer chosen |
| 2642 | # in the case of a tie. |
| 2643 | # |
| 2644 | # To ensure correct rounding in all cases, we use the |
| 2645 | # following trick: we compute the square root to an extra |
| 2646 | # place (precision p+1 instead of precision p), rounding down. |
| 2647 | # Then, if the result is inexact and its last digit is 0 or 5, |
| 2648 | # we increase the last digit to 1 or 6 respectively; if it's |
| 2649 | # exact we leave the last digit alone. Now the final round to |
| 2650 | # p places (or fewer in the case of underflow) will round |
| 2651 | # correctly and raise the appropriate flags. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2652 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2653 | # use an extra digit of precision |
| 2654 | prec = context.prec+1 |
| 2655 | |
| 2656 | # write argument in the form c*100**e where e = self._exp//2 |
| 2657 | # is the 'ideal' exponent, to be used if the square root is |
| 2658 | # exactly representable. l is the number of 'digits' of c in |
| 2659 | # base 100, so that 100**(l-1) <= c < 100**l. |
| 2660 | op = _WorkRep(self) |
| 2661 | e = op.exp >> 1 |
| 2662 | if op.exp & 1: |
| 2663 | c = op.int * 10 |
| 2664 | l = (len(self._int) >> 1) + 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2665 | else: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2666 | c = op.int |
| 2667 | l = len(self._int)+1 >> 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2668 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2669 | # rescale so that c has exactly prec base 100 'digits' |
| 2670 | shift = prec-l |
| 2671 | if shift >= 0: |
| 2672 | c *= 100**shift |
| 2673 | exact = True |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2674 | else: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2675 | c, remainder = divmod(c, 100**-shift) |
| 2676 | exact = not remainder |
| 2677 | e -= shift |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2678 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2679 | # find n = floor(sqrt(c)) using Newton's method |
| 2680 | n = 10**prec |
| 2681 | while True: |
| 2682 | q = c//n |
| 2683 | if n <= q: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2684 | break |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2685 | else: |
| 2686 | n = n + q >> 1 |
| 2687 | exact = exact and n*n == c |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2688 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2689 | if exact: |
| 2690 | # result is exact; rescale to use ideal exponent e |
| 2691 | if shift >= 0: |
| 2692 | # assert n % 10**shift == 0 |
| 2693 | n //= 10**shift |
| 2694 | else: |
| 2695 | n *= 10**-shift |
| 2696 | e += shift |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2697 | else: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2698 | # result is not exact; fix last digit as described above |
| 2699 | if n % 5 == 0: |
| 2700 | n += 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2701 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2702 | ans = _dec_from_triple(0, str(n), e) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2703 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2704 | # round, and fit to current context |
| 2705 | context = context._shallow_copy() |
| 2706 | rounding = context._set_rounding(ROUND_HALF_EVEN) |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 2707 | ans = ans._fix(context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2708 | context.rounding = rounding |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2709 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2710 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2711 | |
| 2712 | def max(self, other, context=None): |
| 2713 | """Returns the larger value. |
| 2714 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2715 | Like max(self, other) except if one is not a number, returns |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2716 | NaN (and signals if one is sNaN). Also rounds. |
| 2717 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2718 | other = _convert_other(other, raiseit=True) |
| 2719 | |
| 2720 | if context is None: |
| 2721 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2722 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2723 | if self._is_special or other._is_special: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2724 | # 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] | 2725 | # number is always returned |
| 2726 | sn = self._isnan() |
| 2727 | on = other._isnan() |
| 2728 | if sn or on: |
Facundo Batista | 708d581 | 2008-12-11 04:20:07 +0000 | [diff] [blame] | 2729 | if on == 1 and sn == 0: |
| 2730 | return self._fix(context) |
| 2731 | if sn == 1 and on == 0: |
| 2732 | return other._fix(context) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2733 | return self._check_nans(other, context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2734 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 2735 | c = self._cmp(other) |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2736 | if c == 0: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2737 | # If both operands are finite and equal in numerical value |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2738 | # then an ordering is applied: |
| 2739 | # |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2740 | # If the signs differ then max returns the operand with the |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2741 | # positive sign and min returns the operand with the negative sign |
| 2742 | # |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2743 | # 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] | 2744 | # the result. This is exactly the ordering used in compare_total. |
| 2745 | c = self.compare_total(other) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2746 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2747 | if c == -1: |
| 2748 | ans = other |
| 2749 | else: |
| 2750 | ans = self |
| 2751 | |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 2752 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2753 | |
| 2754 | def min(self, other, context=None): |
| 2755 | """Returns the smaller value. |
| 2756 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2757 | Like min(self, other) except if one is not a number, returns |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2758 | NaN (and signals if one is sNaN). Also rounds. |
| 2759 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2760 | other = _convert_other(other, raiseit=True) |
| 2761 | |
| 2762 | if context is None: |
| 2763 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2764 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2765 | if self._is_special or other._is_special: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2766 | # 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] | 2767 | # number is always returned |
| 2768 | sn = self._isnan() |
| 2769 | on = other._isnan() |
| 2770 | if sn or on: |
Facundo Batista | 708d581 | 2008-12-11 04:20:07 +0000 | [diff] [blame] | 2771 | if on == 1 and sn == 0: |
| 2772 | return self._fix(context) |
| 2773 | if sn == 1 and on == 0: |
| 2774 | return other._fix(context) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2775 | return self._check_nans(other, context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2776 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 2777 | c = self._cmp(other) |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2778 | if c == 0: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2779 | c = self.compare_total(other) |
| 2780 | |
| 2781 | if c == -1: |
| 2782 | ans = self |
| 2783 | else: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2784 | ans = other |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2785 | |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 2786 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2787 | |
| 2788 | def _isinteger(self): |
| 2789 | """Returns whether self is an integer""" |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2790 | if self._is_special: |
| 2791 | return False |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2792 | if self._exp >= 0: |
| 2793 | return True |
| 2794 | rest = self._int[self._exp:] |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2795 | return rest == '0'*len(rest) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2796 | |
| 2797 | def _iseven(self): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2798 | """Returns True if self is even. Assumes self is an integer.""" |
| 2799 | if not self or self._exp > 0: |
| 2800 | return True |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2801 | return self._int[-1+self._exp] in '02468' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2802 | |
| 2803 | def adjusted(self): |
| 2804 | """Return the adjusted exponent of self""" |
| 2805 | try: |
| 2806 | return self._exp + len(self._int) - 1 |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2807 | # If NaN or Infinity, self._exp is string |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2808 | except TypeError: |
| 2809 | return 0 |
| 2810 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2811 | def canonical(self, context=None): |
| 2812 | """Returns the same Decimal object. |
| 2813 | |
| 2814 | As we do not have different encodings for the same number, the |
| 2815 | received object already is in its canonical form. |
| 2816 | """ |
| 2817 | return self |
| 2818 | |
| 2819 | def compare_signal(self, other, context=None): |
| 2820 | """Compares self to the other operand numerically. |
| 2821 | |
| 2822 | It's pretty much like compare(), but all NaNs signal, with signaling |
| 2823 | NaNs taking precedence over quiet NaNs. |
| 2824 | """ |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 2825 | other = _convert_other(other, raiseit = True) |
| 2826 | ans = self._compare_check_nans(other, context) |
| 2827 | if ans: |
| 2828 | return ans |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2829 | return self.compare(other, context=context) |
| 2830 | |
| 2831 | def compare_total(self, other): |
| 2832 | """Compares self to other using the abstract representations. |
| 2833 | |
| 2834 | This is not like the standard compare, which use their numerical |
| 2835 | value. Note that a total ordering is defined for all possible abstract |
| 2836 | representations. |
| 2837 | """ |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 2838 | other = _convert_other(other, raiseit=True) |
| 2839 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2840 | # if one is negative and the other is positive, it's easy |
| 2841 | if self._sign and not other._sign: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2842 | return _NegativeOne |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2843 | if not self._sign and other._sign: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2844 | return _One |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2845 | sign = self._sign |
| 2846 | |
| 2847 | # let's handle both NaN types |
| 2848 | self_nan = self._isnan() |
| 2849 | other_nan = other._isnan() |
| 2850 | if self_nan or other_nan: |
| 2851 | if self_nan == other_nan: |
Mark Dickinson | d314e1b | 2009-08-28 13:39:53 +0000 | [diff] [blame] | 2852 | # compare payloads as though they're integers |
| 2853 | self_key = len(self._int), self._int |
| 2854 | other_key = len(other._int), other._int |
| 2855 | if self_key < other_key: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2856 | if sign: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2857 | return _One |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2858 | else: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2859 | return _NegativeOne |
Mark Dickinson | d314e1b | 2009-08-28 13:39:53 +0000 | [diff] [blame] | 2860 | if self_key > other_key: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2861 | if sign: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2862 | return _NegativeOne |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2863 | else: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2864 | return _One |
| 2865 | return _Zero |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2866 | |
| 2867 | if sign: |
| 2868 | if self_nan == 1: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2869 | return _NegativeOne |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2870 | if other_nan == 1: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2871 | return _One |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2872 | if self_nan == 2: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2873 | return _NegativeOne |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2874 | if other_nan == 2: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2875 | return _One |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2876 | else: |
| 2877 | if self_nan == 1: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2878 | return _One |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2879 | if other_nan == 1: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2880 | return _NegativeOne |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2881 | if self_nan == 2: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2882 | return _One |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2883 | if other_nan == 2: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2884 | return _NegativeOne |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2885 | |
| 2886 | if self < other: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2887 | return _NegativeOne |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2888 | if self > other: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2889 | return _One |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2890 | |
| 2891 | if self._exp < other._exp: |
| 2892 | if sign: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2893 | return _One |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2894 | else: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2895 | return _NegativeOne |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2896 | if self._exp > other._exp: |
| 2897 | if sign: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2898 | return _NegativeOne |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2899 | else: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2900 | return _One |
| 2901 | return _Zero |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2902 | |
| 2903 | |
| 2904 | def compare_total_mag(self, other): |
| 2905 | """Compares self to other using abstract repr., ignoring sign. |
| 2906 | |
| 2907 | Like compare_total, but with operand's sign ignored and assumed to be 0. |
| 2908 | """ |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 2909 | other = _convert_other(other, raiseit=True) |
| 2910 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2911 | s = self.copy_abs() |
| 2912 | o = other.copy_abs() |
| 2913 | return s.compare_total(o) |
| 2914 | |
| 2915 | def copy_abs(self): |
| 2916 | """Returns a copy with the sign set to 0. """ |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2917 | return _dec_from_triple(0, self._int, self._exp, self._is_special) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2918 | |
| 2919 | def copy_negate(self): |
| 2920 | """Returns a copy with the sign inverted.""" |
| 2921 | if self._sign: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2922 | return _dec_from_triple(0, self._int, self._exp, self._is_special) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2923 | else: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2924 | return _dec_from_triple(1, self._int, self._exp, self._is_special) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2925 | |
| 2926 | def copy_sign(self, other): |
| 2927 | """Returns self with the sign of other.""" |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 2928 | other = _convert_other(other, raiseit=True) |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2929 | return _dec_from_triple(other._sign, self._int, |
| 2930 | self._exp, self._is_special) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2931 | |
| 2932 | def exp(self, context=None): |
| 2933 | """Returns e ** self.""" |
| 2934 | |
| 2935 | if context is None: |
| 2936 | context = getcontext() |
| 2937 | |
| 2938 | # exp(NaN) = NaN |
| 2939 | ans = self._check_nans(context=context) |
| 2940 | if ans: |
| 2941 | return ans |
| 2942 | |
| 2943 | # exp(-Infinity) = 0 |
| 2944 | if self._isinfinity() == -1: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2945 | return _Zero |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2946 | |
| 2947 | # exp(0) = 1 |
| 2948 | if not self: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2949 | return _One |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2950 | |
| 2951 | # exp(Infinity) = Infinity |
| 2952 | if self._isinfinity() == 1: |
| 2953 | return Decimal(self) |
| 2954 | |
| 2955 | # the result is now guaranteed to be inexact (the true |
| 2956 | # mathematical result is transcendental). There's no need to |
| 2957 | # raise Rounded and Inexact here---they'll always be raised as |
| 2958 | # a result of the call to _fix. |
| 2959 | p = context.prec |
| 2960 | adj = self.adjusted() |
| 2961 | |
| 2962 | # we only need to do any computation for quite a small range |
| 2963 | # of adjusted exponents---for example, -29 <= adj <= 10 for |
| 2964 | # the default context. For smaller exponent the result is |
| 2965 | # indistinguishable from 1 at the given precision, while for |
| 2966 | # larger exponent the result either overflows or underflows. |
| 2967 | if self._sign == 0 and adj > len(str((context.Emax+1)*3)): |
| 2968 | # overflow |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2969 | ans = _dec_from_triple(0, '1', context.Emax+1) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2970 | elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)): |
| 2971 | # underflow to 0 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2972 | ans = _dec_from_triple(0, '1', context.Etiny()-1) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2973 | elif self._sign == 0 and adj < -p: |
| 2974 | # p+1 digits; final round will raise correct flags |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2975 | ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2976 | elif self._sign == 1 and adj < -p-1: |
| 2977 | # p+1 digits; final round will raise correct flags |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2978 | ans = _dec_from_triple(0, '9'*(p+1), -p-1) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2979 | # general case |
| 2980 | else: |
| 2981 | op = _WorkRep(self) |
| 2982 | c, e = op.int, op.exp |
| 2983 | if op.sign == 1: |
| 2984 | c = -c |
| 2985 | |
| 2986 | # compute correctly rounded result: increase precision by |
| 2987 | # 3 digits at a time until we get an unambiguously |
| 2988 | # roundable result |
| 2989 | extra = 3 |
| 2990 | while True: |
| 2991 | coeff, exp = _dexp(c, e, p+extra) |
| 2992 | if coeff % (5*10**(len(str(coeff))-p-1)): |
| 2993 | break |
| 2994 | extra += 3 |
| 2995 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2996 | ans = _dec_from_triple(0, str(coeff), exp) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2997 | |
| 2998 | # at this stage, ans should round correctly with *any* |
| 2999 | # rounding mode, not just with ROUND_HALF_EVEN |
| 3000 | context = context._shallow_copy() |
| 3001 | rounding = context._set_rounding(ROUND_HALF_EVEN) |
| 3002 | ans = ans._fix(context) |
| 3003 | context.rounding = rounding |
| 3004 | |
| 3005 | return ans |
| 3006 | |
| 3007 | def is_canonical(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3008 | """Return True if self is canonical; otherwise return False. |
| 3009 | |
| 3010 | Currently, the encoding of a Decimal instance is always |
| 3011 | canonical, so this method returns True for any Decimal. |
| 3012 | """ |
| 3013 | return True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3014 | |
| 3015 | def is_finite(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3016 | """Return True if self is finite; otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3017 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3018 | A Decimal instance is considered finite if it is neither |
| 3019 | infinite nor a NaN. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3020 | """ |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3021 | return not self._is_special |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3022 | |
| 3023 | def is_infinite(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3024 | """Return True if self is infinite; otherwise return False.""" |
| 3025 | return self._exp == 'F' |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3026 | |
| 3027 | def is_nan(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3028 | """Return True if self is a qNaN or sNaN; otherwise return False.""" |
| 3029 | return self._exp in ('n', 'N') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3030 | |
| 3031 | def is_normal(self, context=None): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3032 | """Return True if self is a normal number; otherwise return False.""" |
| 3033 | if self._is_special or not self: |
| 3034 | return False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3035 | if context is None: |
| 3036 | context = getcontext() |
Mark Dickinson | 06bb674 | 2009-10-20 13:38:04 +0000 | [diff] [blame] | 3037 | return context.Emin <= self.adjusted() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3038 | |
| 3039 | def is_qnan(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3040 | """Return True if self is a quiet NaN; otherwise return False.""" |
| 3041 | return self._exp == 'n' |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3042 | |
| 3043 | def is_signed(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3044 | """Return True if self is negative; otherwise return False.""" |
| 3045 | return self._sign == 1 |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3046 | |
| 3047 | def is_snan(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3048 | """Return True if self is a signaling NaN; otherwise return False.""" |
| 3049 | return self._exp == 'N' |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3050 | |
| 3051 | def is_subnormal(self, context=None): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3052 | """Return True if self is subnormal; otherwise return False.""" |
| 3053 | if self._is_special or not self: |
| 3054 | return False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3055 | if context is None: |
| 3056 | context = getcontext() |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3057 | return self.adjusted() < context.Emin |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3058 | |
| 3059 | def is_zero(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3060 | """Return True if self is a zero; otherwise return False.""" |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3061 | return not self._is_special and self._int == '0' |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3062 | |
| 3063 | def _ln_exp_bound(self): |
| 3064 | """Compute a lower bound for the adjusted exponent of self.ln(). |
| 3065 | In other words, compute r such that self.ln() >= 10**r. Assumes |
| 3066 | that self is finite and positive and that self != 1. |
| 3067 | """ |
| 3068 | |
| 3069 | # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1 |
| 3070 | adj = self._exp + len(self._int) - 1 |
| 3071 | if adj >= 1: |
| 3072 | # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10) |
| 3073 | return len(str(adj*23//10)) - 1 |
| 3074 | if adj <= -2: |
| 3075 | # argument <= 0.1 |
| 3076 | return len(str((-1-adj)*23//10)) - 1 |
| 3077 | op = _WorkRep(self) |
| 3078 | c, e = op.int, op.exp |
| 3079 | if adj == 0: |
| 3080 | # 1 < self < 10 |
| 3081 | num = str(c-10**-e) |
| 3082 | den = str(c) |
| 3083 | return len(num) - len(den) - (num < den) |
| 3084 | # adj == -1, 0.1 <= self < 1 |
| 3085 | return e + len(str(10**-e - c)) - 1 |
| 3086 | |
| 3087 | |
| 3088 | def ln(self, context=None): |
| 3089 | """Returns the natural (base e) logarithm of self.""" |
| 3090 | |
| 3091 | if context is None: |
| 3092 | context = getcontext() |
| 3093 | |
| 3094 | # ln(NaN) = NaN |
| 3095 | ans = self._check_nans(context=context) |
| 3096 | if ans: |
| 3097 | return ans |
| 3098 | |
| 3099 | # ln(0.0) == -Infinity |
| 3100 | if not self: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3101 | return _NegativeInfinity |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3102 | |
| 3103 | # ln(Infinity) = Infinity |
| 3104 | if self._isinfinity() == 1: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3105 | return _Infinity |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3106 | |
| 3107 | # ln(1.0) == 0.0 |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3108 | if self == _One: |
| 3109 | return _Zero |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3110 | |
| 3111 | # ln(negative) raises InvalidOperation |
| 3112 | if self._sign == 1: |
| 3113 | return context._raise_error(InvalidOperation, |
| 3114 | 'ln of a negative value') |
| 3115 | |
| 3116 | # result is irrational, so necessarily inexact |
| 3117 | op = _WorkRep(self) |
| 3118 | c, e = op.int, op.exp |
| 3119 | p = context.prec |
| 3120 | |
| 3121 | # correctly rounded result: repeatedly increase precision by 3 |
| 3122 | # until we get an unambiguously roundable result |
| 3123 | places = p - self._ln_exp_bound() + 2 # at least p+3 places |
| 3124 | while True: |
| 3125 | coeff = _dlog(c, e, places) |
| 3126 | # assert len(str(abs(coeff)))-p >= 1 |
| 3127 | if coeff % (5*10**(len(str(abs(coeff)))-p-1)): |
| 3128 | break |
| 3129 | places += 3 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3130 | ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3131 | |
| 3132 | context = context._shallow_copy() |
| 3133 | rounding = context._set_rounding(ROUND_HALF_EVEN) |
| 3134 | ans = ans._fix(context) |
| 3135 | context.rounding = rounding |
| 3136 | return ans |
| 3137 | |
| 3138 | def _log10_exp_bound(self): |
| 3139 | """Compute a lower bound for the adjusted exponent of self.log10(). |
| 3140 | In other words, find r such that self.log10() >= 10**r. |
| 3141 | Assumes that self is finite and positive and that self != 1. |
| 3142 | """ |
| 3143 | |
| 3144 | # For x >= 10 or x < 0.1 we only need a bound on the integer |
| 3145 | # part of log10(self), and this comes directly from the |
| 3146 | # exponent of x. For 0.1 <= x <= 10 we use the inequalities |
| 3147 | # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| > |
| 3148 | # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0 |
| 3149 | |
| 3150 | adj = self._exp + len(self._int) - 1 |
| 3151 | if adj >= 1: |
| 3152 | # self >= 10 |
| 3153 | return len(str(adj))-1 |
| 3154 | if adj <= -2: |
| 3155 | # self < 0.1 |
| 3156 | return len(str(-1-adj))-1 |
| 3157 | op = _WorkRep(self) |
| 3158 | c, e = op.int, op.exp |
| 3159 | if adj == 0: |
| 3160 | # 1 < self < 10 |
| 3161 | num = str(c-10**-e) |
| 3162 | den = str(231*c) |
| 3163 | return len(num) - len(den) - (num < den) + 2 |
| 3164 | # adj == -1, 0.1 <= self < 1 |
| 3165 | num = str(10**-e-c) |
| 3166 | return len(num) + e - (num < "231") - 1 |
| 3167 | |
| 3168 | def log10(self, context=None): |
| 3169 | """Returns the base 10 logarithm of self.""" |
| 3170 | |
| 3171 | if context is None: |
| 3172 | context = getcontext() |
| 3173 | |
| 3174 | # log10(NaN) = NaN |
| 3175 | ans = self._check_nans(context=context) |
| 3176 | if ans: |
| 3177 | return ans |
| 3178 | |
| 3179 | # log10(0.0) == -Infinity |
| 3180 | if not self: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3181 | return _NegativeInfinity |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3182 | |
| 3183 | # log10(Infinity) = Infinity |
| 3184 | if self._isinfinity() == 1: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3185 | return _Infinity |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3186 | |
| 3187 | # log10(negative or -Infinity) raises InvalidOperation |
| 3188 | if self._sign == 1: |
| 3189 | return context._raise_error(InvalidOperation, |
| 3190 | 'log10 of a negative value') |
| 3191 | |
| 3192 | # log10(10**n) = n |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3193 | 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] | 3194 | # answer may need rounding |
| 3195 | ans = Decimal(self._exp + len(self._int) - 1) |
| 3196 | else: |
| 3197 | # result is irrational, so necessarily inexact |
| 3198 | op = _WorkRep(self) |
| 3199 | c, e = op.int, op.exp |
| 3200 | p = context.prec |
| 3201 | |
| 3202 | # correctly rounded result: repeatedly increase precision |
| 3203 | # until result is unambiguously roundable |
| 3204 | places = p-self._log10_exp_bound()+2 |
| 3205 | while True: |
| 3206 | coeff = _dlog10(c, e, places) |
| 3207 | # assert len(str(abs(coeff)))-p >= 1 |
| 3208 | if coeff % (5*10**(len(str(abs(coeff)))-p-1)): |
| 3209 | break |
| 3210 | places += 3 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3211 | ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3212 | |
| 3213 | context = context._shallow_copy() |
| 3214 | rounding = context._set_rounding(ROUND_HALF_EVEN) |
| 3215 | ans = ans._fix(context) |
| 3216 | context.rounding = rounding |
| 3217 | return ans |
| 3218 | |
| 3219 | def logb(self, context=None): |
| 3220 | """ Returns the exponent of the magnitude of self's MSD. |
| 3221 | |
| 3222 | The result is the integer which is the exponent of the magnitude |
| 3223 | of the most significant digit of self (as though it were truncated |
| 3224 | to a single digit while maintaining the value of that digit and |
| 3225 | without limiting the resulting exponent). |
| 3226 | """ |
| 3227 | # logb(NaN) = NaN |
| 3228 | ans = self._check_nans(context=context) |
| 3229 | if ans: |
| 3230 | return ans |
| 3231 | |
| 3232 | if context is None: |
| 3233 | context = getcontext() |
| 3234 | |
| 3235 | # logb(+/-Inf) = +Inf |
| 3236 | if self._isinfinity(): |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3237 | return _Infinity |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3238 | |
| 3239 | # logb(0) = -Inf, DivisionByZero |
| 3240 | if not self: |
| 3241 | return context._raise_error(DivisionByZero, 'logb(0)', 1) |
| 3242 | |
| 3243 | # otherwise, simply return the adjusted exponent of self, as a |
| 3244 | # Decimal. Note that no attempt is made to fit the result |
| 3245 | # into the current context. |
Mark Dickinson | 56df887 | 2009-10-07 19:23:50 +0000 | [diff] [blame] | 3246 | ans = Decimal(self.adjusted()) |
| 3247 | return ans._fix(context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3248 | |
| 3249 | def _islogical(self): |
| 3250 | """Return True if self is a logical operand. |
| 3251 | |
Christian Heimes | 679db4a | 2008-01-18 09:56:22 +0000 | [diff] [blame] | 3252 | 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] | 3253 | an exponent of 0, and a coefficient whose digits must all be |
| 3254 | either 0 or 1. |
| 3255 | """ |
| 3256 | if self._sign != 0 or self._exp != 0: |
| 3257 | return False |
| 3258 | for dig in self._int: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3259 | if dig not in '01': |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3260 | return False |
| 3261 | return True |
| 3262 | |
| 3263 | def _fill_logical(self, context, opa, opb): |
| 3264 | dif = context.prec - len(opa) |
| 3265 | if dif > 0: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3266 | opa = '0'*dif + opa |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3267 | elif dif < 0: |
| 3268 | opa = opa[-context.prec:] |
| 3269 | dif = context.prec - len(opb) |
| 3270 | if dif > 0: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3271 | opb = '0'*dif + opb |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3272 | elif dif < 0: |
| 3273 | opb = opb[-context.prec:] |
| 3274 | return opa, opb |
| 3275 | |
| 3276 | def logical_and(self, other, context=None): |
| 3277 | """Applies an 'and' operation between self and other's digits.""" |
| 3278 | if context is None: |
| 3279 | context = getcontext() |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 3280 | |
| 3281 | other = _convert_other(other, raiseit=True) |
| 3282 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3283 | if not self._islogical() or not other._islogical(): |
| 3284 | return context._raise_error(InvalidOperation) |
| 3285 | |
| 3286 | # fill to context.prec |
| 3287 | (opa, opb) = self._fill_logical(context, self._int, other._int) |
| 3288 | |
| 3289 | # make the operation, and clean starting zeroes |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3290 | result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)]) |
| 3291 | return _dec_from_triple(0, result.lstrip('0') or '0', 0) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3292 | |
| 3293 | def logical_invert(self, context=None): |
| 3294 | """Invert all its digits.""" |
| 3295 | if context is None: |
| 3296 | context = getcontext() |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3297 | return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0), |
| 3298 | context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3299 | |
| 3300 | def logical_or(self, other, context=None): |
| 3301 | """Applies an 'or' operation between self and other's digits.""" |
| 3302 | if context is None: |
| 3303 | context = getcontext() |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 3304 | |
| 3305 | other = _convert_other(other, raiseit=True) |
| 3306 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3307 | if not self._islogical() or not other._islogical(): |
| 3308 | return context._raise_error(InvalidOperation) |
| 3309 | |
| 3310 | # fill to context.prec |
| 3311 | (opa, opb) = self._fill_logical(context, self._int, other._int) |
| 3312 | |
| 3313 | # make the operation, and clean starting zeroes |
Mark Dickinson | 315a20a | 2009-01-04 21:34:18 +0000 | [diff] [blame] | 3314 | result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)]) |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3315 | return _dec_from_triple(0, result.lstrip('0') or '0', 0) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3316 | |
| 3317 | def logical_xor(self, other, context=None): |
| 3318 | """Applies an 'xor' operation between self and other's digits.""" |
| 3319 | if context is None: |
| 3320 | context = getcontext() |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 3321 | |
| 3322 | other = _convert_other(other, raiseit=True) |
| 3323 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3324 | if not self._islogical() or not other._islogical(): |
| 3325 | return context._raise_error(InvalidOperation) |
| 3326 | |
| 3327 | # fill to context.prec |
| 3328 | (opa, opb) = self._fill_logical(context, self._int, other._int) |
| 3329 | |
| 3330 | # make the operation, and clean starting zeroes |
Mark Dickinson | 315a20a | 2009-01-04 21:34:18 +0000 | [diff] [blame] | 3331 | result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)]) |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3332 | return _dec_from_triple(0, result.lstrip('0') or '0', 0) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3333 | |
| 3334 | def max_mag(self, other, context=None): |
| 3335 | """Compares the values numerically with their sign ignored.""" |
| 3336 | other = _convert_other(other, raiseit=True) |
| 3337 | |
| 3338 | if context is None: |
| 3339 | context = getcontext() |
| 3340 | |
| 3341 | if self._is_special or other._is_special: |
| 3342 | # If one operand is a quiet NaN and the other is number, then the |
| 3343 | # number is always returned |
| 3344 | sn = self._isnan() |
| 3345 | on = other._isnan() |
| 3346 | if sn or on: |
Facundo Batista | 708d581 | 2008-12-11 04:20:07 +0000 | [diff] [blame] | 3347 | if on == 1 and sn == 0: |
| 3348 | return self._fix(context) |
| 3349 | if sn == 1 and on == 0: |
| 3350 | return other._fix(context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3351 | return self._check_nans(other, context) |
| 3352 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 3353 | c = self.copy_abs()._cmp(other.copy_abs()) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3354 | if c == 0: |
| 3355 | c = self.compare_total(other) |
| 3356 | |
| 3357 | if c == -1: |
| 3358 | ans = other |
| 3359 | else: |
| 3360 | ans = self |
| 3361 | |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 3362 | return ans._fix(context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3363 | |
| 3364 | def min_mag(self, other, context=None): |
| 3365 | """Compares the values numerically with their sign ignored.""" |
| 3366 | other = _convert_other(other, raiseit=True) |
| 3367 | |
| 3368 | if context is None: |
| 3369 | context = getcontext() |
| 3370 | |
| 3371 | if self._is_special or other._is_special: |
| 3372 | # If one operand is a quiet NaN and the other is number, then the |
| 3373 | # number is always returned |
| 3374 | sn = self._isnan() |
| 3375 | on = other._isnan() |
| 3376 | if sn or on: |
Facundo Batista | 708d581 | 2008-12-11 04:20:07 +0000 | [diff] [blame] | 3377 | if on == 1 and sn == 0: |
| 3378 | return self._fix(context) |
| 3379 | if sn == 1 and on == 0: |
| 3380 | return other._fix(context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3381 | return self._check_nans(other, context) |
| 3382 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 3383 | c = self.copy_abs()._cmp(other.copy_abs()) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3384 | if c == 0: |
| 3385 | c = self.compare_total(other) |
| 3386 | |
| 3387 | if c == -1: |
| 3388 | ans = self |
| 3389 | else: |
| 3390 | ans = other |
| 3391 | |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 3392 | return ans._fix(context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3393 | |
| 3394 | def next_minus(self, context=None): |
| 3395 | """Returns the largest representable number smaller than itself.""" |
| 3396 | if context is None: |
| 3397 | context = getcontext() |
| 3398 | |
| 3399 | ans = self._check_nans(context=context) |
| 3400 | if ans: |
| 3401 | return ans |
| 3402 | |
| 3403 | if self._isinfinity() == -1: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3404 | return _NegativeInfinity |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3405 | if self._isinfinity() == 1: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3406 | return _dec_from_triple(0, '9'*context.prec, context.Etop()) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3407 | |
| 3408 | context = context.copy() |
| 3409 | context._set_rounding(ROUND_FLOOR) |
| 3410 | context._ignore_all_flags() |
| 3411 | new_self = self._fix(context) |
| 3412 | if new_self != self: |
| 3413 | return new_self |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3414 | return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1), |
| 3415 | context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3416 | |
| 3417 | def next_plus(self, context=None): |
| 3418 | """Returns the smallest representable number larger than itself.""" |
| 3419 | if context is None: |
| 3420 | context = getcontext() |
| 3421 | |
| 3422 | ans = self._check_nans(context=context) |
| 3423 | if ans: |
| 3424 | return ans |
| 3425 | |
| 3426 | if self._isinfinity() == 1: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3427 | return _Infinity |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3428 | if self._isinfinity() == -1: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3429 | return _dec_from_triple(1, '9'*context.prec, context.Etop()) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3430 | |
| 3431 | context = context.copy() |
| 3432 | context._set_rounding(ROUND_CEILING) |
| 3433 | context._ignore_all_flags() |
| 3434 | new_self = self._fix(context) |
| 3435 | if new_self != self: |
| 3436 | return new_self |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3437 | return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1), |
| 3438 | context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3439 | |
| 3440 | def next_toward(self, other, context=None): |
| 3441 | """Returns the number closest to self, in the direction towards other. |
| 3442 | |
| 3443 | The result is the closest representable number to self |
| 3444 | (excluding self) that is in the direction towards other, |
| 3445 | unless both have the same value. If the two operands are |
| 3446 | numerically equal, then the result is a copy of self with the |
| 3447 | sign set to be the same as the sign of other. |
| 3448 | """ |
| 3449 | other = _convert_other(other, raiseit=True) |
| 3450 | |
| 3451 | if context is None: |
| 3452 | context = getcontext() |
| 3453 | |
| 3454 | ans = self._check_nans(other, context) |
| 3455 | if ans: |
| 3456 | return ans |
| 3457 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 3458 | comparison = self._cmp(other) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3459 | if comparison == 0: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3460 | return self.copy_sign(other) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3461 | |
| 3462 | if comparison == -1: |
| 3463 | ans = self.next_plus(context) |
| 3464 | else: # comparison == 1 |
| 3465 | ans = self.next_minus(context) |
| 3466 | |
| 3467 | # decide which flags to raise using value of ans |
| 3468 | if ans._isinfinity(): |
| 3469 | context._raise_error(Overflow, |
| 3470 | 'Infinite result from next_toward', |
| 3471 | ans._sign) |
| 3472 | context._raise_error(Rounded) |
| 3473 | context._raise_error(Inexact) |
| 3474 | elif ans.adjusted() < context.Emin: |
| 3475 | context._raise_error(Underflow) |
| 3476 | context._raise_error(Subnormal) |
| 3477 | context._raise_error(Rounded) |
| 3478 | context._raise_error(Inexact) |
| 3479 | # if precision == 1 then we don't raise Clamped for a |
| 3480 | # result 0E-Etiny. |
| 3481 | if not ans: |
| 3482 | context._raise_error(Clamped) |
| 3483 | |
| 3484 | return ans |
| 3485 | |
| 3486 | def number_class(self, context=None): |
| 3487 | """Returns an indication of the class of self. |
| 3488 | |
| 3489 | The class is one of the following strings: |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 3490 | sNaN |
| 3491 | NaN |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3492 | -Infinity |
| 3493 | -Normal |
| 3494 | -Subnormal |
| 3495 | -Zero |
| 3496 | +Zero |
| 3497 | +Subnormal |
| 3498 | +Normal |
| 3499 | +Infinity |
| 3500 | """ |
| 3501 | if self.is_snan(): |
| 3502 | return "sNaN" |
| 3503 | if self.is_qnan(): |
| 3504 | return "NaN" |
| 3505 | inf = self._isinfinity() |
| 3506 | if inf == 1: |
| 3507 | return "+Infinity" |
| 3508 | if inf == -1: |
| 3509 | return "-Infinity" |
| 3510 | if self.is_zero(): |
| 3511 | if self._sign: |
| 3512 | return "-Zero" |
| 3513 | else: |
| 3514 | return "+Zero" |
| 3515 | if context is None: |
| 3516 | context = getcontext() |
| 3517 | if self.is_subnormal(context=context): |
| 3518 | if self._sign: |
| 3519 | return "-Subnormal" |
| 3520 | else: |
| 3521 | return "+Subnormal" |
| 3522 | # just a normal, regular, boring number, :) |
| 3523 | if self._sign: |
| 3524 | return "-Normal" |
| 3525 | else: |
| 3526 | return "+Normal" |
| 3527 | |
| 3528 | def radix(self): |
| 3529 | """Just returns 10, as this is Decimal, :)""" |
| 3530 | return Decimal(10) |
| 3531 | |
| 3532 | def rotate(self, other, context=None): |
| 3533 | """Returns a rotated copy of self, value-of-other times.""" |
| 3534 | if context is None: |
| 3535 | context = getcontext() |
| 3536 | |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 3537 | other = _convert_other(other, raiseit=True) |
| 3538 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3539 | ans = self._check_nans(other, context) |
| 3540 | if ans: |
| 3541 | return ans |
| 3542 | |
| 3543 | if other._exp != 0: |
| 3544 | return context._raise_error(InvalidOperation) |
| 3545 | if not (-context.prec <= int(other) <= context.prec): |
| 3546 | return context._raise_error(InvalidOperation) |
| 3547 | |
| 3548 | if self._isinfinity(): |
| 3549 | return Decimal(self) |
| 3550 | |
| 3551 | # get values, pad if necessary |
| 3552 | torot = int(other) |
| 3553 | rotdig = self._int |
| 3554 | topad = context.prec - len(rotdig) |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 3555 | if topad > 0: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3556 | rotdig = '0'*topad + rotdig |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 3557 | elif topad < 0: |
| 3558 | rotdig = rotdig[-topad:] |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3559 | |
| 3560 | # let's rotate! |
| 3561 | rotated = rotdig[torot:] + rotdig[:torot] |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3562 | return _dec_from_triple(self._sign, |
| 3563 | rotated.lstrip('0') or '0', self._exp) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3564 | |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 3565 | def scaleb(self, other, context=None): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3566 | """Returns self operand after adding the second value to its exp.""" |
| 3567 | if context is None: |
| 3568 | context = getcontext() |
| 3569 | |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 3570 | other = _convert_other(other, raiseit=True) |
| 3571 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3572 | ans = self._check_nans(other, context) |
| 3573 | if ans: |
| 3574 | return ans |
| 3575 | |
| 3576 | if other._exp != 0: |
| 3577 | return context._raise_error(InvalidOperation) |
| 3578 | liminf = -2 * (context.Emax + context.prec) |
| 3579 | limsup = 2 * (context.Emax + context.prec) |
| 3580 | if not (liminf <= int(other) <= limsup): |
| 3581 | return context._raise_error(InvalidOperation) |
| 3582 | |
| 3583 | if self._isinfinity(): |
| 3584 | return Decimal(self) |
| 3585 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3586 | d = _dec_from_triple(self._sign, self._int, self._exp + int(other)) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3587 | d = d._fix(context) |
| 3588 | return d |
| 3589 | |
| 3590 | def shift(self, other, context=None): |
| 3591 | """Returns a shifted copy of self, value-of-other times.""" |
| 3592 | if context is None: |
| 3593 | context = getcontext() |
| 3594 | |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 3595 | other = _convert_other(other, raiseit=True) |
| 3596 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3597 | ans = self._check_nans(other, context) |
| 3598 | if ans: |
| 3599 | return ans |
| 3600 | |
| 3601 | if other._exp != 0: |
| 3602 | return context._raise_error(InvalidOperation) |
| 3603 | if not (-context.prec <= int(other) <= context.prec): |
| 3604 | return context._raise_error(InvalidOperation) |
| 3605 | |
| 3606 | if self._isinfinity(): |
| 3607 | return Decimal(self) |
| 3608 | |
| 3609 | # get values, pad if necessary |
| 3610 | torot = int(other) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3611 | rotdig = self._int |
| 3612 | topad = context.prec - len(rotdig) |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 3613 | if topad > 0: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3614 | rotdig = '0'*topad + rotdig |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 3615 | elif topad < 0: |
| 3616 | rotdig = rotdig[-topad:] |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3617 | |
| 3618 | # let's shift! |
| 3619 | if torot < 0: |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 3620 | shifted = rotdig[:torot] |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3621 | else: |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 3622 | shifted = rotdig + '0'*torot |
| 3623 | shifted = shifted[-context.prec:] |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3624 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3625 | return _dec_from_triple(self._sign, |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 3626 | shifted.lstrip('0') or '0', self._exp) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3627 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3628 | # Support for pickling, copy, and deepcopy |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3629 | def __reduce__(self): |
| 3630 | return (self.__class__, (str(self),)) |
| 3631 | |
| 3632 | def __copy__(self): |
Benjamin Peterson | d69fe2a | 2010-02-03 02:59:43 +0000 | [diff] [blame] | 3633 | if type(self) is Decimal: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3634 | return self # I'm immutable; therefore I am my own clone |
| 3635 | return self.__class__(str(self)) |
| 3636 | |
| 3637 | def __deepcopy__(self, memo): |
Benjamin Peterson | d69fe2a | 2010-02-03 02:59:43 +0000 | [diff] [blame] | 3638 | if type(self) is Decimal: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3639 | return self # My components are also immutable |
| 3640 | return self.__class__(str(self)) |
| 3641 | |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 3642 | # PEP 3101 support. the _localeconv keyword argument should be |
| 3643 | # considered private: it's provided for ease of testing only. |
| 3644 | def __format__(self, specifier, context=None, _localeconv=None): |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3645 | """Format a Decimal instance according to the given specifier. |
| 3646 | |
| 3647 | The specifier should be a standard format specifier, with the |
| 3648 | form described in PEP 3101. Formatting types 'e', 'E', 'f', |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 3649 | 'F', 'g', 'G', 'n' and '%' are supported. If the formatting |
| 3650 | type is omitted it defaults to 'g' or 'G', depending on the |
| 3651 | value of context.capitals. |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3652 | """ |
| 3653 | |
| 3654 | # Note: PEP 3101 says that if the type is not present then |
| 3655 | # there should be at least one digit after the decimal point. |
| 3656 | # We take the liberty of ignoring this requirement for |
| 3657 | # Decimal---it's presumably there to make sure that |
| 3658 | # format(float, '') behaves similarly to str(float). |
| 3659 | if context is None: |
| 3660 | context = getcontext() |
| 3661 | |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 3662 | spec = _parse_format_specifier(specifier, _localeconv=_localeconv) |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3663 | |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 3664 | # special values don't care about the type or precision |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3665 | if self._is_special: |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 3666 | sign = _format_sign(self._sign, spec) |
| 3667 | body = str(self.copy_abs()) |
| 3668 | return _format_align(sign, body, spec) |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3669 | |
| 3670 | # a type of None defaults to 'g' or 'G', depending on context |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3671 | if spec['type'] is None: |
| 3672 | spec['type'] = ['g', 'G'][context.capitals] |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 3673 | |
| 3674 | # if type is '%', adjust exponent of self accordingly |
| 3675 | if spec['type'] == '%': |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3676 | self = _dec_from_triple(self._sign, self._int, self._exp+2) |
| 3677 | |
| 3678 | # round if necessary, taking rounding mode from the context |
| 3679 | rounding = context.rounding |
| 3680 | precision = spec['precision'] |
| 3681 | if precision is not None: |
| 3682 | if spec['type'] in 'eE': |
| 3683 | self = self._round(precision+1, rounding) |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3684 | elif spec['type'] in 'fF%': |
| 3685 | self = self._rescale(-precision, rounding) |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 3686 | elif spec['type'] in 'gG' and len(self._int) > precision: |
| 3687 | self = self._round(precision, rounding) |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3688 | # special case: zeros with a positive exponent can't be |
| 3689 | # represented in fixed point; rescale them to 0e0. |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 3690 | if not self and self._exp > 0 and spec['type'] in 'fF%': |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3691 | self = self._rescale(0, rounding) |
| 3692 | |
| 3693 | # figure out placement of the decimal point |
| 3694 | leftdigits = self._exp + len(self._int) |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 3695 | if spec['type'] in 'eE': |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3696 | if not self and precision is not None: |
| 3697 | dotplace = 1 - precision |
| 3698 | else: |
| 3699 | dotplace = 1 |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 3700 | elif spec['type'] in 'fF%': |
| 3701 | dotplace = leftdigits |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3702 | elif spec['type'] in 'gG': |
| 3703 | if self._exp <= 0 and leftdigits > -6: |
| 3704 | dotplace = leftdigits |
| 3705 | else: |
| 3706 | dotplace = 1 |
| 3707 | |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 3708 | # find digits before and after decimal point, and get exponent |
| 3709 | if dotplace < 0: |
| 3710 | intpart = '0' |
| 3711 | fracpart = '0'*(-dotplace) + self._int |
| 3712 | elif dotplace > len(self._int): |
| 3713 | intpart = self._int + '0'*(dotplace-len(self._int)) |
| 3714 | fracpart = '' |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3715 | else: |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 3716 | intpart = self._int[:dotplace] or '0' |
| 3717 | fracpart = self._int[dotplace:] |
| 3718 | exp = leftdigits-dotplace |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3719 | |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 3720 | # done with the decimal-specific stuff; hand over the rest |
| 3721 | # of the formatting to the _format_number function |
| 3722 | return _format_number(self._sign, intpart, fracpart, exp, spec) |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3723 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3724 | def _dec_from_triple(sign, coefficient, exponent, special=False): |
| 3725 | """Create a decimal instance directly, without any validation, |
| 3726 | normalization (e.g. removal of leading zeros) or argument |
| 3727 | conversion. |
| 3728 | |
| 3729 | This function is for *internal use only*. |
| 3730 | """ |
| 3731 | |
| 3732 | self = object.__new__(Decimal) |
| 3733 | self._sign = sign |
| 3734 | self._int = coefficient |
| 3735 | self._exp = exponent |
| 3736 | self._is_special = special |
| 3737 | |
| 3738 | return self |
| 3739 | |
Raymond Hettinger | 82417ca | 2009-02-03 03:54:28 +0000 | [diff] [blame] | 3740 | # Register Decimal as a kind of Number (an abstract base class). |
| 3741 | # However, do not register it as Real (because Decimals are not |
| 3742 | # interoperable with floats). |
| 3743 | _numbers.Number.register(Decimal) |
| 3744 | |
| 3745 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3746 | ##### Context class ####################################################### |
Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 3747 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3748 | |
| 3749 | # get rounding method function: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3750 | rounding_functions = [name for name in Decimal.__dict__.keys() |
| 3751 | if name.startswith('_round_')] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3752 | for name in rounding_functions: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3753 | # 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] | 3754 | globalname = name[1:].upper() |
| 3755 | val = globals()[globalname] |
| 3756 | Decimal._pick_rounding_function[val] = name |
| 3757 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3758 | del name, val, globalname, rounding_functions |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3759 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 3760 | class _ContextManager(object): |
| 3761 | """Context manager class to support localcontext(). |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 3762 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 3763 | Sets a copy of the supplied context in __enter__() and restores |
| 3764 | the previous decimal context in __exit__() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 3765 | """ |
| 3766 | def __init__(self, new_context): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 3767 | self.new_context = new_context.copy() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 3768 | def __enter__(self): |
| 3769 | self.saved_context = getcontext() |
| 3770 | setcontext(self.new_context) |
| 3771 | return self.new_context |
| 3772 | def __exit__(self, t, v, tb): |
| 3773 | setcontext(self.saved_context) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 3774 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3775 | class Context(object): |
| 3776 | """Contains the context for a Decimal instance. |
| 3777 | |
| 3778 | Contains: |
| 3779 | prec - precision (for use in rounding, division, square roots..) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3780 | rounding - rounding type (how you round) |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3781 | traps - If traps[exception] = 1, then the exception is |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3782 | raised when it is caused. Otherwise, a value is |
| 3783 | substituted in. |
Raymond Hettinger | 86173da | 2008-02-01 20:38:12 +0000 | [diff] [blame] | 3784 | flags - When an exception is caused, flags[exception] is set. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3785 | (Whether or not the trap_enabler is set) |
| 3786 | Should be reset by user of Decimal instance. |
Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 3787 | Emin - Minimum exponent |
| 3788 | Emax - Maximum exponent |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3789 | capitals - If 1, 1*10^1 is printed as 1E+1. |
| 3790 | If 0, printed as 1e1 |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 3791 | _clamp - If 1, change exponents if too high (Default 0) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3792 | """ |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3793 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3794 | def __init__(self, prec=None, rounding=None, |
Raymond Hettinger | abf8a56 | 2004-10-12 09:12:16 +0000 | [diff] [blame] | 3795 | traps=None, flags=None, |
Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 3796 | Emin=None, Emax=None, |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 3797 | capitals=None, _clamp=0, |
Raymond Hettinger | abf8a56 | 2004-10-12 09:12:16 +0000 | [diff] [blame] | 3798 | _ignored_flags=None): |
| 3799 | if flags is None: |
| 3800 | flags = [] |
| 3801 | if _ignored_flags is None: |
| 3802 | _ignored_flags = [] |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3803 | if not isinstance(flags, dict): |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 3804 | flags = dict([(s, int(s in flags)) for s in _signals]) |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3805 | if traps is not None and not isinstance(traps, dict): |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 3806 | traps = dict([(s, int(s in traps)) for s in _signals]) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3807 | for name, val in locals().items(): |
| 3808 | if val is None: |
Raymond Hettinger | eb26084 | 2005-06-07 18:52:34 +0000 | [diff] [blame] | 3809 | setattr(self, name, _copy.copy(getattr(DefaultContext, name))) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3810 | else: |
| 3811 | setattr(self, name, val) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3812 | del self.self |
| 3813 | |
Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 3814 | def __repr__(self): |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3815 | """Show the current context.""" |
Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 3816 | s = [] |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3817 | s.append('Context(prec=%(prec)d, rounding=%(rounding)s, ' |
| 3818 | 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d' |
| 3819 | % vars(self)) |
| 3820 | names = [f.__name__ for f, v in self.flags.items() if v] |
| 3821 | s.append('flags=[' + ', '.join(names) + ']') |
| 3822 | names = [t.__name__ for t, v in self.traps.items() if v] |
| 3823 | s.append('traps=[' + ', '.join(names) + ']') |
Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 3824 | return ', '.join(s) + ')' |
| 3825 | |
Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 3826 | def clear_flags(self): |
| 3827 | """Reset all flags to zero""" |
| 3828 | for flag in self.flags: |
Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 3829 | self.flags[flag] = 0 |
Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 3830 | |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 3831 | def _shallow_copy(self): |
| 3832 | """Returns a shallow copy from self.""" |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 3833 | nc = Context(self.prec, self.rounding, self.traps, |
| 3834 | self.flags, self.Emin, self.Emax, |
| 3835 | self.capitals, self._clamp, self._ignored_flags) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3836 | return nc |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 3837 | |
| 3838 | def copy(self): |
| 3839 | """Returns a deep copy from self.""" |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3840 | nc = Context(self.prec, self.rounding, self.traps.copy(), |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 3841 | self.flags.copy(), self.Emin, self.Emax, |
| 3842 | self.capitals, self._clamp, self._ignored_flags) |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 3843 | return nc |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3844 | __copy__ = copy |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3845 | |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 3846 | def _raise_error(self, condition, explanation = None, *args): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3847 | """Handles an error |
| 3848 | |
| 3849 | If the flag is in _ignored_flags, returns the default response. |
Raymond Hettinger | 86173da | 2008-02-01 20:38:12 +0000 | [diff] [blame] | 3850 | Otherwise, it sets the flag, then, if the corresponding |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3851 | trap_enabler is set, it reaises the exception. Otherwise, it returns |
Raymond Hettinger | 86173da | 2008-02-01 20:38:12 +0000 | [diff] [blame] | 3852 | the default value after setting the flag. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3853 | """ |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 3854 | error = _condition_map.get(condition, condition) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3855 | if error in self._ignored_flags: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3856 | # Don't touch the flag |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3857 | return error().handle(self, *args) |
| 3858 | |
Raymond Hettinger | 86173da | 2008-02-01 20:38:12 +0000 | [diff] [blame] | 3859 | self.flags[error] = 1 |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3860 | if not self.traps[error]: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3861 | # The errors define how to handle themselves. |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 3862 | return condition().handle(self, *args) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3863 | |
| 3864 | # Errors should only be risked on copies of the context |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3865 | # self._ignored_flags = [] |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 3866 | raise error(explanation) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3867 | |
| 3868 | def _ignore_all_flags(self): |
| 3869 | """Ignore all flags, if they are raised""" |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 3870 | return self._ignore_flags(*_signals) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3871 | |
| 3872 | def _ignore_flags(self, *flags): |
| 3873 | """Ignore the flags, if they are raised""" |
| 3874 | # Do not mutate-- This way, copies of a context leave the original |
| 3875 | # alone. |
| 3876 | self._ignored_flags = (self._ignored_flags + list(flags)) |
| 3877 | return list(flags) |
| 3878 | |
| 3879 | def _regard_flags(self, *flags): |
| 3880 | """Stop ignoring the flags, if they are raised""" |
| 3881 | if flags and isinstance(flags[0], (tuple,list)): |
| 3882 | flags = flags[0] |
| 3883 | for flag in flags: |
| 3884 | self._ignored_flags.remove(flag) |
| 3885 | |
Nick Coghlan | d1abd25 | 2008-07-15 15:46:38 +0000 | [diff] [blame] | 3886 | # We inherit object.__hash__, so we must deny this explicitly |
| 3887 | __hash__ = None |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 3888 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3889 | def Etiny(self): |
| 3890 | """Returns Etiny (= Emin - prec + 1)""" |
| 3891 | return int(self.Emin - self.prec + 1) |
| 3892 | |
| 3893 | def Etop(self): |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 3894 | """Returns maximum exponent (= Emax - prec + 1)""" |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3895 | return int(self.Emax - self.prec + 1) |
| 3896 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3897 | def _set_rounding(self, type): |
| 3898 | """Sets the rounding type. |
| 3899 | |
| 3900 | Sets the rounding type, and returns the current (previous) |
| 3901 | rounding type. Often used like: |
| 3902 | |
| 3903 | context = context.copy() |
| 3904 | # so you don't change the calling context |
| 3905 | # if an error occurs in the middle. |
| 3906 | rounding = context._set_rounding(ROUND_UP) |
| 3907 | val = self.__sub__(other, context=context) |
| 3908 | context._set_rounding(rounding) |
| 3909 | |
| 3910 | This will make it round up for that operation. |
| 3911 | """ |
| 3912 | rounding = self.rounding |
| 3913 | self.rounding= type |
| 3914 | return rounding |
| 3915 | |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 3916 | def create_decimal(self, num='0'): |
Christian Heimes | a62da1d | 2008-01-12 19:39:10 +0000 | [diff] [blame] | 3917 | """Creates a new Decimal instance but using self as context. |
| 3918 | |
| 3919 | This method implements the to-number operation of the |
| 3920 | IBM Decimal specification.""" |
| 3921 | |
| 3922 | if isinstance(num, str) and num != num.strip(): |
| 3923 | return self._raise_error(ConversionSyntax, |
| 3924 | "no trailing or leading whitespace is " |
| 3925 | "permitted.") |
| 3926 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3927 | d = Decimal(num, context=self) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3928 | if d._isnan() and len(d._int) > self.prec - self._clamp: |
| 3929 | return self._raise_error(ConversionSyntax, |
| 3930 | "diagnostic info too long in NaN") |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 3931 | return d._fix(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3932 | |
Raymond Hettinger | 771ed76 | 2009-01-03 19:20:32 +0000 | [diff] [blame] | 3933 | def create_decimal_from_float(self, f): |
| 3934 | """Creates a new Decimal instance from a float but rounding using self |
| 3935 | as the context. |
| 3936 | |
| 3937 | >>> context = Context(prec=5, rounding=ROUND_DOWN) |
| 3938 | >>> context.create_decimal_from_float(3.1415926535897932) |
| 3939 | Decimal('3.1415') |
| 3940 | >>> context = Context(prec=5, traps=[Inexact]) |
| 3941 | >>> context.create_decimal_from_float(3.1415926535897932) |
| 3942 | Traceback (most recent call last): |
| 3943 | ... |
| 3944 | decimal.Inexact: None |
| 3945 | |
| 3946 | """ |
| 3947 | d = Decimal.from_float(f) # An exact conversion |
| 3948 | return d._fix(self) # Apply the context rounding |
| 3949 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3950 | # Methods |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3951 | def abs(self, a): |
| 3952 | """Returns the absolute value of the operand. |
| 3953 | |
| 3954 | 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] | 3955 | operation on the operand. Otherwise, the result is the same as using |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3956 | the plus operation on the operand. |
| 3957 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3958 | >>> ExtendedContext.abs(Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3959 | Decimal('2.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3960 | >>> ExtendedContext.abs(Decimal('-100')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3961 | Decimal('100') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3962 | >>> ExtendedContext.abs(Decimal('101.5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3963 | Decimal('101.5') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3964 | >>> ExtendedContext.abs(Decimal('-101.5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3965 | Decimal('101.5') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 3966 | >>> ExtendedContext.abs(-1) |
| 3967 | Decimal('1') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3968 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 3969 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3970 | return a.__abs__(context=self) |
| 3971 | |
| 3972 | def add(self, a, b): |
| 3973 | """Return the sum of the two operands. |
| 3974 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3975 | >>> ExtendedContext.add(Decimal('12'), Decimal('7.00')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3976 | Decimal('19.00') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3977 | >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 3978 | Decimal('1.02E+4') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 3979 | >>> ExtendedContext.add(1, Decimal(2)) |
| 3980 | Decimal('3') |
| 3981 | >>> ExtendedContext.add(Decimal(8), 5) |
| 3982 | Decimal('13') |
| 3983 | >>> ExtendedContext.add(5, 5) |
| 3984 | Decimal('10') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3985 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 3986 | a = _convert_other(a, raiseit=True) |
| 3987 | r = a.__add__(b, context=self) |
| 3988 | if r is NotImplemented: |
| 3989 | raise TypeError("Unable to convert %s to Decimal" % b) |
| 3990 | else: |
| 3991 | return r |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3992 | |
| 3993 | def _apply(self, a): |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 3994 | return str(a._fix(self)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3995 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3996 | def canonical(self, a): |
| 3997 | """Returns the same Decimal object. |
| 3998 | |
| 3999 | As we do not have different encodings for the same number, the |
| 4000 | received object already is in its canonical form. |
| 4001 | |
| 4002 | >>> ExtendedContext.canonical(Decimal('2.50')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4003 | Decimal('2.50') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4004 | """ |
| 4005 | return a.canonical(context=self) |
| 4006 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4007 | def compare(self, a, b): |
| 4008 | """Compares values numerically. |
| 4009 | |
| 4010 | If the signs of the operands differ, a value representing each operand |
| 4011 | ('-1' if the operand is less than zero, '0' if the operand is zero or |
| 4012 | negative zero, or '1' if the operand is greater than zero) is used in |
| 4013 | place of that operand for the comparison instead of the actual |
| 4014 | operand. |
| 4015 | |
| 4016 | The comparison is then effected by subtracting the second operand from |
| 4017 | the first and then returning a value according to the result of the |
| 4018 | subtraction: '-1' if the result is less than zero, '0' if the result is |
| 4019 | zero or negative zero, or '1' if the result is greater than zero. |
| 4020 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4021 | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4022 | Decimal('-1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4023 | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4024 | Decimal('0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4025 | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4026 | Decimal('0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4027 | >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4028 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4029 | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4030 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4031 | >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4032 | Decimal('-1') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4033 | >>> ExtendedContext.compare(1, 2) |
| 4034 | Decimal('-1') |
| 4035 | >>> ExtendedContext.compare(Decimal(1), 2) |
| 4036 | Decimal('-1') |
| 4037 | >>> ExtendedContext.compare(1, Decimal(2)) |
| 4038 | Decimal('-1') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4039 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4040 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4041 | return a.compare(b, context=self) |
| 4042 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4043 | def compare_signal(self, a, b): |
| 4044 | """Compares the values of the two operands numerically. |
| 4045 | |
| 4046 | It's pretty much like compare(), but all NaNs signal, with signaling |
| 4047 | NaNs taking precedence over quiet NaNs. |
| 4048 | |
| 4049 | >>> c = ExtendedContext |
| 4050 | >>> c.compare_signal(Decimal('2.1'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4051 | Decimal('-1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4052 | >>> c.compare_signal(Decimal('2.1'), Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4053 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4054 | >>> c.flags[InvalidOperation] = 0 |
| 4055 | >>> print(c.flags[InvalidOperation]) |
| 4056 | 0 |
| 4057 | >>> c.compare_signal(Decimal('NaN'), Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4058 | Decimal('NaN') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4059 | >>> print(c.flags[InvalidOperation]) |
| 4060 | 1 |
| 4061 | >>> c.flags[InvalidOperation] = 0 |
| 4062 | >>> print(c.flags[InvalidOperation]) |
| 4063 | 0 |
| 4064 | >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4065 | Decimal('NaN') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4066 | >>> print(c.flags[InvalidOperation]) |
| 4067 | 1 |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4068 | >>> c.compare_signal(-1, 2) |
| 4069 | Decimal('-1') |
| 4070 | >>> c.compare_signal(Decimal(-1), 2) |
| 4071 | Decimal('-1') |
| 4072 | >>> c.compare_signal(-1, Decimal(2)) |
| 4073 | Decimal('-1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4074 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4075 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4076 | return a.compare_signal(b, context=self) |
| 4077 | |
| 4078 | def compare_total(self, a, b): |
| 4079 | """Compares two operands using their abstract representation. |
| 4080 | |
| 4081 | This is not like the standard compare, which use their numerical |
| 4082 | value. Note that a total ordering is defined for all possible abstract |
| 4083 | representations. |
| 4084 | |
| 4085 | >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4086 | Decimal('-1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4087 | >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4088 | Decimal('-1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4089 | >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4090 | Decimal('-1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4091 | >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4092 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4093 | >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4094 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4095 | >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4096 | Decimal('-1') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4097 | >>> ExtendedContext.compare_total(1, 2) |
| 4098 | Decimal('-1') |
| 4099 | >>> ExtendedContext.compare_total(Decimal(1), 2) |
| 4100 | Decimal('-1') |
| 4101 | >>> ExtendedContext.compare_total(1, Decimal(2)) |
| 4102 | Decimal('-1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4103 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4104 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4105 | return a.compare_total(b) |
| 4106 | |
| 4107 | def compare_total_mag(self, a, b): |
| 4108 | """Compares two operands using their abstract representation ignoring sign. |
| 4109 | |
| 4110 | Like compare_total, but with operand's sign ignored and assumed to be 0. |
| 4111 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4112 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4113 | return a.compare_total_mag(b) |
| 4114 | |
| 4115 | def copy_abs(self, a): |
| 4116 | """Returns a copy of the operand with the sign set to 0. |
| 4117 | |
| 4118 | >>> ExtendedContext.copy_abs(Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4119 | Decimal('2.1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4120 | >>> ExtendedContext.copy_abs(Decimal('-100')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4121 | Decimal('100') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4122 | >>> ExtendedContext.copy_abs(-1) |
| 4123 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4124 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4125 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4126 | return a.copy_abs() |
| 4127 | |
| 4128 | def copy_decimal(self, a): |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4129 | """Returns a copy of the decimal object. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4130 | |
| 4131 | >>> ExtendedContext.copy_decimal(Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4132 | Decimal('2.1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4133 | >>> ExtendedContext.copy_decimal(Decimal('-1.00')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4134 | Decimal('-1.00') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4135 | >>> ExtendedContext.copy_decimal(1) |
| 4136 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4137 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4138 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4139 | return Decimal(a) |
| 4140 | |
| 4141 | def copy_negate(self, a): |
| 4142 | """Returns a copy of the operand with the sign inverted. |
| 4143 | |
| 4144 | >>> ExtendedContext.copy_negate(Decimal('101.5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4145 | Decimal('-101.5') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4146 | >>> ExtendedContext.copy_negate(Decimal('-101.5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4147 | Decimal('101.5') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4148 | >>> ExtendedContext.copy_negate(1) |
| 4149 | Decimal('-1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4150 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4151 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4152 | return a.copy_negate() |
| 4153 | |
| 4154 | def copy_sign(self, a, b): |
| 4155 | """Copies the second operand's sign to the first one. |
| 4156 | |
| 4157 | In detail, it returns a copy of the first operand with the sign |
| 4158 | equal to the sign of the second operand. |
| 4159 | |
| 4160 | >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4161 | Decimal('1.50') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4162 | >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4163 | Decimal('1.50') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4164 | >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4165 | Decimal('-1.50') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4166 | >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4167 | Decimal('-1.50') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4168 | >>> ExtendedContext.copy_sign(1, -2) |
| 4169 | Decimal('-1') |
| 4170 | >>> ExtendedContext.copy_sign(Decimal(1), -2) |
| 4171 | Decimal('-1') |
| 4172 | >>> ExtendedContext.copy_sign(1, Decimal(-2)) |
| 4173 | Decimal('-1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4174 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4175 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4176 | return a.copy_sign(b) |
| 4177 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4178 | def divide(self, a, b): |
| 4179 | """Decimal division in a specified context. |
| 4180 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4181 | >>> ExtendedContext.divide(Decimal('1'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4182 | Decimal('0.333333333') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4183 | >>> ExtendedContext.divide(Decimal('2'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4184 | Decimal('0.666666667') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4185 | >>> ExtendedContext.divide(Decimal('5'), Decimal('2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4186 | Decimal('2.5') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4187 | >>> ExtendedContext.divide(Decimal('1'), Decimal('10')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4188 | Decimal('0.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4189 | >>> ExtendedContext.divide(Decimal('12'), Decimal('12')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4190 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4191 | >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4192 | Decimal('4.00') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4193 | >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4194 | Decimal('1.20') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4195 | >>> ExtendedContext.divide(Decimal('1000'), Decimal('100')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4196 | Decimal('10') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4197 | >>> ExtendedContext.divide(Decimal('1000'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4198 | Decimal('1000') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4199 | >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4200 | Decimal('1.20E+6') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4201 | >>> ExtendedContext.divide(5, 5) |
| 4202 | Decimal('1') |
| 4203 | >>> ExtendedContext.divide(Decimal(5), 5) |
| 4204 | Decimal('1') |
| 4205 | >>> ExtendedContext.divide(5, Decimal(5)) |
| 4206 | Decimal('1') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4207 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4208 | a = _convert_other(a, raiseit=True) |
| 4209 | r = a.__truediv__(b, context=self) |
| 4210 | if r is NotImplemented: |
| 4211 | raise TypeError("Unable to convert %s to Decimal" % b) |
| 4212 | else: |
| 4213 | return r |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4214 | |
| 4215 | def divide_int(self, a, b): |
| 4216 | """Divides two numbers and returns the integer part of the result. |
| 4217 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4218 | >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4219 | Decimal('0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4220 | >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4221 | Decimal('3') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4222 | >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4223 | Decimal('3') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4224 | >>> ExtendedContext.divide_int(10, 3) |
| 4225 | Decimal('3') |
| 4226 | >>> ExtendedContext.divide_int(Decimal(10), 3) |
| 4227 | Decimal('3') |
| 4228 | >>> ExtendedContext.divide_int(10, Decimal(3)) |
| 4229 | Decimal('3') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4230 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4231 | a = _convert_other(a, raiseit=True) |
| 4232 | r = a.__floordiv__(b, context=self) |
| 4233 | if r is NotImplemented: |
| 4234 | raise TypeError("Unable to convert %s to Decimal" % b) |
| 4235 | else: |
| 4236 | return r |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4237 | |
| 4238 | def divmod(self, a, b): |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4239 | """Return (a // b, a % b). |
Mark Dickinson | c53796e | 2010-01-06 16:22:15 +0000 | [diff] [blame] | 4240 | |
| 4241 | >>> ExtendedContext.divmod(Decimal(8), Decimal(3)) |
| 4242 | (Decimal('2'), Decimal('2')) |
| 4243 | >>> ExtendedContext.divmod(Decimal(8), Decimal(4)) |
| 4244 | (Decimal('2'), Decimal('0')) |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4245 | >>> ExtendedContext.divmod(8, 4) |
| 4246 | (Decimal('2'), Decimal('0')) |
| 4247 | >>> ExtendedContext.divmod(Decimal(8), 4) |
| 4248 | (Decimal('2'), Decimal('0')) |
| 4249 | >>> ExtendedContext.divmod(8, Decimal(4)) |
| 4250 | (Decimal('2'), Decimal('0')) |
Mark Dickinson | c53796e | 2010-01-06 16:22:15 +0000 | [diff] [blame] | 4251 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4252 | a = _convert_other(a, raiseit=True) |
| 4253 | r = a.__divmod__(b, context=self) |
| 4254 | if r is NotImplemented: |
| 4255 | raise TypeError("Unable to convert %s to Decimal" % b) |
| 4256 | else: |
| 4257 | return r |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4258 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4259 | def exp(self, a): |
| 4260 | """Returns e ** a. |
| 4261 | |
| 4262 | >>> c = ExtendedContext.copy() |
| 4263 | >>> c.Emin = -999 |
| 4264 | >>> c.Emax = 999 |
| 4265 | >>> c.exp(Decimal('-Infinity')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4266 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4267 | >>> c.exp(Decimal('-1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4268 | Decimal('0.367879441') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4269 | >>> c.exp(Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4270 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4271 | >>> c.exp(Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4272 | Decimal('2.71828183') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4273 | >>> c.exp(Decimal('0.693147181')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4274 | Decimal('2.00000000') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4275 | >>> c.exp(Decimal('+Infinity')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4276 | Decimal('Infinity') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4277 | >>> c.exp(10) |
| 4278 | Decimal('22026.4658') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4279 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4280 | a =_convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4281 | return a.exp(context=self) |
| 4282 | |
| 4283 | def fma(self, a, b, c): |
| 4284 | """Returns a multiplied by b, plus c. |
| 4285 | |
| 4286 | The first two operands are multiplied together, using multiply, |
| 4287 | the third operand is then added to the result of that |
| 4288 | multiplication, using add, all with only one final rounding. |
| 4289 | |
| 4290 | >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4291 | Decimal('22') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4292 | >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4293 | Decimal('-8') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4294 | >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4295 | Decimal('1.38435736E+12') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4296 | >>> ExtendedContext.fma(1, 3, 4) |
| 4297 | Decimal('7') |
| 4298 | >>> ExtendedContext.fma(1, Decimal(3), 4) |
| 4299 | Decimal('7') |
| 4300 | >>> ExtendedContext.fma(1, 3, Decimal(4)) |
| 4301 | Decimal('7') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4302 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4303 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4304 | return a.fma(b, c, context=self) |
| 4305 | |
| 4306 | def is_canonical(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4307 | """Return True if the operand is canonical; otherwise return False. |
| 4308 | |
| 4309 | Currently, the encoding of a Decimal instance is always |
| 4310 | canonical, so this method returns True for any Decimal. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4311 | |
| 4312 | >>> ExtendedContext.is_canonical(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4313 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4314 | """ |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4315 | return a.is_canonical() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4316 | |
| 4317 | def is_finite(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4318 | """Return True if the operand is finite; otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4319 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4320 | A Decimal instance is considered finite if it is neither |
| 4321 | infinite nor a NaN. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4322 | |
| 4323 | >>> ExtendedContext.is_finite(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4324 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4325 | >>> ExtendedContext.is_finite(Decimal('-0.3')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4326 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4327 | >>> ExtendedContext.is_finite(Decimal('0')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4328 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4329 | >>> ExtendedContext.is_finite(Decimal('Inf')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4330 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4331 | >>> ExtendedContext.is_finite(Decimal('NaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4332 | False |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4333 | >>> ExtendedContext.is_finite(1) |
| 4334 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4335 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4336 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4337 | return a.is_finite() |
| 4338 | |
| 4339 | def is_infinite(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4340 | """Return True if the operand is infinite; otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4341 | |
| 4342 | >>> ExtendedContext.is_infinite(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4343 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4344 | >>> ExtendedContext.is_infinite(Decimal('-Inf')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4345 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4346 | >>> ExtendedContext.is_infinite(Decimal('NaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4347 | False |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4348 | >>> ExtendedContext.is_infinite(1) |
| 4349 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4350 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4351 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4352 | return a.is_infinite() |
| 4353 | |
| 4354 | def is_nan(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4355 | """Return True if the operand is a qNaN or sNaN; |
| 4356 | otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4357 | |
| 4358 | >>> ExtendedContext.is_nan(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4359 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4360 | >>> ExtendedContext.is_nan(Decimal('NaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4361 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4362 | >>> ExtendedContext.is_nan(Decimal('-sNaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4363 | True |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4364 | >>> ExtendedContext.is_nan(1) |
| 4365 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4366 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4367 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4368 | return a.is_nan() |
| 4369 | |
| 4370 | def is_normal(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4371 | """Return True if the operand is a normal number; |
| 4372 | otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4373 | |
| 4374 | >>> c = ExtendedContext.copy() |
| 4375 | >>> c.Emin = -999 |
| 4376 | >>> c.Emax = 999 |
| 4377 | >>> c.is_normal(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4378 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4379 | >>> c.is_normal(Decimal('0.1E-999')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4380 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4381 | >>> c.is_normal(Decimal('0.00')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4382 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4383 | >>> c.is_normal(Decimal('-Inf')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4384 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4385 | >>> c.is_normal(Decimal('NaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4386 | False |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4387 | >>> c.is_normal(1) |
| 4388 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4389 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4390 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4391 | return a.is_normal(context=self) |
| 4392 | |
| 4393 | def is_qnan(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4394 | """Return True if the operand is a quiet NaN; otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4395 | |
| 4396 | >>> ExtendedContext.is_qnan(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4397 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4398 | >>> ExtendedContext.is_qnan(Decimal('NaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4399 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4400 | >>> ExtendedContext.is_qnan(Decimal('sNaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4401 | False |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4402 | >>> ExtendedContext.is_qnan(1) |
| 4403 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4404 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4405 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4406 | return a.is_qnan() |
| 4407 | |
| 4408 | def is_signed(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4409 | """Return True if the operand is negative; otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4410 | |
| 4411 | >>> ExtendedContext.is_signed(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4412 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4413 | >>> ExtendedContext.is_signed(Decimal('-12')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4414 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4415 | >>> ExtendedContext.is_signed(Decimal('-0')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4416 | True |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4417 | >>> ExtendedContext.is_signed(8) |
| 4418 | False |
| 4419 | >>> ExtendedContext.is_signed(-8) |
| 4420 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4421 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4422 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4423 | return a.is_signed() |
| 4424 | |
| 4425 | def is_snan(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4426 | """Return True if the operand is a signaling NaN; |
| 4427 | otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4428 | |
| 4429 | >>> ExtendedContext.is_snan(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4430 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4431 | >>> ExtendedContext.is_snan(Decimal('NaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4432 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4433 | >>> ExtendedContext.is_snan(Decimal('sNaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4434 | True |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4435 | >>> ExtendedContext.is_snan(1) |
| 4436 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4437 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4438 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4439 | return a.is_snan() |
| 4440 | |
| 4441 | def is_subnormal(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4442 | """Return True if the operand is subnormal; otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4443 | |
| 4444 | >>> c = ExtendedContext.copy() |
| 4445 | >>> c.Emin = -999 |
| 4446 | >>> c.Emax = 999 |
| 4447 | >>> c.is_subnormal(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4448 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4449 | >>> c.is_subnormal(Decimal('0.1E-999')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4450 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4451 | >>> c.is_subnormal(Decimal('0.00')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4452 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4453 | >>> c.is_subnormal(Decimal('-Inf')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4454 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4455 | >>> c.is_subnormal(Decimal('NaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4456 | False |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4457 | >>> c.is_subnormal(1) |
| 4458 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4459 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4460 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4461 | return a.is_subnormal(context=self) |
| 4462 | |
| 4463 | def is_zero(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4464 | """Return True if the operand is a zero; otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4465 | |
| 4466 | >>> ExtendedContext.is_zero(Decimal('0')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4467 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4468 | >>> ExtendedContext.is_zero(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4469 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4470 | >>> ExtendedContext.is_zero(Decimal('-0E+2')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4471 | True |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4472 | >>> ExtendedContext.is_zero(1) |
| 4473 | False |
| 4474 | >>> ExtendedContext.is_zero(0) |
| 4475 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4476 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4477 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4478 | return a.is_zero() |
| 4479 | |
| 4480 | def ln(self, a): |
| 4481 | """Returns the natural (base e) logarithm of the operand. |
| 4482 | |
| 4483 | >>> c = ExtendedContext.copy() |
| 4484 | >>> c.Emin = -999 |
| 4485 | >>> c.Emax = 999 |
| 4486 | >>> c.ln(Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4487 | Decimal('-Infinity') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4488 | >>> c.ln(Decimal('1.000')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4489 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4490 | >>> c.ln(Decimal('2.71828183')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4491 | Decimal('1.00000000') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4492 | >>> c.ln(Decimal('10')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4493 | Decimal('2.30258509') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4494 | >>> c.ln(Decimal('+Infinity')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4495 | Decimal('Infinity') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4496 | >>> c.ln(1) |
| 4497 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4498 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4499 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4500 | return a.ln(context=self) |
| 4501 | |
| 4502 | def log10(self, a): |
| 4503 | """Returns the base 10 logarithm of the operand. |
| 4504 | |
| 4505 | >>> c = ExtendedContext.copy() |
| 4506 | >>> c.Emin = -999 |
| 4507 | >>> c.Emax = 999 |
| 4508 | >>> c.log10(Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4509 | Decimal('-Infinity') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4510 | >>> c.log10(Decimal('0.001')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4511 | Decimal('-3') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4512 | >>> c.log10(Decimal('1.000')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4513 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4514 | >>> c.log10(Decimal('2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4515 | Decimal('0.301029996') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4516 | >>> c.log10(Decimal('10')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4517 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4518 | >>> c.log10(Decimal('70')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4519 | Decimal('1.84509804') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4520 | >>> c.log10(Decimal('+Infinity')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4521 | Decimal('Infinity') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4522 | >>> c.log10(0) |
| 4523 | Decimal('-Infinity') |
| 4524 | >>> c.log10(1) |
| 4525 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4526 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4527 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4528 | return a.log10(context=self) |
| 4529 | |
| 4530 | def logb(self, a): |
| 4531 | """ Returns the exponent of the magnitude of the operand's MSD. |
| 4532 | |
| 4533 | The result is the integer which is the exponent of the magnitude |
| 4534 | of the most significant digit of the operand (as though the |
| 4535 | operand were truncated to a single digit while maintaining the |
| 4536 | value of that digit and without limiting the resulting exponent). |
| 4537 | |
| 4538 | >>> ExtendedContext.logb(Decimal('250')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4539 | Decimal('2') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4540 | >>> ExtendedContext.logb(Decimal('2.50')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4541 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4542 | >>> ExtendedContext.logb(Decimal('0.03')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4543 | Decimal('-2') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4544 | >>> ExtendedContext.logb(Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4545 | Decimal('-Infinity') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4546 | >>> ExtendedContext.logb(1) |
| 4547 | Decimal('0') |
| 4548 | >>> ExtendedContext.logb(10) |
| 4549 | Decimal('1') |
| 4550 | >>> ExtendedContext.logb(100) |
| 4551 | Decimal('2') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4552 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4553 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4554 | return a.logb(context=self) |
| 4555 | |
| 4556 | def logical_and(self, a, b): |
| 4557 | """Applies the logical operation 'and' between each operand's digits. |
| 4558 | |
| 4559 | The operands must be both logical numbers. |
| 4560 | |
| 4561 | >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4562 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4563 | >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4564 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4565 | >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4566 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4567 | >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4568 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4569 | >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4570 | Decimal('1000') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4571 | >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4572 | Decimal('10') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4573 | >>> ExtendedContext.logical_and(110, 1101) |
| 4574 | Decimal('100') |
| 4575 | >>> ExtendedContext.logical_and(Decimal(110), 1101) |
| 4576 | Decimal('100') |
| 4577 | >>> ExtendedContext.logical_and(110, Decimal(1101)) |
| 4578 | Decimal('100') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4579 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4580 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4581 | return a.logical_and(b, context=self) |
| 4582 | |
| 4583 | def logical_invert(self, a): |
| 4584 | """Invert all the digits in the operand. |
| 4585 | |
| 4586 | The operand must be a logical number. |
| 4587 | |
| 4588 | >>> ExtendedContext.logical_invert(Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4589 | Decimal('111111111') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4590 | >>> ExtendedContext.logical_invert(Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4591 | Decimal('111111110') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4592 | >>> ExtendedContext.logical_invert(Decimal('111111111')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4593 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4594 | >>> ExtendedContext.logical_invert(Decimal('101010101')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4595 | Decimal('10101010') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4596 | >>> ExtendedContext.logical_invert(1101) |
| 4597 | Decimal('111110010') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4598 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4599 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4600 | return a.logical_invert(context=self) |
| 4601 | |
| 4602 | def logical_or(self, a, b): |
| 4603 | """Applies the logical operation 'or' between each operand's digits. |
| 4604 | |
| 4605 | The operands must be both logical numbers. |
| 4606 | |
| 4607 | >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4608 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4609 | >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4610 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4611 | >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4612 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4613 | >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4614 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4615 | >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4616 | Decimal('1110') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4617 | >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4618 | Decimal('1110') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4619 | >>> ExtendedContext.logical_or(110, 1101) |
| 4620 | Decimal('1111') |
| 4621 | >>> ExtendedContext.logical_or(Decimal(110), 1101) |
| 4622 | Decimal('1111') |
| 4623 | >>> ExtendedContext.logical_or(110, Decimal(1101)) |
| 4624 | Decimal('1111') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4625 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4626 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4627 | return a.logical_or(b, context=self) |
| 4628 | |
| 4629 | def logical_xor(self, a, b): |
| 4630 | """Applies the logical operation 'xor' between each operand's digits. |
| 4631 | |
| 4632 | The operands must be both logical numbers. |
| 4633 | |
| 4634 | >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4635 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4636 | >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4637 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4638 | >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4639 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4640 | >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4641 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4642 | >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4643 | Decimal('110') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4644 | >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4645 | Decimal('1101') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4646 | >>> ExtendedContext.logical_xor(110, 1101) |
| 4647 | Decimal('1011') |
| 4648 | >>> ExtendedContext.logical_xor(Decimal(110), 1101) |
| 4649 | Decimal('1011') |
| 4650 | >>> ExtendedContext.logical_xor(110, Decimal(1101)) |
| 4651 | Decimal('1011') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4652 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4653 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4654 | return a.logical_xor(b, context=self) |
| 4655 | |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4656 | def max(self, a, b): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4657 | """max compares two values numerically and returns the maximum. |
| 4658 | |
| 4659 | If either operand is a NaN then the general rules apply. |
Christian Heimes | 679db4a | 2008-01-18 09:56:22 +0000 | [diff] [blame] | 4660 | Otherwise, the operands are compared as though by the compare |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 4661 | operation. If they are numerically equal then the left-hand operand |
| 4662 | is chosen as the result. Otherwise the maximum (closer to positive |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4663 | infinity) of the two operands is chosen as the result. |
| 4664 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4665 | >>> ExtendedContext.max(Decimal('3'), Decimal('2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4666 | Decimal('3') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4667 | >>> ExtendedContext.max(Decimal('-10'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4668 | Decimal('3') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4669 | >>> ExtendedContext.max(Decimal('1.0'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4670 | Decimal('1') |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 4671 | >>> ExtendedContext.max(Decimal('7'), Decimal('NaN')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4672 | Decimal('7') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4673 | >>> ExtendedContext.max(1, 2) |
| 4674 | Decimal('2') |
| 4675 | >>> ExtendedContext.max(Decimal(1), 2) |
| 4676 | Decimal('2') |
| 4677 | >>> ExtendedContext.max(1, Decimal(2)) |
| 4678 | Decimal('2') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4679 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4680 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4681 | return a.max(b, context=self) |
| 4682 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4683 | def max_mag(self, a, b): |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4684 | """Compares the values numerically with their sign ignored. |
| 4685 | |
| 4686 | >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN')) |
| 4687 | Decimal('7') |
| 4688 | >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10')) |
| 4689 | Decimal('-10') |
| 4690 | >>> ExtendedContext.max_mag(1, -2) |
| 4691 | Decimal('-2') |
| 4692 | >>> ExtendedContext.max_mag(Decimal(1), -2) |
| 4693 | Decimal('-2') |
| 4694 | >>> ExtendedContext.max_mag(1, Decimal(-2)) |
| 4695 | Decimal('-2') |
| 4696 | """ |
| 4697 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4698 | return a.max_mag(b, context=self) |
| 4699 | |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4700 | def min(self, a, b): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4701 | """min compares two values numerically and returns the minimum. |
| 4702 | |
| 4703 | If either operand is a NaN then the general rules apply. |
Christian Heimes | 679db4a | 2008-01-18 09:56:22 +0000 | [diff] [blame] | 4704 | Otherwise, the operands are compared as though by the compare |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 4705 | operation. If they are numerically equal then the left-hand operand |
| 4706 | is chosen as the result. Otherwise the minimum (closer to negative |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4707 | infinity) of the two operands is chosen as the result. |
| 4708 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4709 | >>> ExtendedContext.min(Decimal('3'), Decimal('2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4710 | Decimal('2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4711 | >>> ExtendedContext.min(Decimal('-10'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4712 | Decimal('-10') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4713 | >>> ExtendedContext.min(Decimal('1.0'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4714 | Decimal('1.0') |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 4715 | >>> ExtendedContext.min(Decimal('7'), Decimal('NaN')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4716 | Decimal('7') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4717 | >>> ExtendedContext.min(1, 2) |
| 4718 | Decimal('1') |
| 4719 | >>> ExtendedContext.min(Decimal(1), 2) |
| 4720 | Decimal('1') |
| 4721 | >>> ExtendedContext.min(1, Decimal(29)) |
| 4722 | Decimal('1') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4723 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4724 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4725 | return a.min(b, context=self) |
| 4726 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4727 | def min_mag(self, a, b): |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4728 | """Compares the values numerically with their sign ignored. |
| 4729 | |
| 4730 | >>> ExtendedContext.min_mag(Decimal('3'), Decimal('-2')) |
| 4731 | Decimal('-2') |
| 4732 | >>> ExtendedContext.min_mag(Decimal('-3'), Decimal('NaN')) |
| 4733 | Decimal('-3') |
| 4734 | >>> ExtendedContext.min_mag(1, -2) |
| 4735 | Decimal('1') |
| 4736 | >>> ExtendedContext.min_mag(Decimal(1), -2) |
| 4737 | Decimal('1') |
| 4738 | >>> ExtendedContext.min_mag(1, Decimal(-2)) |
| 4739 | Decimal('1') |
| 4740 | """ |
| 4741 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4742 | return a.min_mag(b, context=self) |
| 4743 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4744 | def minus(self, a): |
| 4745 | """Minus corresponds to unary prefix minus in Python. |
| 4746 | |
| 4747 | The operation is evaluated using the same rules as subtract; the |
| 4748 | operation minus(a) is calculated as subtract('0', a) where the '0' |
| 4749 | has the same exponent as the operand. |
| 4750 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4751 | >>> ExtendedContext.minus(Decimal('1.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4752 | Decimal('-1.3') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4753 | >>> ExtendedContext.minus(Decimal('-1.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4754 | Decimal('1.3') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4755 | >>> ExtendedContext.minus(1) |
| 4756 | Decimal('-1') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4757 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4758 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4759 | return a.__neg__(context=self) |
| 4760 | |
| 4761 | def multiply(self, a, b): |
| 4762 | """multiply multiplies two operands. |
| 4763 | |
| 4764 | If either operand is a special value then the general rules apply. |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4765 | Otherwise, the operands are multiplied together |
| 4766 | ('long multiplication'), resulting in a number which may be as long as |
| 4767 | the sum of the lengths of the two operands. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4768 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4769 | >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4770 | Decimal('3.60') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4771 | >>> ExtendedContext.multiply(Decimal('7'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4772 | Decimal('21') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4773 | >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4774 | Decimal('0.72') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4775 | >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4776 | Decimal('-0.0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4777 | >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4778 | Decimal('4.28135971E+11') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4779 | >>> ExtendedContext.multiply(7, 7) |
| 4780 | Decimal('49') |
| 4781 | >>> ExtendedContext.multiply(Decimal(7), 7) |
| 4782 | Decimal('49') |
| 4783 | >>> ExtendedContext.multiply(7, Decimal(7)) |
| 4784 | Decimal('49') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4785 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4786 | a = _convert_other(a, raiseit=True) |
| 4787 | r = a.__mul__(b, context=self) |
| 4788 | if r is NotImplemented: |
| 4789 | raise TypeError("Unable to convert %s to Decimal" % b) |
| 4790 | else: |
| 4791 | return r |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4792 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4793 | def next_minus(self, a): |
| 4794 | """Returns the largest representable number smaller than a. |
| 4795 | |
| 4796 | >>> c = ExtendedContext.copy() |
| 4797 | >>> c.Emin = -999 |
| 4798 | >>> c.Emax = 999 |
| 4799 | >>> ExtendedContext.next_minus(Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4800 | Decimal('0.999999999') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4801 | >>> c.next_minus(Decimal('1E-1007')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4802 | Decimal('0E-1007') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4803 | >>> ExtendedContext.next_minus(Decimal('-1.00000003')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4804 | Decimal('-1.00000004') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4805 | >>> c.next_minus(Decimal('Infinity')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4806 | Decimal('9.99999999E+999') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4807 | >>> c.next_minus(1) |
| 4808 | Decimal('0.999999999') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4809 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4810 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4811 | return a.next_minus(context=self) |
| 4812 | |
| 4813 | def next_plus(self, a): |
| 4814 | """Returns the smallest representable number larger than a. |
| 4815 | |
| 4816 | >>> c = ExtendedContext.copy() |
| 4817 | >>> c.Emin = -999 |
| 4818 | >>> c.Emax = 999 |
| 4819 | >>> ExtendedContext.next_plus(Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4820 | Decimal('1.00000001') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4821 | >>> c.next_plus(Decimal('-1E-1007')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4822 | Decimal('-0E-1007') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4823 | >>> ExtendedContext.next_plus(Decimal('-1.00000003')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4824 | Decimal('-1.00000002') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4825 | >>> c.next_plus(Decimal('-Infinity')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4826 | Decimal('-9.99999999E+999') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4827 | >>> c.next_plus(1) |
| 4828 | Decimal('1.00000001') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4829 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4830 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4831 | return a.next_plus(context=self) |
| 4832 | |
| 4833 | def next_toward(self, a, b): |
| 4834 | """Returns the number closest to a, in direction towards b. |
| 4835 | |
| 4836 | The result is the closest representable number from the first |
| 4837 | operand (but not the first operand) that is in the direction |
| 4838 | towards the second operand, unless the operands have the same |
| 4839 | value. |
| 4840 | |
| 4841 | >>> c = ExtendedContext.copy() |
| 4842 | >>> c.Emin = -999 |
| 4843 | >>> c.Emax = 999 |
| 4844 | >>> c.next_toward(Decimal('1'), Decimal('2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4845 | Decimal('1.00000001') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4846 | >>> c.next_toward(Decimal('-1E-1007'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4847 | Decimal('-0E-1007') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4848 | >>> c.next_toward(Decimal('-1.00000003'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4849 | Decimal('-1.00000002') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4850 | >>> c.next_toward(Decimal('1'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4851 | Decimal('0.999999999') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4852 | >>> c.next_toward(Decimal('1E-1007'), Decimal('-100')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4853 | Decimal('0E-1007') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4854 | >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4855 | Decimal('-1.00000004') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4856 | >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4857 | Decimal('-0.00') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4858 | >>> c.next_toward(0, 1) |
| 4859 | Decimal('1E-1007') |
| 4860 | >>> c.next_toward(Decimal(0), 1) |
| 4861 | Decimal('1E-1007') |
| 4862 | >>> c.next_toward(0, Decimal(1)) |
| 4863 | Decimal('1E-1007') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4864 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4865 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4866 | return a.next_toward(b, context=self) |
| 4867 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4868 | def normalize(self, a): |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 4869 | """normalize reduces an operand to its simplest form. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4870 | |
| 4871 | Essentially a plus operation with all trailing zeros removed from the |
| 4872 | result. |
| 4873 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4874 | >>> ExtendedContext.normalize(Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4875 | Decimal('2.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4876 | >>> ExtendedContext.normalize(Decimal('-2.0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4877 | Decimal('-2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4878 | >>> ExtendedContext.normalize(Decimal('1.200')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4879 | Decimal('1.2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4880 | >>> ExtendedContext.normalize(Decimal('-120')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4881 | Decimal('-1.2E+2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4882 | >>> ExtendedContext.normalize(Decimal('120.00')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4883 | Decimal('1.2E+2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4884 | >>> ExtendedContext.normalize(Decimal('0.00')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4885 | Decimal('0') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4886 | >>> ExtendedContext.normalize(6) |
| 4887 | Decimal('6') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4888 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4889 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4890 | return a.normalize(context=self) |
| 4891 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4892 | def number_class(self, a): |
| 4893 | """Returns an indication of the class of the operand. |
| 4894 | |
| 4895 | The class is one of the following strings: |
| 4896 | -sNaN |
| 4897 | -NaN |
| 4898 | -Infinity |
| 4899 | -Normal |
| 4900 | -Subnormal |
| 4901 | -Zero |
| 4902 | +Zero |
| 4903 | +Subnormal |
| 4904 | +Normal |
| 4905 | +Infinity |
| 4906 | |
| 4907 | >>> c = Context(ExtendedContext) |
| 4908 | >>> c.Emin = -999 |
| 4909 | >>> c.Emax = 999 |
| 4910 | >>> c.number_class(Decimal('Infinity')) |
| 4911 | '+Infinity' |
| 4912 | >>> c.number_class(Decimal('1E-10')) |
| 4913 | '+Normal' |
| 4914 | >>> c.number_class(Decimal('2.50')) |
| 4915 | '+Normal' |
| 4916 | >>> c.number_class(Decimal('0.1E-999')) |
| 4917 | '+Subnormal' |
| 4918 | >>> c.number_class(Decimal('0')) |
| 4919 | '+Zero' |
| 4920 | >>> c.number_class(Decimal('-0')) |
| 4921 | '-Zero' |
| 4922 | >>> c.number_class(Decimal('-0.1E-999')) |
| 4923 | '-Subnormal' |
| 4924 | >>> c.number_class(Decimal('-1E-10')) |
| 4925 | '-Normal' |
| 4926 | >>> c.number_class(Decimal('-2.50')) |
| 4927 | '-Normal' |
| 4928 | >>> c.number_class(Decimal('-Infinity')) |
| 4929 | '-Infinity' |
| 4930 | >>> c.number_class(Decimal('NaN')) |
| 4931 | 'NaN' |
| 4932 | >>> c.number_class(Decimal('-NaN')) |
| 4933 | 'NaN' |
| 4934 | >>> c.number_class(Decimal('sNaN')) |
| 4935 | 'sNaN' |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4936 | >>> c.number_class(123) |
| 4937 | '+Normal' |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4938 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4939 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4940 | return a.number_class(context=self) |
| 4941 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4942 | def plus(self, a): |
| 4943 | """Plus corresponds to unary prefix plus in Python. |
| 4944 | |
| 4945 | The operation is evaluated using the same rules as add; the |
| 4946 | operation plus(a) is calculated as add('0', a) where the '0' |
| 4947 | has the same exponent as the operand. |
| 4948 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4949 | >>> ExtendedContext.plus(Decimal('1.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4950 | Decimal('1.3') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4951 | >>> ExtendedContext.plus(Decimal('-1.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4952 | Decimal('-1.3') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4953 | >>> ExtendedContext.plus(-1) |
| 4954 | Decimal('-1') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4955 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4956 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4957 | return a.__pos__(context=self) |
| 4958 | |
| 4959 | def power(self, a, b, modulo=None): |
| 4960 | """Raises a to the power of b, to modulo if given. |
| 4961 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4962 | With two arguments, compute a**b. If a is negative then b |
| 4963 | must be integral. The result will be inexact unless b is |
| 4964 | integral and the result is finite and can be expressed exactly |
| 4965 | in 'precision' digits. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4966 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4967 | With three arguments, compute (a**b) % modulo. For the |
| 4968 | three argument form, the following restrictions on the |
| 4969 | arguments hold: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4970 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4971 | - all three arguments must be integral |
| 4972 | - b must be nonnegative |
| 4973 | - at least one of a or b must be nonzero |
| 4974 | - modulo must be nonzero and have at most 'precision' digits |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4975 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4976 | The result of pow(a, b, modulo) is identical to the result |
| 4977 | that would be obtained by computing (a**b) % modulo with |
| 4978 | unbounded precision, but is computed more efficiently. It is |
| 4979 | always exact. |
| 4980 | |
| 4981 | >>> c = ExtendedContext.copy() |
| 4982 | >>> c.Emin = -999 |
| 4983 | >>> c.Emax = 999 |
| 4984 | >>> c.power(Decimal('2'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4985 | Decimal('8') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4986 | >>> c.power(Decimal('-2'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4987 | Decimal('-8') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4988 | >>> c.power(Decimal('2'), Decimal('-3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4989 | Decimal('0.125') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4990 | >>> c.power(Decimal('1.7'), Decimal('8')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4991 | Decimal('69.7575744') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4992 | >>> c.power(Decimal('10'), Decimal('0.301029996')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4993 | Decimal('2.00000000') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4994 | >>> c.power(Decimal('Infinity'), Decimal('-1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4995 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4996 | >>> c.power(Decimal('Infinity'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4997 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4998 | >>> c.power(Decimal('Infinity'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4999 | Decimal('Infinity') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5000 | >>> c.power(Decimal('-Infinity'), Decimal('-1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5001 | Decimal('-0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5002 | >>> c.power(Decimal('-Infinity'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5003 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5004 | >>> c.power(Decimal('-Infinity'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5005 | Decimal('-Infinity') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5006 | >>> c.power(Decimal('-Infinity'), Decimal('2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5007 | Decimal('Infinity') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5008 | >>> c.power(Decimal('0'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5009 | Decimal('NaN') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5010 | |
| 5011 | >>> c.power(Decimal('3'), Decimal('7'), Decimal('16')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5012 | Decimal('11') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5013 | >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5014 | Decimal('-11') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5015 | >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5016 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5017 | >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5018 | Decimal('11') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5019 | >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5020 | Decimal('11729830') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5021 | >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5022 | Decimal('-0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5023 | >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5024 | Decimal('1') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5025 | >>> ExtendedContext.power(7, 7) |
| 5026 | Decimal('823543') |
| 5027 | >>> ExtendedContext.power(Decimal(7), 7) |
| 5028 | Decimal('823543') |
| 5029 | >>> ExtendedContext.power(7, Decimal(7), 2) |
| 5030 | Decimal('1') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5031 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5032 | a = _convert_other(a, raiseit=True) |
| 5033 | r = a.__pow__(b, modulo, context=self) |
| 5034 | if r is NotImplemented: |
| 5035 | raise TypeError("Unable to convert %s to Decimal" % b) |
| 5036 | else: |
| 5037 | return r |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5038 | |
| 5039 | def quantize(self, a, b): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 5040 | """Returns a value equal to 'a' (rounded), having the exponent of 'b'. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5041 | |
| 5042 | 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] | 5043 | operand. It may be rounded using the current rounding setting (if the |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5044 | exponent is being increased), multiplied by a positive power of ten (if |
| 5045 | the exponent is being decreased), or is unchanged (if the exponent is |
| 5046 | already equal to that of the right-hand operand). |
| 5047 | |
| 5048 | Unlike other operations, if the length of the coefficient after the |
| 5049 | quantize operation would be greater than precision then an Invalid |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 5050 | operation condition is raised. This guarantees that, unless there is |
| 5051 | 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] | 5052 | equal to that of the right-hand operand. |
| 5053 | |
| 5054 | Also unlike other operations, quantize will never raise Underflow, even |
| 5055 | if the result is subnormal and inexact. |
| 5056 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5057 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5058 | Decimal('2.170') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5059 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5060 | Decimal('2.17') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5061 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5062 | Decimal('2.2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5063 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5064 | Decimal('2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5065 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5066 | Decimal('0E+1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5067 | >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5068 | Decimal('-Infinity') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5069 | >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5070 | Decimal('NaN') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5071 | >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5072 | Decimal('-0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5073 | >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5074 | Decimal('-0E+5') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5075 | >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5076 | Decimal('NaN') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5077 | >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5078 | Decimal('NaN') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5079 | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5080 | Decimal('217.0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5081 | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5082 | Decimal('217') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5083 | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5084 | Decimal('2.2E+2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5085 | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5086 | Decimal('2E+2') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5087 | >>> ExtendedContext.quantize(1, 2) |
| 5088 | Decimal('1') |
| 5089 | >>> ExtendedContext.quantize(Decimal(1), 2) |
| 5090 | Decimal('1') |
| 5091 | >>> ExtendedContext.quantize(1, Decimal(2)) |
| 5092 | Decimal('1') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5093 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5094 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5095 | return a.quantize(b, context=self) |
| 5096 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5097 | def radix(self): |
| 5098 | """Just returns 10, as this is Decimal, :) |
| 5099 | |
| 5100 | >>> ExtendedContext.radix() |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5101 | Decimal('10') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5102 | """ |
| 5103 | return Decimal(10) |
| 5104 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5105 | def remainder(self, a, b): |
| 5106 | """Returns the remainder from integer division. |
| 5107 | |
| 5108 | 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] | 5109 | calculating integer division as described for divide-integer, rounded |
| 5110 | to precision digits if necessary. The sign of the result, if |
| 5111 | non-zero, is the same as that of the original dividend. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5112 | |
| 5113 | This operation will fail under the same conditions as integer division |
| 5114 | (that is, if integer division on the same two operands would fail, the |
| 5115 | remainder cannot be calculated). |
| 5116 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5117 | >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5118 | Decimal('2.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5119 | >>> ExtendedContext.remainder(Decimal('10'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5120 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5121 | >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5122 | Decimal('-1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5123 | >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5124 | Decimal('0.2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5125 | >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5126 | Decimal('0.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5127 | >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5128 | Decimal('1.0') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5129 | >>> ExtendedContext.remainder(22, 6) |
| 5130 | Decimal('4') |
| 5131 | >>> ExtendedContext.remainder(Decimal(22), 6) |
| 5132 | Decimal('4') |
| 5133 | >>> ExtendedContext.remainder(22, Decimal(6)) |
| 5134 | Decimal('4') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5135 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5136 | a = _convert_other(a, raiseit=True) |
| 5137 | r = a.__mod__(b, context=self) |
| 5138 | if r is NotImplemented: |
| 5139 | raise TypeError("Unable to convert %s to Decimal" % b) |
| 5140 | else: |
| 5141 | return r |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5142 | |
| 5143 | def remainder_near(self, a, b): |
| 5144 | """Returns to be "a - b * n", where n is the integer nearest the exact |
| 5145 | 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] | 5146 | 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] | 5147 | sign of a. |
| 5148 | |
| 5149 | This operation will fail under the same conditions as integer division |
| 5150 | (that is, if integer division on the same two operands would fail, the |
| 5151 | remainder cannot be calculated). |
| 5152 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5153 | >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5154 | Decimal('-0.9') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5155 | >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5156 | Decimal('-2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5157 | >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5158 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5159 | >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5160 | Decimal('-1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5161 | >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5162 | Decimal('0.2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5163 | >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5164 | Decimal('0.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5165 | >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5166 | Decimal('-0.3') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5167 | >>> ExtendedContext.remainder_near(3, 11) |
| 5168 | Decimal('3') |
| 5169 | >>> ExtendedContext.remainder_near(Decimal(3), 11) |
| 5170 | Decimal('3') |
| 5171 | >>> ExtendedContext.remainder_near(3, Decimal(11)) |
| 5172 | Decimal('3') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5173 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5174 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5175 | return a.remainder_near(b, context=self) |
| 5176 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5177 | def rotate(self, a, b): |
| 5178 | """Returns a rotated copy of a, b times. |
| 5179 | |
| 5180 | The coefficient of the result is a rotated copy of the digits in |
| 5181 | the coefficient of the first operand. The number of places of |
| 5182 | rotation is taken from the absolute value of the second operand, |
| 5183 | with the rotation being to the left if the second operand is |
| 5184 | positive or to the right otherwise. |
| 5185 | |
| 5186 | >>> ExtendedContext.rotate(Decimal('34'), Decimal('8')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5187 | Decimal('400000003') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5188 | >>> ExtendedContext.rotate(Decimal('12'), Decimal('9')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5189 | Decimal('12') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5190 | >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5191 | Decimal('891234567') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5192 | >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5193 | Decimal('123456789') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5194 | >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5195 | Decimal('345678912') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5196 | >>> ExtendedContext.rotate(1333333, 1) |
| 5197 | Decimal('13333330') |
| 5198 | >>> ExtendedContext.rotate(Decimal(1333333), 1) |
| 5199 | Decimal('13333330') |
| 5200 | >>> ExtendedContext.rotate(1333333, Decimal(1)) |
| 5201 | Decimal('13333330') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5202 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5203 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5204 | return a.rotate(b, context=self) |
| 5205 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5206 | def same_quantum(self, a, b): |
| 5207 | """Returns True if the two operands have the same exponent. |
| 5208 | |
| 5209 | The result is never affected by either the sign or the coefficient of |
| 5210 | either operand. |
| 5211 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5212 | >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5213 | False |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5214 | >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5215 | True |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5216 | >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5217 | False |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5218 | >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5219 | True |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5220 | >>> ExtendedContext.same_quantum(10000, -1) |
| 5221 | True |
| 5222 | >>> ExtendedContext.same_quantum(Decimal(10000), -1) |
| 5223 | True |
| 5224 | >>> ExtendedContext.same_quantum(10000, Decimal(-1)) |
| 5225 | True |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5226 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5227 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5228 | return a.same_quantum(b) |
| 5229 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5230 | def scaleb (self, a, b): |
| 5231 | """Returns the first operand after adding the second value its exp. |
| 5232 | |
| 5233 | >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5234 | Decimal('0.0750') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5235 | >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5236 | Decimal('7.50') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5237 | >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5238 | Decimal('7.50E+3') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5239 | >>> ExtendedContext.scaleb(1, 4) |
| 5240 | Decimal('1E+4') |
| 5241 | >>> ExtendedContext.scaleb(Decimal(1), 4) |
| 5242 | Decimal('1E+4') |
| 5243 | >>> ExtendedContext.scaleb(1, Decimal(4)) |
| 5244 | Decimal('1E+4') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5245 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5246 | a = _convert_other(a, raiseit=True) |
| 5247 | return a.scaleb(b, context=self) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5248 | |
| 5249 | def shift(self, a, b): |
| 5250 | """Returns a shifted copy of a, b times. |
| 5251 | |
| 5252 | The coefficient of the result is a shifted copy of the digits |
| 5253 | in the coefficient of the first operand. The number of places |
| 5254 | to shift is taken from the absolute value of the second operand, |
| 5255 | with the shift being to the left if the second operand is |
| 5256 | positive or to the right otherwise. Digits shifted into the |
| 5257 | coefficient are zeros. |
| 5258 | |
| 5259 | >>> ExtendedContext.shift(Decimal('34'), Decimal('8')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5260 | Decimal('400000000') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5261 | >>> ExtendedContext.shift(Decimal('12'), Decimal('9')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5262 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5263 | >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5264 | Decimal('1234567') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5265 | >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5266 | Decimal('123456789') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5267 | >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5268 | Decimal('345678900') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5269 | >>> ExtendedContext.shift(88888888, 2) |
| 5270 | Decimal('888888800') |
| 5271 | >>> ExtendedContext.shift(Decimal(88888888), 2) |
| 5272 | Decimal('888888800') |
| 5273 | >>> ExtendedContext.shift(88888888, Decimal(2)) |
| 5274 | Decimal('888888800') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5275 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5276 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5277 | return a.shift(b, context=self) |
| 5278 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5279 | def sqrt(self, a): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 5280 | """Square root of a non-negative number to context precision. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5281 | |
| 5282 | If the result must be inexact, it is rounded using the round-half-even |
| 5283 | algorithm. |
| 5284 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5285 | >>> ExtendedContext.sqrt(Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5286 | Decimal('0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5287 | >>> ExtendedContext.sqrt(Decimal('-0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5288 | Decimal('-0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5289 | >>> ExtendedContext.sqrt(Decimal('0.39')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5290 | Decimal('0.624499800') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5291 | >>> ExtendedContext.sqrt(Decimal('100')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5292 | Decimal('10') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5293 | >>> ExtendedContext.sqrt(Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5294 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5295 | >>> ExtendedContext.sqrt(Decimal('1.0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5296 | Decimal('1.0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5297 | >>> ExtendedContext.sqrt(Decimal('1.00')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5298 | Decimal('1.0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5299 | >>> ExtendedContext.sqrt(Decimal('7')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5300 | Decimal('2.64575131') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5301 | >>> ExtendedContext.sqrt(Decimal('10')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5302 | Decimal('3.16227766') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5303 | >>> ExtendedContext.sqrt(2) |
| 5304 | Decimal('1.41421356') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5305 | >>> ExtendedContext.prec |
Raymond Hettinger | 6ea4845 | 2004-07-03 12:26:21 +0000 | [diff] [blame] | 5306 | 9 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5307 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5308 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5309 | return a.sqrt(context=self) |
| 5310 | |
| 5311 | def subtract(self, a, b): |
Georg Brandl | f33d01d | 2005-08-22 19:35:18 +0000 | [diff] [blame] | 5312 | """Return the difference between the two operands. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5313 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5314 | >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5315 | Decimal('0.23') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5316 | >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5317 | Decimal('0.00') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5318 | >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5319 | Decimal('-0.77') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5320 | >>> ExtendedContext.subtract(8, 5) |
| 5321 | Decimal('3') |
| 5322 | >>> ExtendedContext.subtract(Decimal(8), 5) |
| 5323 | Decimal('3') |
| 5324 | >>> ExtendedContext.subtract(8, Decimal(5)) |
| 5325 | Decimal('3') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5326 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5327 | a = _convert_other(a, raiseit=True) |
| 5328 | r = a.__sub__(b, context=self) |
| 5329 | if r is NotImplemented: |
| 5330 | raise TypeError("Unable to convert %s to Decimal" % b) |
| 5331 | else: |
| 5332 | return r |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5333 | |
| 5334 | def to_eng_string(self, a): |
| 5335 | """Converts a number to a string, using scientific notation. |
| 5336 | |
| 5337 | The operation is not affected by the context. |
| 5338 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5339 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5340 | return a.to_eng_string(context=self) |
| 5341 | |
| 5342 | def to_sci_string(self, a): |
| 5343 | """Converts a number to a string, using scientific notation. |
| 5344 | |
| 5345 | The operation is not affected by the context. |
| 5346 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5347 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5348 | return a.__str__(context=self) |
| 5349 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5350 | def to_integral_exact(self, a): |
| 5351 | """Rounds to an integer. |
| 5352 | |
| 5353 | When the operand has a negative exponent, the result is the same |
| 5354 | as using the quantize() operation using the given operand as the |
| 5355 | left-hand-operand, 1E+0 as the right-hand-operand, and the precision |
| 5356 | of the operand as the precision setting; Inexact and Rounded flags |
| 5357 | are allowed in this operation. The rounding mode is taken from the |
| 5358 | context. |
| 5359 | |
| 5360 | >>> ExtendedContext.to_integral_exact(Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5361 | Decimal('2') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5362 | >>> ExtendedContext.to_integral_exact(Decimal('100')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5363 | Decimal('100') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5364 | >>> ExtendedContext.to_integral_exact(Decimal('100.0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5365 | Decimal('100') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5366 | >>> ExtendedContext.to_integral_exact(Decimal('101.5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5367 | Decimal('102') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5368 | >>> ExtendedContext.to_integral_exact(Decimal('-101.5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5369 | Decimal('-102') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5370 | >>> ExtendedContext.to_integral_exact(Decimal('10E+5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5371 | Decimal('1.0E+6') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5372 | >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5373 | Decimal('7.89E+77') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5374 | >>> ExtendedContext.to_integral_exact(Decimal('-Inf')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5375 | Decimal('-Infinity') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5376 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5377 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5378 | return a.to_integral_exact(context=self) |
| 5379 | |
| 5380 | def to_integral_value(self, a): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5381 | """Rounds to an integer. |
| 5382 | |
| 5383 | When the operand has a negative exponent, the result is the same |
| 5384 | as using the quantize() operation using the given operand as the |
| 5385 | left-hand-operand, 1E+0 as the right-hand-operand, and the precision |
| 5386 | 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] | 5387 | be set. The rounding mode is taken from the context. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5388 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5389 | >>> ExtendedContext.to_integral_value(Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5390 | Decimal('2') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5391 | >>> ExtendedContext.to_integral_value(Decimal('100')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5392 | Decimal('100') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5393 | >>> ExtendedContext.to_integral_value(Decimal('100.0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5394 | Decimal('100') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5395 | >>> ExtendedContext.to_integral_value(Decimal('101.5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5396 | Decimal('102') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5397 | >>> ExtendedContext.to_integral_value(Decimal('-101.5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5398 | Decimal('-102') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5399 | >>> ExtendedContext.to_integral_value(Decimal('10E+5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5400 | Decimal('1.0E+6') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5401 | >>> ExtendedContext.to_integral_value(Decimal('7.89E+77')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5402 | Decimal('7.89E+77') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5403 | >>> ExtendedContext.to_integral_value(Decimal('-Inf')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5404 | Decimal('-Infinity') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5405 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5406 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5407 | return a.to_integral_value(context=self) |
| 5408 | |
| 5409 | # the method name changed, but we provide also the old one, for compatibility |
| 5410 | to_integral = to_integral_value |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5411 | |
| 5412 | class _WorkRep(object): |
| 5413 | __slots__ = ('sign','int','exp') |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 5414 | # sign: 0 or 1 |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5415 | # int: int |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5416 | # exp: None, int, or string |
| 5417 | |
| 5418 | def __init__(self, value=None): |
| 5419 | if value is None: |
| 5420 | self.sign = None |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5421 | self.int = 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5422 | self.exp = None |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 5423 | elif isinstance(value, Decimal): |
| 5424 | self.sign = value._sign |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5425 | self.int = int(value._int) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5426 | self.exp = value._exp |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 5427 | else: |
| 5428 | # assert isinstance(value, tuple) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5429 | self.sign = value[0] |
| 5430 | self.int = value[1] |
| 5431 | self.exp = value[2] |
| 5432 | |
| 5433 | def __repr__(self): |
| 5434 | return "(%r, %r, %r)" % (self.sign, self.int, self.exp) |
| 5435 | |
| 5436 | __str__ = __repr__ |
| 5437 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5438 | |
| 5439 | |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 5440 | def _normalize(op1, op2, prec = 0): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5441 | """Normalizes op1, op2 to have the same exp and length of coefficient. |
| 5442 | |
| 5443 | Done during addition. |
| 5444 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5445 | if op1.exp < op2.exp: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5446 | tmp = op2 |
| 5447 | other = op1 |
| 5448 | else: |
| 5449 | tmp = op1 |
| 5450 | other = op2 |
| 5451 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5452 | # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1). |
| 5453 | # Then adding 10**exp to tmp has the same effect (after rounding) |
| 5454 | # as adding any positive quantity smaller than 10**exp; similarly |
| 5455 | # for subtraction. So if other is smaller than 10**exp we replace |
| 5456 | # 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] | 5457 | tmp_len = len(str(tmp.int)) |
| 5458 | other_len = len(str(other.int)) |
| 5459 | exp = tmp.exp + min(-1, tmp_len - prec - 2) |
| 5460 | if other_len + other.exp - 1 < exp: |
| 5461 | other.int = 1 |
| 5462 | other.exp = exp |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5463 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5464 | tmp.int *= 10 ** (tmp.exp - other.exp) |
| 5465 | tmp.exp = other.exp |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5466 | return op1, op2 |
| 5467 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5468 | ##### Integer arithmetic functions used by ln, log10, exp and __pow__ ##### |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5469 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5470 | # This function from Tim Peters was taken from here: |
| 5471 | # http://mail.python.org/pipermail/python-list/1999-July/007758.html |
| 5472 | # The correction being in the function definition is for speed, and |
| 5473 | # the whole function is not resolved with math.log because of avoiding |
| 5474 | # the use of floats. |
| 5475 | def _nbits(n, correction = { |
| 5476 | '0': 4, '1': 3, '2': 2, '3': 2, |
| 5477 | '4': 1, '5': 1, '6': 1, '7': 1, |
| 5478 | '8': 0, '9': 0, 'a': 0, 'b': 0, |
| 5479 | 'c': 0, 'd': 0, 'e': 0, 'f': 0}): |
| 5480 | """Number of bits in binary representation of the positive integer n, |
| 5481 | or 0 if n == 0. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5482 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5483 | if n < 0: |
| 5484 | raise ValueError("The argument to _nbits should be nonnegative.") |
| 5485 | hex_n = "%x" % n |
| 5486 | return 4*len(hex_n) - correction[hex_n[0]] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5487 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5488 | def _sqrt_nearest(n, a): |
| 5489 | """Closest integer to the square root of the positive integer n. a is |
| 5490 | an initial approximation to the square root. Any positive integer |
| 5491 | will do for a, but the closer a is to the square root of n the |
| 5492 | faster convergence will be. |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5493 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5494 | """ |
| 5495 | if n <= 0 or a <= 0: |
| 5496 | raise ValueError("Both arguments to _sqrt_nearest should be positive.") |
| 5497 | |
| 5498 | b=0 |
| 5499 | while a != b: |
| 5500 | b, a = a, a--n//a>>1 |
| 5501 | return a |
| 5502 | |
| 5503 | def _rshift_nearest(x, shift): |
| 5504 | """Given an integer x and a nonnegative integer shift, return closest |
| 5505 | integer to x / 2**shift; use round-to-even in case of a tie. |
| 5506 | |
| 5507 | """ |
| 5508 | b, q = 1 << shift, x >> shift |
| 5509 | return q + (2*(x & (b-1)) + (q&1) > b) |
| 5510 | |
| 5511 | def _div_nearest(a, b): |
| 5512 | """Closest integer to a/b, a and b positive integers; rounds to even |
| 5513 | in the case of a tie. |
| 5514 | |
| 5515 | """ |
| 5516 | q, r = divmod(a, b) |
| 5517 | return q + (2*r + (q&1) > b) |
| 5518 | |
| 5519 | def _ilog(x, M, L = 8): |
| 5520 | """Integer approximation to M*log(x/M), with absolute error boundable |
| 5521 | in terms only of x/M. |
| 5522 | |
| 5523 | Given positive integers x and M, return an integer approximation to |
| 5524 | M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference |
| 5525 | between the approximation and the exact result is at most 22. For |
| 5526 | L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In |
| 5527 | both cases these are upper bounds on the error; it will usually be |
| 5528 | much smaller.""" |
| 5529 | |
| 5530 | # The basic algorithm is the following: let log1p be the function |
| 5531 | # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use |
| 5532 | # the reduction |
| 5533 | # |
| 5534 | # log1p(y) = 2*log1p(y/(1+sqrt(1+y))) |
| 5535 | # |
| 5536 | # repeatedly until the argument to log1p is small (< 2**-L in |
| 5537 | # absolute value). For small y we can use the Taylor series |
| 5538 | # expansion |
| 5539 | # |
| 5540 | # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T |
| 5541 | # |
| 5542 | # truncating at T such that y**T is small enough. The whole |
| 5543 | # computation is carried out in a form of fixed-point arithmetic, |
| 5544 | # with a real number z being represented by an integer |
| 5545 | # approximation to z*M. To avoid loss of precision, the y below |
| 5546 | # is actually an integer approximation to 2**R*y*M, where R is the |
| 5547 | # number of reductions performed so far. |
| 5548 | |
| 5549 | y = x-M |
| 5550 | # argument reduction; R = number of reductions performed |
| 5551 | R = 0 |
| 5552 | while (R <= L and abs(y) << L-R >= M or |
| 5553 | R > L and abs(y) >> R-L >= M): |
| 5554 | y = _div_nearest((M*y) << 1, |
| 5555 | M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M)) |
| 5556 | R += 1 |
| 5557 | |
| 5558 | # Taylor series with T terms |
| 5559 | T = -int(-10*len(str(M))//(3*L)) |
| 5560 | yshift = _rshift_nearest(y, R) |
| 5561 | w = _div_nearest(M, T) |
| 5562 | for k in range(T-1, 0, -1): |
| 5563 | w = _div_nearest(M, k) - _div_nearest(yshift*w, M) |
| 5564 | |
| 5565 | return _div_nearest(w*y, M) |
| 5566 | |
| 5567 | def _dlog10(c, e, p): |
| 5568 | """Given integers c, e and p with c > 0, p >= 0, compute an integer |
| 5569 | approximation to 10**p * log10(c*10**e), with an absolute error of |
| 5570 | at most 1. Assumes that c*10**e is not exactly 1.""" |
| 5571 | |
| 5572 | # increase precision by 2; compensate for this by dividing |
| 5573 | # final result by 100 |
| 5574 | p += 2 |
| 5575 | |
| 5576 | # write c*10**e as d*10**f with either: |
| 5577 | # f >= 0 and 1 <= d <= 10, or |
| 5578 | # f <= 0 and 0.1 <= d <= 1. |
| 5579 | # Thus for c*10**e close to 1, f = 0 |
| 5580 | l = len(str(c)) |
| 5581 | f = e+l - (e+l >= 1) |
| 5582 | |
| 5583 | if p > 0: |
| 5584 | M = 10**p |
| 5585 | k = e+p-f |
| 5586 | if k >= 0: |
| 5587 | c *= 10**k |
| 5588 | else: |
| 5589 | c = _div_nearest(c, 10**-k) |
| 5590 | |
| 5591 | log_d = _ilog(c, M) # error < 5 + 22 = 27 |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5592 | log_10 = _log10_digits(p) # error < 1 |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5593 | log_d = _div_nearest(log_d*M, log_10) |
| 5594 | log_tenpower = f*M # exact |
| 5595 | else: |
| 5596 | log_d = 0 # error < 2.31 |
Neal Norwitz | 2f99b24 | 2008-08-24 05:48:10 +0000 | [diff] [blame] | 5597 | log_tenpower = _div_nearest(f, 10**-p) # error < 0.5 |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5598 | |
| 5599 | return _div_nearest(log_tenpower+log_d, 100) |
| 5600 | |
| 5601 | def _dlog(c, e, p): |
| 5602 | """Given integers c, e and p with c > 0, compute an integer |
| 5603 | approximation to 10**p * log(c*10**e), with an absolute error of |
| 5604 | at most 1. Assumes that c*10**e is not exactly 1.""" |
| 5605 | |
| 5606 | # Increase precision by 2. The precision increase is compensated |
| 5607 | # for at the end with a division by 100. |
| 5608 | p += 2 |
| 5609 | |
| 5610 | # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10, |
| 5611 | # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e) |
| 5612 | # as 10**p * log(d) + 10**p*f * log(10). |
| 5613 | l = len(str(c)) |
| 5614 | f = e+l - (e+l >= 1) |
| 5615 | |
| 5616 | # compute approximation to 10**p*log(d), with error < 27 |
| 5617 | if p > 0: |
| 5618 | k = e+p-f |
| 5619 | if k >= 0: |
| 5620 | c *= 10**k |
| 5621 | else: |
| 5622 | c = _div_nearest(c, 10**-k) # error of <= 0.5 in c |
| 5623 | |
| 5624 | # _ilog magnifies existing error in c by a factor of at most 10 |
| 5625 | log_d = _ilog(c, 10**p) # error < 5 + 22 = 27 |
| 5626 | else: |
| 5627 | # p <= 0: just approximate the whole thing by 0; error < 2.31 |
| 5628 | log_d = 0 |
| 5629 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5630 | # compute approximation to f*10**p*log(10), with error < 11. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5631 | if f: |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5632 | extra = len(str(abs(f)))-1 |
| 5633 | if p + extra >= 0: |
| 5634 | # error in f * _log10_digits(p+extra) < |f| * 1 = |f| |
| 5635 | # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11 |
| 5636 | f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5637 | else: |
| 5638 | f_log_ten = 0 |
| 5639 | else: |
| 5640 | f_log_ten = 0 |
| 5641 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5642 | # 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] | 5643 | return _div_nearest(f_log_ten + log_d, 100) |
| 5644 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5645 | class _Log10Memoize(object): |
| 5646 | """Class to compute, store, and allow retrieval of, digits of the |
| 5647 | constant log(10) = 2.302585.... This constant is needed by |
| 5648 | Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__.""" |
| 5649 | def __init__(self): |
| 5650 | self.digits = "23025850929940456840179914546843642076011014886" |
| 5651 | |
| 5652 | def getdigits(self, p): |
| 5653 | """Given an integer p >= 0, return floor(10**p)*log(10). |
| 5654 | |
| 5655 | For example, self.getdigits(3) returns 2302. |
| 5656 | """ |
| 5657 | # digits are stored as a string, for quick conversion to |
| 5658 | # integer in the case that we've already computed enough |
| 5659 | # digits; the stored digits should always be correct |
| 5660 | # (truncated, not rounded to nearest). |
| 5661 | if p < 0: |
| 5662 | raise ValueError("p should be nonnegative") |
| 5663 | |
| 5664 | if p >= len(self.digits): |
| 5665 | # compute p+3, p+6, p+9, ... digits; continue until at |
| 5666 | # least one of the extra digits is nonzero |
| 5667 | extra = 3 |
| 5668 | while True: |
| 5669 | # compute p+extra digits, correct to within 1ulp |
| 5670 | M = 10**(p+extra+2) |
| 5671 | digits = str(_div_nearest(_ilog(10*M, M), 100)) |
| 5672 | if digits[-extra:] != '0'*extra: |
| 5673 | break |
| 5674 | extra += 3 |
| 5675 | # keep all reliable digits so far; remove trailing zeros |
| 5676 | # and next nonzero digit |
| 5677 | self.digits = digits.rstrip('0')[:-1] |
| 5678 | return int(self.digits[:p+1]) |
| 5679 | |
| 5680 | _log10_digits = _Log10Memoize().getdigits |
| 5681 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5682 | def _iexp(x, M, L=8): |
| 5683 | """Given integers x and M, M > 0, such that x/M is small in absolute |
| 5684 | value, compute an integer approximation to M*exp(x/M). For 0 <= |
| 5685 | x/M <= 2.4, the absolute error in the result is bounded by 60 (and |
| 5686 | is usually much smaller).""" |
| 5687 | |
| 5688 | # Algorithm: to compute exp(z) for a real number z, first divide z |
| 5689 | # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then |
| 5690 | # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor |
| 5691 | # series |
| 5692 | # |
| 5693 | # expm1(x) = x + x**2/2! + x**3/3! + ... |
| 5694 | # |
| 5695 | # Now use the identity |
| 5696 | # |
| 5697 | # expm1(2x) = expm1(x)*(expm1(x)+2) |
| 5698 | # |
| 5699 | # R times to compute the sequence expm1(z/2**R), |
| 5700 | # expm1(z/2**(R-1)), ... , exp(z/2), exp(z). |
| 5701 | |
| 5702 | # Find R such that x/2**R/M <= 2**-L |
| 5703 | R = _nbits((x<<L)//M) |
| 5704 | |
| 5705 | # Taylor series. (2**L)**T > M |
| 5706 | T = -int(-10*len(str(M))//(3*L)) |
| 5707 | y = _div_nearest(x, T) |
| 5708 | Mshift = M<<R |
| 5709 | for i in range(T-1, 0, -1): |
| 5710 | y = _div_nearest(x*(Mshift + y), Mshift * i) |
| 5711 | |
| 5712 | # Expansion |
| 5713 | for k in range(R-1, -1, -1): |
| 5714 | Mshift = M<<(k+2) |
| 5715 | y = _div_nearest(y*(y+Mshift), Mshift) |
| 5716 | |
| 5717 | return M+y |
| 5718 | |
| 5719 | def _dexp(c, e, p): |
| 5720 | """Compute an approximation to exp(c*10**e), with p decimal places of |
| 5721 | precision. |
| 5722 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5723 | Returns integers d, f such that: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5724 | |
| 5725 | 10**(p-1) <= d <= 10**p, and |
| 5726 | (d-1)*10**f < exp(c*10**e) < (d+1)*10**f |
| 5727 | |
| 5728 | In other words, d*10**f is an approximation to exp(c*10**e) with p |
| 5729 | digits of precision, and with an error in d of at most 1. This is |
| 5730 | almost, but not quite, the same as the error being < 1ulp: when d |
| 5731 | = 10**(p-1) the error could be up to 10 ulp.""" |
| 5732 | |
| 5733 | # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision |
| 5734 | p += 2 |
| 5735 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5736 | # compute log(10) with extra precision = adjusted exponent of c*10**e |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5737 | extra = max(0, e + len(str(c)) - 1) |
| 5738 | q = p + extra |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5739 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5740 | # 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] | 5741 | # rounding down |
| 5742 | shift = e+q |
| 5743 | if shift >= 0: |
| 5744 | cshift = c*10**shift |
| 5745 | else: |
| 5746 | cshift = c//10**-shift |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5747 | quot, rem = divmod(cshift, _log10_digits(q)) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5748 | |
| 5749 | # reduce remainder back to original precision |
| 5750 | rem = _div_nearest(rem, 10**extra) |
| 5751 | |
| 5752 | # error in result of _iexp < 120; error after division < 0.62 |
| 5753 | return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3 |
| 5754 | |
| 5755 | def _dpower(xc, xe, yc, ye, p): |
| 5756 | """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and |
| 5757 | y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that: |
| 5758 | |
| 5759 | 10**(p-1) <= c <= 10**p, and |
| 5760 | (c-1)*10**e < x**y < (c+1)*10**e |
| 5761 | |
| 5762 | in other words, c*10**e is an approximation to x**y with p digits |
| 5763 | of precision, and with an error in c of at most 1. (This is |
| 5764 | almost, but not quite, the same as the error being < 1ulp: when c |
| 5765 | == 10**(p-1) we can only guarantee error < 10ulp.) |
| 5766 | |
| 5767 | We assume that: x is positive and not equal to 1, and y is nonzero. |
| 5768 | """ |
| 5769 | |
| 5770 | # Find b such that 10**(b-1) <= |y| <= 10**b |
| 5771 | b = len(str(abs(yc))) + ye |
| 5772 | |
| 5773 | # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point |
| 5774 | lxc = _dlog(xc, xe, p+b+1) |
| 5775 | |
| 5776 | # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1) |
| 5777 | shift = ye-b |
| 5778 | if shift >= 0: |
| 5779 | pc = lxc*yc*10**shift |
| 5780 | else: |
| 5781 | pc = _div_nearest(lxc*yc, 10**-shift) |
| 5782 | |
| 5783 | if pc == 0: |
| 5784 | # we prefer a result that isn't exactly 1; this makes it |
| 5785 | # easier to compute a correctly rounded result in __pow__ |
| 5786 | if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1: |
| 5787 | coeff, exp = 10**(p-1)+1, 1-p |
| 5788 | else: |
| 5789 | coeff, exp = 10**p-1, -p |
| 5790 | else: |
| 5791 | coeff, exp = _dexp(pc, -(p+1), p+1) |
| 5792 | coeff = _div_nearest(coeff, 10) |
| 5793 | exp += 1 |
| 5794 | |
| 5795 | return coeff, exp |
| 5796 | |
| 5797 | def _log10_lb(c, correction = { |
| 5798 | '1': 100, '2': 70, '3': 53, '4': 40, '5': 31, |
| 5799 | '6': 23, '7': 16, '8': 10, '9': 5}): |
| 5800 | """Compute a lower bound for 100*log10(c) for a positive integer c.""" |
| 5801 | if c <= 0: |
| 5802 | raise ValueError("The argument to _log10_lb should be nonnegative.") |
| 5803 | str_c = str(c) |
| 5804 | return 100*len(str_c) - correction[str_c[0]] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5805 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 5806 | ##### Helper Functions #################################################### |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5807 | |
Mark Dickinson | ac256ab | 2010-04-03 11:08:14 +0000 | [diff] [blame] | 5808 | def _convert_other(other, raiseit=False, allow_float=False): |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5809 | """Convert other to Decimal. |
| 5810 | |
| 5811 | Verifies that it's ok to use in an implicit construction. |
Mark Dickinson | ac256ab | 2010-04-03 11:08:14 +0000 | [diff] [blame] | 5812 | If allow_float is true, allow conversion from float; this |
| 5813 | is used in the comparison methods (__eq__ and friends). |
| 5814 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5815 | """ |
| 5816 | if isinstance(other, Decimal): |
| 5817 | return other |
Walter Dörwald | aa97f04 | 2007-05-03 21:05:51 +0000 | [diff] [blame] | 5818 | if isinstance(other, int): |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5819 | return Decimal(other) |
Mark Dickinson | ac256ab | 2010-04-03 11:08:14 +0000 | [diff] [blame] | 5820 | if allow_float and isinstance(other, float): |
| 5821 | return Decimal.from_float(other) |
| 5822 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5823 | if raiseit: |
| 5824 | raise TypeError("Unable to convert %s to Decimal" % other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 5825 | return NotImplemented |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5826 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 5827 | ##### Setup Specific Contexts ############################################ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5828 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5829 | # The default context prototype used by Context() |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 5830 | # Is mutable, so that new contexts can have different default values |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5831 | |
| 5832 | DefaultContext = Context( |
Raymond Hettinger | 6ea4845 | 2004-07-03 12:26:21 +0000 | [diff] [blame] | 5833 | prec=28, rounding=ROUND_HALF_EVEN, |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 5834 | traps=[DivisionByZero, Overflow, InvalidOperation], |
| 5835 | flags=[], |
Raymond Hettinger | 99148e7 | 2004-07-14 19:56:56 +0000 | [diff] [blame] | 5836 | Emax=999999999, |
| 5837 | Emin=-999999999, |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 5838 | capitals=1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5839 | ) |
| 5840 | |
| 5841 | # Pre-made alternate contexts offered by the specification |
| 5842 | # Don't change these; the user should be able to select these |
| 5843 | # contexts and be able to reproduce results from other implementations |
| 5844 | # of the spec. |
| 5845 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5846 | BasicContext = Context( |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5847 | prec=9, rounding=ROUND_HALF_UP, |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 5848 | traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow], |
| 5849 | flags=[], |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5850 | ) |
| 5851 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5852 | ExtendedContext = Context( |
Raymond Hettinger | 6ea4845 | 2004-07-03 12:26:21 +0000 | [diff] [blame] | 5853 | prec=9, rounding=ROUND_HALF_EVEN, |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 5854 | traps=[], |
| 5855 | flags=[], |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5856 | ) |
| 5857 | |
| 5858 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5859 | ##### crud for parsing strings ############################################# |
Christian Heimes | 23daade0 | 2008-02-25 12:39:23 +0000 | [diff] [blame] | 5860 | # |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5861 | # Regular expression used for parsing numeric strings. Additional |
| 5862 | # comments: |
| 5863 | # |
| 5864 | # 1. Uncomment the two '\s*' lines to allow leading and/or trailing |
| 5865 | # whitespace. But note that the specification disallows whitespace in |
| 5866 | # a numeric string. |
| 5867 | # |
| 5868 | # 2. For finite numbers (not infinities and NaNs) the body of the |
| 5869 | # number between the optional sign and the optional exponent must have |
| 5870 | # at least one decimal digit, possibly after the decimal point. The |
Mark Dickinson | 345adc4 | 2009-08-02 10:14:23 +0000 | [diff] [blame] | 5871 | # lookahead expression '(?=\d|\.\d)' checks this. |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5872 | |
| 5873 | import re |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 5874 | _parser = re.compile(r""" # A numeric string consists of: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5875 | # \s* |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 5876 | (?P<sign>[-+])? # an optional sign, followed by either... |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5877 | ( |
Mark Dickinson | 345adc4 | 2009-08-02 10:14:23 +0000 | [diff] [blame] | 5878 | (?=\d|\.\d) # ...a number (with at least one digit) |
| 5879 | (?P<int>\d*) # having a (possibly empty) integer part |
| 5880 | (\.(?P<frac>\d*))? # followed by an optional fractional part |
| 5881 | (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or... |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5882 | | |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 5883 | Inf(inity)? # ...an infinity, or... |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5884 | | |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 5885 | (?P<signal>s)? # ...an (optionally signaling) |
| 5886 | NaN # NaN |
Mark Dickinson | 345adc4 | 2009-08-02 10:14:23 +0000 | [diff] [blame] | 5887 | (?P<diag>\d*) # with (possibly empty) diagnostic info. |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5888 | ) |
| 5889 | # \s* |
Christian Heimes | a62da1d | 2008-01-12 19:39:10 +0000 | [diff] [blame] | 5890 | \Z |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5891 | """, re.VERBOSE | re.IGNORECASE).match |
| 5892 | |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 5893 | _all_zeros = re.compile('0*$').match |
| 5894 | _exact_half = re.compile('50*$').match |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 5895 | |
| 5896 | ##### PEP3101 support functions ############################################## |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 5897 | # The functions in this section have little to do with the Decimal |
| 5898 | # class, and could potentially be reused or adapted for other pure |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 5899 | # Python numeric classes that want to implement __format__ |
| 5900 | # |
| 5901 | # A format specifier for Decimal looks like: |
| 5902 | # |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 5903 | # [[fill]align][sign][0][minimumwidth][,][.precision][type] |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 5904 | |
| 5905 | _parse_format_specifier_regex = re.compile(r"""\A |
| 5906 | (?: |
| 5907 | (?P<fill>.)? |
| 5908 | (?P<align>[<>=^]) |
| 5909 | )? |
| 5910 | (?P<sign>[-+ ])? |
| 5911 | (?P<zeropad>0)? |
| 5912 | (?P<minimumwidth>(?!0)\d+)? |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 5913 | (?P<thousands_sep>,)? |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 5914 | (?:\.(?P<precision>0|(?!0)\d+))? |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 5915 | (?P<type>[eEfFgGn%])? |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 5916 | \Z |
| 5917 | """, re.VERBOSE) |
| 5918 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5919 | del re |
| 5920 | |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 5921 | # The locale module is only needed for the 'n' format specifier. The |
| 5922 | # rest of the PEP 3101 code functions quite happily without it, so we |
| 5923 | # don't care too much if locale isn't present. |
| 5924 | try: |
| 5925 | import locale as _locale |
| 5926 | except ImportError: |
| 5927 | pass |
| 5928 | |
| 5929 | def _parse_format_specifier(format_spec, _localeconv=None): |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 5930 | """Parse and validate a format specifier. |
| 5931 | |
| 5932 | Turns a standard numeric format specifier into a dict, with the |
| 5933 | following entries: |
| 5934 | |
| 5935 | fill: fill character to pad field to minimum width |
| 5936 | align: alignment type, either '<', '>', '=' or '^' |
| 5937 | sign: either '+', '-' or ' ' |
| 5938 | minimumwidth: nonnegative integer giving minimum width |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 5939 | zeropad: boolean, indicating whether to pad with zeros |
| 5940 | thousands_sep: string to use as thousands separator, or '' |
| 5941 | grouping: grouping for thousands separators, in format |
| 5942 | used by localeconv |
| 5943 | decimal_point: string to use for decimal point |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 5944 | precision: nonnegative integer giving precision, or None |
| 5945 | type: one of the characters 'eEfFgG%', or None |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 5946 | |
| 5947 | """ |
| 5948 | m = _parse_format_specifier_regex.match(format_spec) |
| 5949 | if m is None: |
| 5950 | raise ValueError("Invalid format specifier: " + format_spec) |
| 5951 | |
| 5952 | # get the dictionary |
| 5953 | format_dict = m.groupdict() |
| 5954 | |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 5955 | # zeropad; defaults for fill and alignment. If zero padding |
| 5956 | # is requested, the fill and align fields should be absent. |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 5957 | fill = format_dict['fill'] |
| 5958 | align = format_dict['align'] |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 5959 | format_dict['zeropad'] = (format_dict['zeropad'] is not None) |
| 5960 | if format_dict['zeropad']: |
| 5961 | if fill is not None: |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 5962 | raise ValueError("Fill character conflicts with '0'" |
| 5963 | " in format specifier: " + format_spec) |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 5964 | if align is not None: |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 5965 | raise ValueError("Alignment conflicts with '0' in " |
| 5966 | "format specifier: " + format_spec) |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 5967 | format_dict['fill'] = fill or ' ' |
Mark Dickinson | 46ab5d0 | 2009-09-08 20:22:46 +0000 | [diff] [blame] | 5968 | # PEP 3101 originally specified that the default alignment should |
| 5969 | # be left; it was later agreed that right-aligned makes more sense |
| 5970 | # for numeric types. See http://bugs.python.org/issue6857. |
| 5971 | format_dict['align'] = align or '>' |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 5972 | |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 5973 | # default sign handling: '-' for negative, '' for positive |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 5974 | if format_dict['sign'] is None: |
| 5975 | format_dict['sign'] = '-' |
| 5976 | |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 5977 | # minimumwidth defaults to 0; precision remains None if not given |
| 5978 | format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0') |
| 5979 | if format_dict['precision'] is not None: |
| 5980 | format_dict['precision'] = int(format_dict['precision']) |
| 5981 | |
| 5982 | # if format type is 'g' or 'G' then a precision of 0 makes little |
| 5983 | # sense; convert it to 1. Same if format type is unspecified. |
| 5984 | if format_dict['precision'] == 0: |
Mark Dickinson | 7718d2b | 2009-09-07 16:21:56 +0000 | [diff] [blame] | 5985 | if format_dict['type'] is None or format_dict['type'] in 'gG': |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 5986 | format_dict['precision'] = 1 |
| 5987 | |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 5988 | # determine thousands separator, grouping, and decimal separator, and |
| 5989 | # add appropriate entries to format_dict |
| 5990 | if format_dict['type'] == 'n': |
| 5991 | # apart from separators, 'n' behaves just like 'g' |
| 5992 | format_dict['type'] = 'g' |
| 5993 | if _localeconv is None: |
| 5994 | _localeconv = _locale.localeconv() |
| 5995 | if format_dict['thousands_sep'] is not None: |
| 5996 | raise ValueError("Explicit thousands separator conflicts with " |
| 5997 | "'n' type in format specifier: " + format_spec) |
| 5998 | format_dict['thousands_sep'] = _localeconv['thousands_sep'] |
| 5999 | format_dict['grouping'] = _localeconv['grouping'] |
| 6000 | format_dict['decimal_point'] = _localeconv['decimal_point'] |
| 6001 | else: |
| 6002 | if format_dict['thousands_sep'] is None: |
| 6003 | format_dict['thousands_sep'] = '' |
| 6004 | format_dict['grouping'] = [3, 0] |
| 6005 | format_dict['decimal_point'] = '.' |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6006 | |
| 6007 | return format_dict |
| 6008 | |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 6009 | def _format_align(sign, body, spec): |
| 6010 | """Given an unpadded, non-aligned numeric string 'body' and sign |
| 6011 | string 'sign', add padding and aligment conforming to the given |
| 6012 | format specifier dictionary 'spec' (as produced by |
| 6013 | parse_format_specifier). |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6014 | |
| 6015 | """ |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6016 | # how much extra space do we have to play with? |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 6017 | minimumwidth = spec['minimumwidth'] |
| 6018 | fill = spec['fill'] |
| 6019 | padding = fill*(minimumwidth - len(sign) - len(body)) |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6020 | |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 6021 | align = spec['align'] |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6022 | if align == '<': |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6023 | result = sign + body + padding |
Mark Dickinson | ad41634 | 2009-03-17 18:10:15 +0000 | [diff] [blame] | 6024 | elif align == '>': |
| 6025 | result = padding + sign + body |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6026 | elif align == '=': |
| 6027 | result = sign + padding + body |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 6028 | elif align == '^': |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6029 | half = len(padding)//2 |
| 6030 | result = padding[:half] + sign + body + padding[half:] |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 6031 | else: |
| 6032 | raise ValueError('Unrecognised alignment field') |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6033 | |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6034 | return result |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 6035 | |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 6036 | def _group_lengths(grouping): |
| 6037 | """Convert a localeconv-style grouping into a (possibly infinite) |
| 6038 | iterable of integers representing group lengths. |
| 6039 | |
| 6040 | """ |
| 6041 | # The result from localeconv()['grouping'], and the input to this |
| 6042 | # function, should be a list of integers in one of the |
| 6043 | # following three forms: |
| 6044 | # |
| 6045 | # (1) an empty list, or |
| 6046 | # (2) nonempty list of positive integers + [0] |
| 6047 | # (3) list of positive integers + [locale.CHAR_MAX], or |
| 6048 | |
| 6049 | from itertools import chain, repeat |
| 6050 | if not grouping: |
| 6051 | return [] |
| 6052 | elif grouping[-1] == 0 and len(grouping) >= 2: |
| 6053 | return chain(grouping[:-1], repeat(grouping[-2])) |
| 6054 | elif grouping[-1] == _locale.CHAR_MAX: |
| 6055 | return grouping[:-1] |
| 6056 | else: |
| 6057 | raise ValueError('unrecognised format for grouping') |
| 6058 | |
| 6059 | def _insert_thousands_sep(digits, spec, min_width=1): |
| 6060 | """Insert thousands separators into a digit string. |
| 6061 | |
| 6062 | spec is a dictionary whose keys should include 'thousands_sep' and |
| 6063 | 'grouping'; typically it's the result of parsing the format |
| 6064 | specifier using _parse_format_specifier. |
| 6065 | |
| 6066 | The min_width keyword argument gives the minimum length of the |
| 6067 | result, which will be padded on the left with zeros if necessary. |
| 6068 | |
| 6069 | If necessary, the zero padding adds an extra '0' on the left to |
| 6070 | avoid a leading thousands separator. For example, inserting |
| 6071 | commas every three digits in '123456', with min_width=8, gives |
| 6072 | '0,123,456', even though that has length 9. |
| 6073 | |
| 6074 | """ |
| 6075 | |
| 6076 | sep = spec['thousands_sep'] |
| 6077 | grouping = spec['grouping'] |
| 6078 | |
| 6079 | groups = [] |
| 6080 | for l in _group_lengths(grouping): |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 6081 | if l <= 0: |
| 6082 | raise ValueError("group length should be positive") |
| 6083 | # max(..., 1) forces at least 1 digit to the left of a separator |
| 6084 | l = min(max(len(digits), min_width, 1), l) |
| 6085 | groups.append('0'*(l - len(digits)) + digits[-l:]) |
| 6086 | digits = digits[:-l] |
| 6087 | min_width -= l |
| 6088 | if not digits and min_width <= 0: |
| 6089 | break |
Mark Dickinson | 7303b59 | 2009-03-18 08:25:36 +0000 | [diff] [blame] | 6090 | min_width -= len(sep) |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 6091 | else: |
| 6092 | l = max(len(digits), min_width, 1) |
| 6093 | groups.append('0'*(l - len(digits)) + digits[-l:]) |
| 6094 | return sep.join(reversed(groups)) |
| 6095 | |
| 6096 | def _format_sign(is_negative, spec): |
| 6097 | """Determine sign character.""" |
| 6098 | |
| 6099 | if is_negative: |
| 6100 | return '-' |
| 6101 | elif spec['sign'] in ' +': |
| 6102 | return spec['sign'] |
| 6103 | else: |
| 6104 | return '' |
| 6105 | |
| 6106 | def _format_number(is_negative, intpart, fracpart, exp, spec): |
| 6107 | """Format a number, given the following data: |
| 6108 | |
| 6109 | is_negative: true if the number is negative, else false |
| 6110 | intpart: string of digits that must appear before the decimal point |
| 6111 | fracpart: string of digits that must come after the point |
| 6112 | exp: exponent, as an integer |
| 6113 | spec: dictionary resulting from parsing the format specifier |
| 6114 | |
| 6115 | This function uses the information in spec to: |
| 6116 | insert separators (decimal separator and thousands separators) |
| 6117 | format the sign |
| 6118 | format the exponent |
| 6119 | add trailing '%' for the '%' type |
| 6120 | zero-pad if necessary |
| 6121 | fill and align if necessary |
| 6122 | """ |
| 6123 | |
| 6124 | sign = _format_sign(is_negative, spec) |
| 6125 | |
| 6126 | if fracpart: |
| 6127 | fracpart = spec['decimal_point'] + fracpart |
| 6128 | |
| 6129 | if exp != 0 or spec['type'] in 'eE': |
| 6130 | echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']] |
| 6131 | fracpart += "{0}{1:+}".format(echar, exp) |
| 6132 | if spec['type'] == '%': |
| 6133 | fracpart += '%' |
| 6134 | |
| 6135 | if spec['zeropad']: |
| 6136 | min_width = spec['minimumwidth'] - len(fracpart) - len(sign) |
| 6137 | else: |
| 6138 | min_width = 0 |
| 6139 | intpart = _insert_thousands_sep(intpart, spec, min_width) |
| 6140 | |
| 6141 | return _format_align(sign, intpart+fracpart, spec) |
| 6142 | |
| 6143 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 6144 | ##### Useful Constants (internal use only) ################################ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 6145 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 6146 | # Reusable defaults |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 6147 | _Infinity = Decimal('Inf') |
| 6148 | _NegativeInfinity = Decimal('-Inf') |
Mark Dickinson | f923641 | 2009-01-02 23:23:21 +0000 | [diff] [blame] | 6149 | _NaN = Decimal('NaN') |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 6150 | _Zero = Decimal(0) |
| 6151 | _One = Decimal(1) |
| 6152 | _NegativeOne = Decimal(-1) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 6153 | |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 6154 | # _SignedInfinity[sign] is infinity w/ that sign |
| 6155 | _SignedInfinity = (_Infinity, _NegativeInfinity) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 6156 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 6157 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 6158 | |
| 6159 | if __name__ == '__main__': |
| 6160 | import doctest, sys |
| 6161 | doctest.testmod(sys.modules[__name__]) |