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 | |
Senthil Kumaran | 4fec47e | 2013-09-07 23:19:29 -0700 | [diff] [blame] | 24 | http://en.wikipedia.org/wiki/IEEE_854-1987 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 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 |
Mark Dickinson | aa63c4d | 2010-06-12 16:37:53 +0000 | [diff] [blame] | 34 | of 0.0; Decimal('1.00') % Decimal('0.1') returns the expected |
| 35 | Decimal('0.00')). |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 36 | |
| 37 | Here are some examples of using the decimal module: |
| 38 | |
| 39 | >>> from decimal import * |
Raymond Hettinger | bd7f76d | 2004-07-08 00:49:18 +0000 | [diff] [blame] | 40 | >>> setcontext(ExtendedContext) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 41 | >>> Decimal(0) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 42 | Decimal('0') |
| 43 | >>> Decimal('1') |
| 44 | Decimal('1') |
| 45 | >>> Decimal('-.0123') |
| 46 | Decimal('-0.0123') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 47 | >>> Decimal(123456) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 48 | Decimal('123456') |
Stefan Krah | 1919b7e | 2012-03-21 18:25:23 +0100 | [diff] [blame] | 49 | >>> Decimal('123.45e12345678') |
| 50 | Decimal('1.2345E+12345680') |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 51 | >>> Decimal('1.33') + Decimal('1.27') |
| 52 | Decimal('2.60') |
| 53 | >>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41') |
| 54 | Decimal('-2.20') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 55 | >>> dig = Decimal(1) |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 56 | >>> print(dig / Decimal(3)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 57 | 0.333333333 |
| 58 | >>> getcontext().prec = 18 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 59 | >>> print(dig / Decimal(3)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 60 | 0.333333333333333333 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 61 | >>> print(dig.sqrt()) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 62 | 1 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 63 | >>> print(Decimal(3).sqrt()) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 64 | 1.73205080756887729 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 65 | >>> print(Decimal(3) ** 123) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 66 | 4.85192780976896427E+58 |
| 67 | >>> inf = Decimal(1) / Decimal(0) |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 68 | >>> print(inf) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 69 | Infinity |
| 70 | >>> neginf = Decimal(-1) / Decimal(0) |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 71 | >>> print(neginf) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 72 | -Infinity |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 73 | >>> print(neginf + inf) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 74 | NaN |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 75 | >>> print(neginf * inf) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 76 | -Infinity |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 77 | >>> print(dig / 0) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 78 | Infinity |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 79 | >>> getcontext().traps[DivisionByZero] = 1 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 80 | >>> print(dig / 0) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 81 | Traceback (most recent call last): |
| 82 | ... |
| 83 | ... |
| 84 | ... |
Guido van Rossum | 6a2a2a0 | 2006-08-26 20:37:44 +0000 | [diff] [blame] | 85 | decimal.DivisionByZero: x / 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 86 | >>> c = Context() |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 87 | >>> c.traps[InvalidOperation] = 0 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 88 | >>> print(c.flags[InvalidOperation]) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 89 | 0 |
| 90 | >>> c.divide(Decimal(0), Decimal(0)) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 91 | Decimal('NaN') |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 92 | >>> c.traps[InvalidOperation] = 1 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 93 | >>> print(c.flags[InvalidOperation]) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 94 | 1 |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 95 | >>> c.flags[InvalidOperation] = 0 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 96 | >>> print(c.flags[InvalidOperation]) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 97 | 0 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 98 | >>> print(c.divide(Decimal(0), Decimal(0))) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 99 | Traceback (most recent call last): |
| 100 | ... |
| 101 | ... |
| 102 | ... |
Guido van Rossum | 6a2a2a0 | 2006-08-26 20:37:44 +0000 | [diff] [blame] | 103 | decimal.InvalidOperation: 0 / 0 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 104 | >>> print(c.flags[InvalidOperation]) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 105 | 1 |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 106 | >>> c.flags[InvalidOperation] = 0 |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 107 | >>> c.traps[InvalidOperation] = 0 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 108 | >>> print(c.divide(Decimal(0), Decimal(0))) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 109 | NaN |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 110 | >>> print(c.flags[InvalidOperation]) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 111 | 1 |
| 112 | >>> |
| 113 | """ |
| 114 | |
| 115 | __all__ = [ |
| 116 | # Two major classes |
| 117 | 'Decimal', 'Context', |
| 118 | |
Stefan Krah | 964feab | 2014-09-09 19:56:56 +0200 | [diff] [blame] | 119 | # Named tuple representation |
| 120 | 'DecimalTuple', |
| 121 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 122 | # Contexts |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 123 | 'DefaultContext', 'BasicContext', 'ExtendedContext', |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 124 | |
| 125 | # Exceptions |
Raymond Hettinger | d87ac8f | 2004-07-09 10:52:54 +0000 | [diff] [blame] | 126 | 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero', |
| 127 | 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow', |
Stefan Krah | 1919b7e | 2012-03-21 18:25:23 +0100 | [diff] [blame] | 128 | 'FloatOperation', |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 129 | |
Stefan Krah | 964feab | 2014-09-09 19:56:56 +0200 | [diff] [blame] | 130 | # Exceptional conditions that trigger InvalidOperation |
| 131 | 'DivisionImpossible', 'InvalidContext', 'ConversionSyntax', 'DivisionUndefined', |
| 132 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 133 | # Constants for use in setting up contexts |
| 134 | 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING', |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 135 | 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP', |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 136 | |
| 137 | # Functions for manipulating contexts |
Stefan Krah | 1919b7e | 2012-03-21 18:25:23 +0100 | [diff] [blame] | 138 | 'setcontext', 'getcontext', 'localcontext', |
| 139 | |
| 140 | # Limits for the C version for compatibility |
| 141 | 'MAX_PREC', 'MAX_EMAX', 'MIN_EMIN', 'MIN_ETINY', |
| 142 | |
| 143 | # C version: compile time choice that enables the thread local context |
| 144 | 'HAVE_THREADS' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 145 | ] |
| 146 | |
Raymond Hettinger | 960dc36 | 2009-04-21 03:43:15 +0000 | [diff] [blame] | 147 | __version__ = '1.70' # Highest version of the spec this complies with |
Raymond Hettinger | 697ce95 | 2010-11-30 20:32:59 +0000 | [diff] [blame] | 148 | # See http://speleotrove.com/decimal/ |
Stefan Krah | cf26115 | 2014-08-26 21:31:47 +0200 | [diff] [blame] | 149 | __libmpdec_version__ = "2.4.1" # compatible libmpdec version |
Raymond Hettinger | 960dc36 | 2009-04-21 03:43:15 +0000 | [diff] [blame] | 150 | |
Raymond Hettinger | 771ed76 | 2009-01-03 19:20:32 +0000 | [diff] [blame] | 151 | import math as _math |
Raymond Hettinger | 82417ca | 2009-02-03 03:54:28 +0000 | [diff] [blame] | 152 | import numbers as _numbers |
Stefan Krah | 1919b7e | 2012-03-21 18:25:23 +0100 | [diff] [blame] | 153 | import sys |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 154 | |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 155 | try: |
| 156 | from collections import namedtuple as _namedtuple |
| 157 | DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent') |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 158 | except ImportError: |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 159 | DecimalTuple = lambda *args: args |
| 160 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 161 | # Rounding |
Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 162 | ROUND_DOWN = 'ROUND_DOWN' |
| 163 | ROUND_HALF_UP = 'ROUND_HALF_UP' |
| 164 | ROUND_HALF_EVEN = 'ROUND_HALF_EVEN' |
| 165 | ROUND_CEILING = 'ROUND_CEILING' |
| 166 | ROUND_FLOOR = 'ROUND_FLOOR' |
| 167 | ROUND_UP = 'ROUND_UP' |
| 168 | ROUND_HALF_DOWN = 'ROUND_HALF_DOWN' |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 169 | ROUND_05UP = 'ROUND_05UP' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 170 | |
Stefan Krah | 1919b7e | 2012-03-21 18:25:23 +0100 | [diff] [blame] | 171 | # Compatibility with the C version |
| 172 | HAVE_THREADS = True |
| 173 | if sys.maxsize == 2**63-1: |
| 174 | MAX_PREC = 999999999999999999 |
| 175 | MAX_EMAX = 999999999999999999 |
| 176 | MIN_EMIN = -999999999999999999 |
| 177 | else: |
| 178 | MAX_PREC = 425000000 |
| 179 | MAX_EMAX = 425000000 |
| 180 | MIN_EMIN = -425000000 |
| 181 | |
| 182 | MIN_ETINY = MIN_EMIN - (MAX_PREC-1) |
| 183 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 184 | # Errors |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 185 | |
| 186 | class DecimalException(ArithmeticError): |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 187 | """Base exception class. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 188 | |
| 189 | Used exceptions derive from this. |
| 190 | If an exception derives from another exception besides this (such as |
| 191 | Underflow (Inexact, Rounded, Subnormal) that indicates that it is only |
| 192 | called if the others are present. This isn't actually used for |
| 193 | anything, though. |
| 194 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 195 | handle -- Called when context._raise_error is called and the |
Stefan Krah | 2eb4a07 | 2010-05-19 15:52:31 +0000 | [diff] [blame] | 196 | trap_enabler is not set. First argument is self, second is the |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 197 | context. More arguments can be given, those being after |
| 198 | the explanation in _raise_error (For example, |
| 199 | context._raise_error(NewError, '(-x)!', self._sign) would |
| 200 | call NewError().handle(context, self._sign).) |
| 201 | |
| 202 | To define a new exception, it should be sufficient to have it derive |
| 203 | from DecimalException. |
| 204 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 205 | def handle(self, context, *args): |
| 206 | pass |
| 207 | |
| 208 | |
| 209 | class Clamped(DecimalException): |
| 210 | """Exponent of a 0 changed to fit bounds. |
| 211 | |
| 212 | This occurs and signals clamped if the exponent of a result has been |
| 213 | altered in order to fit the constraints of a specific concrete |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 214 | representation. This may occur when the exponent of a zero result would |
| 215 | be outside the bounds of a representation, or when a large normal |
| 216 | number would have an encoded exponent that cannot be represented. In |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 217 | this latter case, the exponent is reduced to fit and the corresponding |
| 218 | number of zero digits are appended to the coefficient ("fold-down"). |
| 219 | """ |
| 220 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 221 | class InvalidOperation(DecimalException): |
| 222 | """An invalid operation was performed. |
| 223 | |
| 224 | Various bad things cause this: |
| 225 | |
| 226 | Something creates a signaling NaN |
| 227 | -INF + INF |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 228 | 0 * (+-)INF |
| 229 | (+-)INF / (+-)INF |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 230 | x % 0 |
| 231 | (+-)INF % x |
| 232 | x._rescale( non-integer ) |
| 233 | sqrt(-x) , x > 0 |
| 234 | 0 ** 0 |
| 235 | x ** (non-integer) |
| 236 | x ** (+-)INF |
| 237 | An operand is invalid |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 238 | |
| 239 | The result of the operation after these is a quiet positive NaN, |
| 240 | except when the cause is a signaling NaN, in which case the result is |
| 241 | also a quiet NaN, but with the original sign, and an optional |
| 242 | diagnostic information. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 243 | """ |
| 244 | def handle(self, context, *args): |
| 245 | if args: |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 246 | ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True) |
| 247 | return ans._fix_nan(context) |
Mark Dickinson | f923641 | 2009-01-02 23:23:21 +0000 | [diff] [blame] | 248 | return _NaN |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 249 | |
| 250 | class ConversionSyntax(InvalidOperation): |
| 251 | """Trying to convert badly formed string. |
| 252 | |
| 253 | This occurs and signals invalid-operation if an string is being |
| 254 | 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] | 255 | syntax. The result is [0,qNaN]. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 256 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 257 | def handle(self, context, *args): |
Mark Dickinson | f923641 | 2009-01-02 23:23:21 +0000 | [diff] [blame] | 258 | return _NaN |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 259 | |
| 260 | class DivisionByZero(DecimalException, ZeroDivisionError): |
| 261 | """Division by 0. |
| 262 | |
| 263 | This occurs and signals division-by-zero if division of a finite number |
| 264 | by zero was attempted (during a divide-integer or divide operation, or a |
| 265 | power operation with negative right-hand operand), and the dividend was |
| 266 | not zero. |
| 267 | |
| 268 | The result of the operation is [sign,inf], where sign is the exclusive |
| 269 | or of the signs of the operands for divide, or is 1 for an odd power of |
| 270 | -0, for power. |
| 271 | """ |
| 272 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 273 | def handle(self, context, sign, *args): |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 274 | return _SignedInfinity[sign] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 275 | |
| 276 | class DivisionImpossible(InvalidOperation): |
| 277 | """Cannot perform the division adequately. |
| 278 | |
| 279 | This occurs and signals invalid-operation if the integer result of a |
| 280 | divide-integer or remainder operation had too many digits (would be |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 281 | longer than precision). The result is [0,qNaN]. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 282 | """ |
| 283 | |
| 284 | def handle(self, context, *args): |
Mark Dickinson | f923641 | 2009-01-02 23:23:21 +0000 | [diff] [blame] | 285 | return _NaN |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 286 | |
| 287 | class DivisionUndefined(InvalidOperation, ZeroDivisionError): |
| 288 | """Undefined result of division. |
| 289 | |
| 290 | This occurs and signals invalid-operation if division by zero was |
| 291 | attempted (during a divide-integer, divide, or remainder operation), and |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 292 | the dividend is also zero. The result is [0,qNaN]. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 293 | """ |
| 294 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 295 | def handle(self, context, *args): |
Mark Dickinson | f923641 | 2009-01-02 23:23:21 +0000 | [diff] [blame] | 296 | return _NaN |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 297 | |
| 298 | class Inexact(DecimalException): |
| 299 | """Had to round, losing information. |
| 300 | |
| 301 | This occurs and signals inexact whenever the result of an operation is |
| 302 | 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] | 303 | were non-zero), or if an overflow or underflow condition occurs. The |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 304 | result in all cases is unchanged. |
| 305 | |
| 306 | The inexact signal may be tested (or trapped) to determine if a given |
| 307 | operation (or sequence of operations) was inexact. |
| 308 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 309 | |
| 310 | class InvalidContext(InvalidOperation): |
| 311 | """Invalid context. Unknown rounding, for example. |
| 312 | |
| 313 | This occurs and signals invalid-operation if an invalid context was |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 314 | detected during an operation. This can occur if contexts are not checked |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 315 | on creation and either the precision exceeds the capability of the |
| 316 | underlying concrete representation or an unknown or unsupported rounding |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 317 | was specified. These aspects of the context need only be checked when |
| 318 | the values are required to be used. The result is [0,qNaN]. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 319 | """ |
| 320 | |
| 321 | def handle(self, context, *args): |
Mark Dickinson | f923641 | 2009-01-02 23:23:21 +0000 | [diff] [blame] | 322 | return _NaN |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 323 | |
| 324 | class Rounded(DecimalException): |
| 325 | """Number got rounded (not necessarily changed during rounding). |
| 326 | |
| 327 | This occurs and signals rounded whenever the result of an operation is |
| 328 | 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] | 329 | coefficient), or if an overflow or underflow condition occurs. The |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 330 | result in all cases is unchanged. |
| 331 | |
| 332 | The rounded signal may be tested (or trapped) to determine if a given |
| 333 | operation (or sequence of operations) caused a loss of precision. |
| 334 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 335 | |
| 336 | class Subnormal(DecimalException): |
| 337 | """Exponent < Emin before rounding. |
| 338 | |
| 339 | This occurs and signals subnormal whenever the result of a conversion or |
| 340 | operation is subnormal (that is, its adjusted exponent is less than |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 341 | Emin, before any rounding). The result in all cases is unchanged. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 342 | |
| 343 | The subnormal signal may be tested (or trapped) to determine if a given |
| 344 | or operation (or sequence of operations) yielded a subnormal result. |
| 345 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 346 | |
| 347 | class Overflow(Inexact, Rounded): |
| 348 | """Numerical overflow. |
| 349 | |
| 350 | This occurs and signals overflow if the adjusted exponent of a result |
| 351 | (from a conversion or from an operation that is not an attempt to divide |
| 352 | by zero), after rounding, would be greater than the largest value that |
| 353 | can be handled by the implementation (the value Emax). |
| 354 | |
| 355 | The result depends on the rounding mode: |
| 356 | |
| 357 | For round-half-up and round-half-even (and for round-half-down and |
| 358 | 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] | 359 | 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] | 360 | 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] | 361 | current precision, with the sign of the intermediate result. For |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 362 | 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] | 363 | 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] | 364 | 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] | 365 | 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] | 366 | will also be raised. |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 367 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 368 | |
| 369 | def handle(self, context, sign, *args): |
| 370 | if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN, |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 371 | ROUND_HALF_DOWN, ROUND_UP): |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 372 | return _SignedInfinity[sign] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 373 | if sign == 0: |
| 374 | if context.rounding == ROUND_CEILING: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 375 | return _SignedInfinity[sign] |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 376 | return _dec_from_triple(sign, '9'*context.prec, |
| 377 | context.Emax-context.prec+1) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 378 | if sign == 1: |
| 379 | if context.rounding == ROUND_FLOOR: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 380 | return _SignedInfinity[sign] |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 381 | return _dec_from_triple(sign, '9'*context.prec, |
| 382 | context.Emax-context.prec+1) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 383 | |
| 384 | |
| 385 | class Underflow(Inexact, Rounded, Subnormal): |
| 386 | """Numerical underflow with result rounded to 0. |
| 387 | |
| 388 | This occurs and signals underflow if a result is inexact and the |
| 389 | adjusted exponent of the result would be smaller (more negative) than |
| 390 | 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] | 391 | Emin). That is, the result is both inexact and subnormal. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 392 | |
| 393 | 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] | 394 | 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] | 395 | in 0 with the sign of the intermediate result and an exponent of Etiny. |
| 396 | |
| 397 | In all cases, Inexact, Rounded, and Subnormal will also be raised. |
| 398 | """ |
| 399 | |
Stefan Krah | b6405ef | 2012-03-23 14:46:48 +0100 | [diff] [blame] | 400 | class FloatOperation(DecimalException, TypeError): |
Stefan Krah | 1919b7e | 2012-03-21 18:25:23 +0100 | [diff] [blame] | 401 | """Enable stricter semantics for mixing floats and Decimals. |
| 402 | |
| 403 | If the signal is not trapped (default), mixing floats and Decimals is |
| 404 | permitted in the Decimal() constructor, context.create_decimal() and |
| 405 | all comparison operators. Both conversion and comparisons are exact. |
| 406 | Any occurrence of a mixed operation is silently recorded by setting |
| 407 | FloatOperation in the context flags. Explicit conversions with |
| 408 | Decimal.from_float() or context.create_decimal_from_float() do not |
| 409 | set the flag. |
| 410 | |
| 411 | Otherwise (the signal is trapped), only equality comparisons and explicit |
| 412 | conversions are silent. All other mixed operations raise FloatOperation. |
| 413 | """ |
| 414 | |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 415 | # List of public traps and flags |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 416 | _signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded, |
Stefan Krah | 1919b7e | 2012-03-21 18:25:23 +0100 | [diff] [blame] | 417 | Underflow, InvalidOperation, Subnormal, FloatOperation] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 418 | |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 419 | # Map conditions (per the spec) to signals |
| 420 | _condition_map = {ConversionSyntax:InvalidOperation, |
| 421 | DivisionImpossible:InvalidOperation, |
| 422 | DivisionUndefined:InvalidOperation, |
| 423 | InvalidContext:InvalidOperation} |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 424 | |
Stefan Krah | 1919b7e | 2012-03-21 18:25:23 +0100 | [diff] [blame] | 425 | # Valid rounding modes |
| 426 | _rounding_modes = (ROUND_DOWN, ROUND_HALF_UP, ROUND_HALF_EVEN, ROUND_CEILING, |
| 427 | ROUND_FLOOR, ROUND_UP, ROUND_HALF_DOWN, ROUND_05UP) |
| 428 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 429 | ##### Context Functions ################################################## |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 430 | |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 431 | # The getcontext() and setcontext() function manage access to a thread-local |
| 432 | # current context. Py2.4 offers direct support for thread locals. If that |
Georg Brandl | f992640 | 2008-06-13 06:32:25 +0000 | [diff] [blame] | 433 | # is not available, use threading.current_thread() which is slower but will |
Raymond Hettinger | 7e71fa5 | 2004-12-18 19:07:19 +0000 | [diff] [blame] | 434 | # work for older Pythons. If threads are not part of the build, create a |
| 435 | # mock threading object with threading.local() returning the module namespace. |
| 436 | |
| 437 | try: |
| 438 | import threading |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 439 | except ImportError: |
Raymond Hettinger | 7e71fa5 | 2004-12-18 19:07:19 +0000 | [diff] [blame] | 440 | # Python was compiled without threads; create a mock object instead |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 441 | class MockThreading(object): |
Raymond Hettinger | 7e71fa5 | 2004-12-18 19:07:19 +0000 | [diff] [blame] | 442 | def local(self, sys=sys): |
| 443 | return sys.modules[__name__] |
| 444 | threading = MockThreading() |
Stefan Krah | 1919b7e | 2012-03-21 18:25:23 +0100 | [diff] [blame] | 445 | del MockThreading |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 446 | |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 447 | try: |
| 448 | threading.local |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 449 | |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 450 | except AttributeError: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 451 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 452 | # To fix reloading, force it to create a new context |
| 453 | # Old contexts have different exceptions in their dicts, making problems. |
Georg Brandl | f992640 | 2008-06-13 06:32:25 +0000 | [diff] [blame] | 454 | if hasattr(threading.current_thread(), '__decimal_context__'): |
| 455 | del threading.current_thread().__decimal_context__ |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 456 | |
| 457 | def setcontext(context): |
| 458 | """Set this thread's context to context.""" |
| 459 | if context in (DefaultContext, BasicContext, ExtendedContext): |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 460 | context = context.copy() |
Raymond Hettinger | 61992ef | 2004-08-06 23:42:16 +0000 | [diff] [blame] | 461 | context.clear_flags() |
Georg Brandl | f992640 | 2008-06-13 06:32:25 +0000 | [diff] [blame] | 462 | threading.current_thread().__decimal_context__ = context |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 463 | |
| 464 | def getcontext(): |
| 465 | """Returns this thread's context. |
| 466 | |
| 467 | If this thread does not yet have a context, returns |
| 468 | a new context and sets this thread's context. |
| 469 | New contexts are copies of DefaultContext. |
| 470 | """ |
| 471 | try: |
Georg Brandl | f992640 | 2008-06-13 06:32:25 +0000 | [diff] [blame] | 472 | return threading.current_thread().__decimal_context__ |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 473 | except AttributeError: |
| 474 | context = Context() |
Georg Brandl | f992640 | 2008-06-13 06:32:25 +0000 | [diff] [blame] | 475 | threading.current_thread().__decimal_context__ = context |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 476 | return context |
| 477 | |
| 478 | else: |
| 479 | |
| 480 | local = threading.local() |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 481 | if hasattr(local, '__decimal_context__'): |
| 482 | del local.__decimal_context__ |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 483 | |
| 484 | def getcontext(_local=local): |
| 485 | """Returns this thread's context. |
| 486 | |
| 487 | If this thread does not yet have a context, returns |
| 488 | a new context and sets this thread's context. |
| 489 | New contexts are copies of DefaultContext. |
| 490 | """ |
| 491 | try: |
| 492 | return _local.__decimal_context__ |
| 493 | except AttributeError: |
| 494 | context = Context() |
| 495 | _local.__decimal_context__ = context |
| 496 | return context |
| 497 | |
| 498 | def setcontext(context, _local=local): |
| 499 | """Set this thread's context to context.""" |
| 500 | if context in (DefaultContext, BasicContext, ExtendedContext): |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 501 | context = context.copy() |
Raymond Hettinger | 61992ef | 2004-08-06 23:42:16 +0000 | [diff] [blame] | 502 | context.clear_flags() |
Raymond Hettinger | ef66deb | 2004-07-14 21:04:27 +0000 | [diff] [blame] | 503 | _local.__decimal_context__ = context |
| 504 | |
| 505 | del threading, local # Don't contaminate the namespace |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 506 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 507 | def localcontext(ctx=None): |
| 508 | """Return a context manager for a copy of the supplied context |
| 509 | |
| 510 | Uses a copy of the current context if no context is specified |
| 511 | The returned context manager creates a local decimal context |
| 512 | in a with statement: |
| 513 | def sin(x): |
| 514 | with localcontext() as ctx: |
| 515 | ctx.prec += 2 |
| 516 | # Rest of sin calculation algorithm |
| 517 | # uses a precision 2 greater than normal |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 518 | return +s # Convert result to normal precision |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 519 | |
| 520 | def sin(x): |
| 521 | with localcontext(ExtendedContext): |
| 522 | # Rest of sin calculation algorithm |
| 523 | # uses the Extended Context from the |
| 524 | # General Decimal Arithmetic Specification |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 525 | return +s # Convert result to normal context |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 526 | |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 527 | >>> setcontext(DefaultContext) |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 528 | >>> print(getcontext().prec) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 529 | 28 |
| 530 | >>> with localcontext(): |
| 531 | ... ctx = getcontext() |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 532 | ... ctx.prec += 2 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 533 | ... print(ctx.prec) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 534 | ... |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 535 | 30 |
| 536 | >>> with localcontext(ExtendedContext): |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 537 | ... print(getcontext().prec) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 538 | ... |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 539 | 9 |
Guido van Rossum | 7131f84 | 2007-02-09 20:13:25 +0000 | [diff] [blame] | 540 | >>> print(getcontext().prec) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 541 | 28 |
| 542 | """ |
| 543 | if ctx is None: ctx = getcontext() |
| 544 | return _ContextManager(ctx) |
| 545 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 546 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 547 | ##### Decimal class ####################################################### |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 548 | |
Raymond Hettinger | a0fd888 | 2009-01-20 07:24:44 +0000 | [diff] [blame] | 549 | # Do not subclass Decimal from numbers.Real and do not register it as such |
| 550 | # (because Decimals are not interoperable with floats). See the notes in |
| 551 | # numbers.py for more detail. |
| 552 | |
| 553 | class Decimal(object): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 554 | """Floating point class for decimal arithmetic.""" |
| 555 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 556 | __slots__ = ('_exp','_int','_sign', '_is_special') |
| 557 | # Generally, the value of the Decimal instance is given by |
| 558 | # (-1)**_sign * _int * 10**_exp |
| 559 | # Special values are signified by _is_special == True |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 560 | |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 561 | # We're immutable, so use __new__ not __init__ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 562 | def __new__(cls, value="0", context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 563 | """Create a decimal point instance. |
| 564 | |
| 565 | >>> Decimal('3.14') # string input |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 566 | Decimal('3.14') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 567 | >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 568 | Decimal('3.14') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 569 | >>> Decimal(314) # int |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 570 | Decimal('314') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 571 | >>> Decimal(Decimal(314)) # another decimal instance |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 572 | Decimal('314') |
Christian Heimes | a62da1d | 2008-01-12 19:39:10 +0000 | [diff] [blame] | 573 | >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 574 | Decimal('3.14') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 575 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 576 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 577 | # Note that the coefficient, self._int, is actually stored as |
| 578 | # a string rather than as a tuple of digits. This speeds up |
| 579 | # the "digits to integer" and "integer to digits" conversions |
| 580 | # that are used in almost every arithmetic operation on |
| 581 | # Decimals. This is an internal detail: the as_tuple function |
| 582 | # and the Decimal constructor still deal with tuples of |
| 583 | # digits. |
| 584 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 585 | self = object.__new__(cls) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 586 | |
Christian Heimes | d59c64c | 2007-11-30 19:27:20 +0000 | [diff] [blame] | 587 | # From a string |
| 588 | # REs insist on real strings, so we can too. |
| 589 | if isinstance(value, str): |
Christian Heimes | a62da1d | 2008-01-12 19:39:10 +0000 | [diff] [blame] | 590 | m = _parser(value.strip()) |
Christian Heimes | d59c64c | 2007-11-30 19:27:20 +0000 | [diff] [blame] | 591 | if m is None: |
| 592 | if context is None: |
| 593 | context = getcontext() |
| 594 | return context._raise_error(ConversionSyntax, |
| 595 | "Invalid literal for Decimal: %r" % value) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 596 | |
Christian Heimes | d59c64c | 2007-11-30 19:27:20 +0000 | [diff] [blame] | 597 | if m.group('sign') == "-": |
| 598 | self._sign = 1 |
| 599 | else: |
| 600 | self._sign = 0 |
| 601 | intpart = m.group('int') |
| 602 | if intpart is not None: |
| 603 | # finite number |
Mark Dickinson | 345adc4 | 2009-08-02 10:14:23 +0000 | [diff] [blame] | 604 | fracpart = m.group('frac') or '' |
Christian Heimes | d59c64c | 2007-11-30 19:27:20 +0000 | [diff] [blame] | 605 | exp = int(m.group('exp') or '0') |
Mark Dickinson | 345adc4 | 2009-08-02 10:14:23 +0000 | [diff] [blame] | 606 | self._int = str(int(intpart+fracpart)) |
| 607 | self._exp = exp - len(fracpart) |
Christian Heimes | d59c64c | 2007-11-30 19:27:20 +0000 | [diff] [blame] | 608 | self._is_special = False |
| 609 | else: |
| 610 | diag = m.group('diag') |
| 611 | if diag is not None: |
| 612 | # NaN |
Mark Dickinson | 345adc4 | 2009-08-02 10:14:23 +0000 | [diff] [blame] | 613 | self._int = str(int(diag or '0')).lstrip('0') |
Christian Heimes | d59c64c | 2007-11-30 19:27:20 +0000 | [diff] [blame] | 614 | if m.group('signal'): |
| 615 | self._exp = 'N' |
| 616 | else: |
| 617 | self._exp = 'n' |
| 618 | else: |
| 619 | # infinity |
| 620 | self._int = '0' |
| 621 | self._exp = 'F' |
| 622 | self._is_special = True |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 623 | return self |
| 624 | |
| 625 | # From an integer |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 626 | if isinstance(value, int): |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 627 | if value >= 0: |
| 628 | self._sign = 0 |
| 629 | else: |
| 630 | self._sign = 1 |
| 631 | self._exp = 0 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 632 | self._int = str(abs(value)) |
Christian Heimes | d59c64c | 2007-11-30 19:27:20 +0000 | [diff] [blame] | 633 | self._is_special = False |
| 634 | return self |
| 635 | |
| 636 | # From another decimal |
| 637 | if isinstance(value, Decimal): |
| 638 | self._exp = value._exp |
| 639 | self._sign = value._sign |
| 640 | self._int = value._int |
| 641 | self._is_special = value._is_special |
| 642 | return self |
| 643 | |
| 644 | # From an internal working value |
| 645 | if isinstance(value, _WorkRep): |
| 646 | self._sign = value.sign |
| 647 | self._int = str(value.int) |
| 648 | self._exp = int(value.exp) |
| 649 | self._is_special = False |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 650 | return self |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 651 | |
| 652 | # tuple/list conversion (possibly from as_tuple()) |
| 653 | if isinstance(value, (list,tuple)): |
| 654 | if len(value) != 3: |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 655 | raise ValueError('Invalid tuple size in creation of Decimal ' |
| 656 | 'from list or tuple. The list or tuple ' |
| 657 | 'should have exactly three elements.') |
| 658 | # process sign. The isinstance test rejects floats |
| 659 | if not (isinstance(value[0], int) and value[0] in (0,1)): |
| 660 | raise ValueError("Invalid sign. The first value in the tuple " |
| 661 | "should be an integer; either 0 for a " |
| 662 | "positive number or 1 for a negative number.") |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 663 | self._sign = value[0] |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 664 | if value[2] == 'F': |
| 665 | # infinity: value[1] is ignored |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 666 | self._int = '0' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 667 | self._exp = value[2] |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 668 | self._is_special = True |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 669 | else: |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 670 | # process and validate the digits in value[1] |
| 671 | digits = [] |
| 672 | for digit in value[1]: |
| 673 | if isinstance(digit, int) and 0 <= digit <= 9: |
| 674 | # skip leading zeros |
| 675 | if digits or digit != 0: |
| 676 | digits.append(digit) |
| 677 | else: |
| 678 | raise ValueError("The second value in the tuple must " |
| 679 | "be composed of integers in the range " |
| 680 | "0 through 9.") |
| 681 | if value[2] in ('n', 'N'): |
| 682 | # NaN: digits form the diagnostic |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 683 | self._int = ''.join(map(str, digits)) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 684 | self._exp = value[2] |
| 685 | self._is_special = True |
| 686 | elif isinstance(value[2], int): |
| 687 | # finite number: digits give the coefficient |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 688 | self._int = ''.join(map(str, digits or [0])) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 689 | self._exp = value[2] |
| 690 | self._is_special = False |
| 691 | else: |
| 692 | raise ValueError("The third value in the tuple must " |
| 693 | "be an integer, or one of the " |
| 694 | "strings 'F', 'n', 'N'.") |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 695 | return self |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 696 | |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 697 | if isinstance(value, float): |
Stefan Krah | 1919b7e | 2012-03-21 18:25:23 +0100 | [diff] [blame] | 698 | if context is None: |
| 699 | context = getcontext() |
| 700 | context._raise_error(FloatOperation, |
| 701 | "strict semantics for mixing floats and Decimals are " |
| 702 | "enabled") |
Raymond Hettinger | 9679859 | 2010-04-02 16:58:27 +0000 | [diff] [blame] | 703 | value = Decimal.from_float(value) |
| 704 | self._exp = value._exp |
| 705 | self._sign = value._sign |
| 706 | self._int = value._int |
| 707 | self._is_special = value._is_special |
| 708 | return self |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 709 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 710 | raise TypeError("Cannot convert %r to Decimal" % value) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 711 | |
Mark Dickinson | 9c3f503 | 2012-10-31 17:53:27 +0000 | [diff] [blame] | 712 | @classmethod |
Raymond Hettinger | 771ed76 | 2009-01-03 19:20:32 +0000 | [diff] [blame] | 713 | def from_float(cls, f): |
| 714 | """Converts a float to a decimal number, exactly. |
| 715 | |
| 716 | Note that Decimal.from_float(0.1) is not the same as Decimal('0.1'). |
| 717 | Since 0.1 is not exactly representable in binary floating point, the |
| 718 | value is stored as the nearest representable value which is |
| 719 | 0x1.999999999999ap-4. The exact equivalent of the value in decimal |
| 720 | is 0.1000000000000000055511151231257827021181583404541015625. |
| 721 | |
| 722 | >>> Decimal.from_float(0.1) |
| 723 | Decimal('0.1000000000000000055511151231257827021181583404541015625') |
| 724 | >>> Decimal.from_float(float('nan')) |
| 725 | Decimal('NaN') |
| 726 | >>> Decimal.from_float(float('inf')) |
| 727 | Decimal('Infinity') |
| 728 | >>> Decimal.from_float(-float('inf')) |
| 729 | Decimal('-Infinity') |
| 730 | >>> Decimal.from_float(-0.0) |
| 731 | Decimal('-0') |
| 732 | |
| 733 | """ |
| 734 | if isinstance(f, int): # handle integer inputs |
| 735 | return cls(f) |
Stefan Krah | 1919b7e | 2012-03-21 18:25:23 +0100 | [diff] [blame] | 736 | if not isinstance(f, float): |
| 737 | raise TypeError("argument must be int or float.") |
| 738 | if _math.isinf(f) or _math.isnan(f): |
Raymond Hettinger | 771ed76 | 2009-01-03 19:20:32 +0000 | [diff] [blame] | 739 | return cls(repr(f)) |
Mark Dickinson | ba298e4 | 2009-01-04 21:17:43 +0000 | [diff] [blame] | 740 | if _math.copysign(1.0, f) == 1.0: |
| 741 | sign = 0 |
| 742 | else: |
| 743 | sign = 1 |
Raymond Hettinger | 771ed76 | 2009-01-03 19:20:32 +0000 | [diff] [blame] | 744 | n, d = abs(f).as_integer_ratio() |
| 745 | k = d.bit_length() - 1 |
| 746 | result = _dec_from_triple(sign, str(n*5**k), -k) |
Mark Dickinson | ba298e4 | 2009-01-04 21:17:43 +0000 | [diff] [blame] | 747 | if cls is Decimal: |
| 748 | return result |
| 749 | else: |
| 750 | return cls(result) |
Raymond Hettinger | 771ed76 | 2009-01-03 19:20:32 +0000 | [diff] [blame] | 751 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 752 | def _isnan(self): |
| 753 | """Returns whether the number is not actually one. |
| 754 | |
| 755 | 0 if a number |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 756 | 1 if NaN |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 757 | 2 if sNaN |
| 758 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 759 | if self._is_special: |
| 760 | exp = self._exp |
| 761 | if exp == 'n': |
| 762 | return 1 |
| 763 | elif exp == 'N': |
| 764 | return 2 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 765 | return 0 |
| 766 | |
| 767 | def _isinfinity(self): |
| 768 | """Returns whether the number is infinite |
| 769 | |
| 770 | 0 if finite or not a number |
| 771 | 1 if +INF |
| 772 | -1 if -INF |
| 773 | """ |
| 774 | if self._exp == 'F': |
| 775 | if self._sign: |
| 776 | return -1 |
| 777 | return 1 |
| 778 | return 0 |
| 779 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 780 | def _check_nans(self, other=None, context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 781 | """Returns whether the number is not actually one. |
| 782 | |
| 783 | if self, other are sNaN, signal |
| 784 | if self, other are NaN return nan |
| 785 | return 0 |
| 786 | |
| 787 | Done before operations. |
| 788 | """ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 789 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 790 | self_is_nan = self._isnan() |
| 791 | if other is None: |
| 792 | other_is_nan = False |
| 793 | else: |
| 794 | other_is_nan = other._isnan() |
| 795 | |
| 796 | if self_is_nan or other_is_nan: |
| 797 | if context is None: |
| 798 | context = getcontext() |
| 799 | |
| 800 | if self_is_nan == 2: |
| 801 | return context._raise_error(InvalidOperation, 'sNaN', |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 802 | self) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 803 | if other_is_nan == 2: |
| 804 | return context._raise_error(InvalidOperation, 'sNaN', |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 805 | other) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 806 | if self_is_nan: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 807 | return self._fix_nan(context) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 808 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 809 | return other._fix_nan(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 810 | return 0 |
| 811 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 812 | def _compare_check_nans(self, other, context): |
| 813 | """Version of _check_nans used for the signaling comparisons |
| 814 | compare_signal, __le__, __lt__, __ge__, __gt__. |
| 815 | |
| 816 | Signal InvalidOperation if either self or other is a (quiet |
| 817 | or signaling) NaN. Signaling NaNs take precedence over quiet |
| 818 | NaNs. |
| 819 | |
| 820 | Return 0 if neither operand is a NaN. |
| 821 | |
| 822 | """ |
| 823 | if context is None: |
| 824 | context = getcontext() |
| 825 | |
| 826 | if self._is_special or other._is_special: |
| 827 | if self.is_snan(): |
| 828 | return context._raise_error(InvalidOperation, |
| 829 | 'comparison involving sNaN', |
| 830 | self) |
| 831 | elif other.is_snan(): |
| 832 | return context._raise_error(InvalidOperation, |
| 833 | 'comparison involving sNaN', |
| 834 | other) |
| 835 | elif self.is_qnan(): |
| 836 | return context._raise_error(InvalidOperation, |
| 837 | 'comparison involving NaN', |
| 838 | self) |
| 839 | elif other.is_qnan(): |
| 840 | return context._raise_error(InvalidOperation, |
| 841 | 'comparison involving NaN', |
| 842 | other) |
| 843 | return 0 |
| 844 | |
Jack Diederich | 4dafcc4 | 2006-11-28 19:15:13 +0000 | [diff] [blame] | 845 | def __bool__(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 846 | """Return True if self is nonzero; otherwise return False. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 847 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 848 | NaNs and infinities are considered nonzero. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 849 | """ |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 850 | return self._is_special or self._int != '0' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 851 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 852 | def _cmp(self, other): |
| 853 | """Compare the two non-NaN decimal instances self and other. |
| 854 | |
| 855 | Returns -1 if self < other, 0 if self == other and 1 |
| 856 | if self > other. This routine is for internal use only.""" |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 857 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 858 | if self._is_special or other._is_special: |
Mark Dickinson | e6aad75 | 2009-01-25 10:48:51 +0000 | [diff] [blame] | 859 | self_inf = self._isinfinity() |
| 860 | other_inf = other._isinfinity() |
| 861 | if self_inf == other_inf: |
| 862 | return 0 |
| 863 | elif self_inf < other_inf: |
| 864 | return -1 |
| 865 | else: |
| 866 | return 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 867 | |
Mark Dickinson | e6aad75 | 2009-01-25 10:48:51 +0000 | [diff] [blame] | 868 | # check for zeros; Decimal('0') == Decimal('-0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 869 | if not self: |
| 870 | if not other: |
| 871 | return 0 |
| 872 | else: |
| 873 | return -((-1)**other._sign) |
| 874 | if not other: |
| 875 | return (-1)**self._sign |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 876 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 877 | # If different signs, neg one is less |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 878 | if other._sign < self._sign: |
| 879 | return -1 |
| 880 | if self._sign < other._sign: |
| 881 | return 1 |
| 882 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 883 | self_adjusted = self.adjusted() |
| 884 | other_adjusted = other.adjusted() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 885 | if self_adjusted == other_adjusted: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 886 | self_padded = self._int + '0'*(self._exp - other._exp) |
| 887 | other_padded = other._int + '0'*(other._exp - self._exp) |
Mark Dickinson | e6aad75 | 2009-01-25 10:48:51 +0000 | [diff] [blame] | 888 | if self_padded == other_padded: |
| 889 | return 0 |
| 890 | elif self_padded < other_padded: |
| 891 | return -(-1)**self._sign |
| 892 | else: |
| 893 | return (-1)**self._sign |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 894 | elif self_adjusted > other_adjusted: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 895 | return (-1)**self._sign |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 896 | else: # self_adjusted < other_adjusted |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 897 | return -((-1)**self._sign) |
| 898 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 899 | # Note: The Decimal standard doesn't cover rich comparisons for |
| 900 | # Decimals. In particular, the specification is silent on the |
| 901 | # subject of what should happen for a comparison involving a NaN. |
| 902 | # We take the following approach: |
| 903 | # |
Mark Dickinson | ac256ab | 2010-04-03 11:08:14 +0000 | [diff] [blame] | 904 | # == comparisons involving a quiet NaN always return False |
| 905 | # != comparisons involving a quiet NaN always return True |
| 906 | # == or != comparisons involving a signaling NaN signal |
| 907 | # InvalidOperation, and return False or True as above if the |
| 908 | # InvalidOperation is not trapped. |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 909 | # <, >, <= and >= comparisons involving a (quiet or signaling) |
| 910 | # NaN signal InvalidOperation, and return False if the |
Christian Heimes | 3feef61 | 2008-02-11 06:19:17 +0000 | [diff] [blame] | 911 | # InvalidOperation is not trapped. |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 912 | # |
| 913 | # This behavior is designed to conform as closely as possible to |
| 914 | # that specified by IEEE 754. |
| 915 | |
Mark Dickinson | ac256ab | 2010-04-03 11:08:14 +0000 | [diff] [blame] | 916 | def __eq__(self, other, context=None): |
Mark Dickinson | 08ade6f | 2010-06-11 10:44:52 +0000 | [diff] [blame] | 917 | self, other = _convert_for_comparison(self, other, equality_op=True) |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 918 | if other is NotImplemented: |
| 919 | return other |
Mark Dickinson | ac256ab | 2010-04-03 11:08:14 +0000 | [diff] [blame] | 920 | if self._check_nans(other, context): |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 921 | return False |
| 922 | return self._cmp(other) == 0 |
Raymond Hettinger | 0aeac10 | 2004-07-05 22:53:03 +0000 | [diff] [blame] | 923 | |
Mark Dickinson | ac256ab | 2010-04-03 11:08:14 +0000 | [diff] [blame] | 924 | def __ne__(self, other, context=None): |
Mark Dickinson | 08ade6f | 2010-06-11 10:44:52 +0000 | [diff] [blame] | 925 | self, other = _convert_for_comparison(self, other, equality_op=True) |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 926 | if other is NotImplemented: |
| 927 | return other |
Mark Dickinson | ac256ab | 2010-04-03 11:08:14 +0000 | [diff] [blame] | 928 | if self._check_nans(other, context): |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 929 | return True |
| 930 | return self._cmp(other) != 0 |
Raymond Hettinger | 0aeac10 | 2004-07-05 22:53:03 +0000 | [diff] [blame] | 931 | |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 932 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 933 | def __lt__(self, other, context=None): |
Mark Dickinson | 08ade6f | 2010-06-11 10:44:52 +0000 | [diff] [blame] | 934 | self, other = _convert_for_comparison(self, other) |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 935 | if other is NotImplemented: |
| 936 | return other |
| 937 | ans = self._compare_check_nans(other, context) |
| 938 | if ans: |
| 939 | return False |
| 940 | return self._cmp(other) < 0 |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 941 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 942 | def __le__(self, other, context=None): |
Mark Dickinson | 08ade6f | 2010-06-11 10:44:52 +0000 | [diff] [blame] | 943 | self, other = _convert_for_comparison(self, other) |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 944 | if other is NotImplemented: |
| 945 | return other |
| 946 | ans = self._compare_check_nans(other, context) |
| 947 | if ans: |
| 948 | return False |
| 949 | return self._cmp(other) <= 0 |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 950 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 951 | def __gt__(self, other, context=None): |
Mark Dickinson | 08ade6f | 2010-06-11 10:44:52 +0000 | [diff] [blame] | 952 | self, other = _convert_for_comparison(self, other) |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 953 | if other is NotImplemented: |
| 954 | return other |
| 955 | ans = self._compare_check_nans(other, context) |
| 956 | if ans: |
| 957 | return False |
| 958 | return self._cmp(other) > 0 |
| 959 | |
| 960 | def __ge__(self, other, context=None): |
Mark Dickinson | 08ade6f | 2010-06-11 10:44:52 +0000 | [diff] [blame] | 961 | self, other = _convert_for_comparison(self, other) |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 962 | if other is NotImplemented: |
| 963 | return other |
| 964 | ans = self._compare_check_nans(other, context) |
| 965 | if ans: |
| 966 | return False |
| 967 | return self._cmp(other) >= 0 |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 968 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 969 | def compare(self, other, context=None): |
Serhiy Storchaka | a60c2fe | 2015-03-12 21:56:08 +0200 | [diff] [blame] | 970 | """Compare self to other. Return a decimal value: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 971 | |
Serhiy Storchaka | a60c2fe | 2015-03-12 21:56:08 +0200 | [diff] [blame] | 972 | a or b is a NaN ==> Decimal('NaN') |
| 973 | a < b ==> Decimal('-1') |
| 974 | a == b ==> Decimal('0') |
| 975 | a > b ==> Decimal('1') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 976 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 977 | other = _convert_other(other, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 978 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 979 | # Compare(NaN, NaN) = NaN |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 980 | if (self._is_special or other and other._is_special): |
| 981 | ans = self._check_nans(other, context) |
| 982 | if ans: |
| 983 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 984 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 985 | return Decimal(self._cmp(other)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 986 | |
| 987 | def __hash__(self): |
| 988 | """x.__hash__() <==> hash(x)""" |
Mark Dickinson | ac256ab | 2010-04-03 11:08:14 +0000 | [diff] [blame] | 989 | |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 990 | # In order to make sure that the hash of a Decimal instance |
| 991 | # agrees with the hash of a numerically equal integer, float |
| 992 | # or Fraction, we follow the rules for numeric hashes outlined |
| 993 | # in the documentation. (See library docs, 'Built-in Types'). |
Raymond Hettinger | bea3f6f | 2005-03-15 04:59:17 +0000 | [diff] [blame] | 994 | if self._is_special: |
Mark Dickinson | ac256ab | 2010-04-03 11:08:14 +0000 | [diff] [blame] | 995 | if self.is_snan(): |
Raymond Hettinger | d325c4b | 2010-11-21 04:08:28 +0000 | [diff] [blame] | 996 | raise TypeError('Cannot hash a signaling NaN value.') |
Mark Dickinson | ac256ab | 2010-04-03 11:08:14 +0000 | [diff] [blame] | 997 | elif self.is_nan(): |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 998 | return _PyHASH_NAN |
Mark Dickinson | ac256ab | 2010-04-03 11:08:14 +0000 | [diff] [blame] | 999 | else: |
Mark Dickinson | ac256ab | 2010-04-03 11:08:14 +0000 | [diff] [blame] | 1000 | if self._sign: |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 1001 | return -_PyHASH_INF |
Mark Dickinson | ac256ab | 2010-04-03 11:08:14 +0000 | [diff] [blame] | 1002 | else: |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 1003 | return _PyHASH_INF |
Mark Dickinson | ac256ab | 2010-04-03 11:08:14 +0000 | [diff] [blame] | 1004 | |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 1005 | if self._exp >= 0: |
| 1006 | exp_hash = pow(10, self._exp, _PyHASH_MODULUS) |
| 1007 | else: |
| 1008 | exp_hash = pow(_PyHASH_10INV, -self._exp, _PyHASH_MODULUS) |
| 1009 | hash_ = int(self._int) * exp_hash % _PyHASH_MODULUS |
Stefan Krah | dc817b2 | 2010-11-17 11:16:34 +0000 | [diff] [blame] | 1010 | ans = hash_ if self >= 0 else -hash_ |
| 1011 | return -2 if ans == -1 else ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1012 | |
| 1013 | def as_tuple(self): |
| 1014 | """Represents the number as a triple tuple. |
| 1015 | |
| 1016 | To show the internals exactly as they are. |
| 1017 | """ |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 1018 | return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1019 | |
| 1020 | def __repr__(self): |
| 1021 | """Represents the number as an instance of Decimal.""" |
| 1022 | # Invariant: eval(repr(d)) == d |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 1023 | return "Decimal('%s')" % str(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1024 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1025 | def __str__(self, eng=False, context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1026 | """Return string representation of the number in scientific notation. |
| 1027 | |
| 1028 | Captures all of the information in the underlying representation. |
| 1029 | """ |
| 1030 | |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1031 | sign = ['', '-'][self._sign] |
Raymond Hettinger | e5a0a96 | 2005-06-20 09:49:42 +0000 | [diff] [blame] | 1032 | if self._is_special: |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1033 | if self._exp == 'F': |
| 1034 | return sign + 'Infinity' |
| 1035 | elif self._exp == 'n': |
| 1036 | return sign + 'NaN' + self._int |
| 1037 | else: # self._exp == 'N' |
| 1038 | return sign + 'sNaN' + self._int |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1039 | |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1040 | # number of digits of self._int to left of decimal point |
| 1041 | leftdigits = self._exp + len(self._int) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1042 | |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1043 | # dotplace is number of digits of self._int to the left of the |
| 1044 | # decimal point in the mantissa of the output string (that is, |
| 1045 | # after adjusting the exponent) |
| 1046 | if self._exp <= 0 and leftdigits > -6: |
| 1047 | # no exponent required |
| 1048 | dotplace = leftdigits |
| 1049 | elif not eng: |
| 1050 | # usual scientific notation: 1 digit on left of the point |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1051 | dotplace = 1 |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1052 | elif self._int == '0': |
| 1053 | # engineering notation, zero |
| 1054 | dotplace = (leftdigits + 1) % 3 - 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1055 | else: |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1056 | # engineering notation, nonzero |
| 1057 | dotplace = (leftdigits - 1) % 3 + 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1058 | |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1059 | if dotplace <= 0: |
| 1060 | intpart = '0' |
| 1061 | fracpart = '.' + '0'*(-dotplace) + self._int |
| 1062 | elif dotplace >= len(self._int): |
| 1063 | intpart = self._int+'0'*(dotplace-len(self._int)) |
| 1064 | fracpart = '' |
| 1065 | else: |
| 1066 | intpart = self._int[:dotplace] |
| 1067 | fracpart = '.' + self._int[dotplace:] |
| 1068 | if leftdigits == dotplace: |
| 1069 | exp = '' |
| 1070 | else: |
| 1071 | if context is None: |
| 1072 | context = getcontext() |
| 1073 | exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace) |
| 1074 | |
| 1075 | return sign + intpart + fracpart + exp |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1076 | |
| 1077 | def to_eng_string(self, context=None): |
| 1078 | """Convert to engineering-type string. |
| 1079 | |
| 1080 | Engineering notation has an exponent which is a multiple of 3, so there |
| 1081 | are up to 3 digits left of the decimal place. |
| 1082 | |
| 1083 | Same rules for when in exponential and when as a value as in __str__. |
| 1084 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1085 | return self.__str__(eng=True, context=context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1086 | |
| 1087 | def __neg__(self, context=None): |
| 1088 | """Returns a copy with the sign switched. |
| 1089 | |
| 1090 | Rounds, if it has reason. |
| 1091 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1092 | if self._is_special: |
| 1093 | ans = self._check_nans(context=context) |
| 1094 | if ans: |
| 1095 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1096 | |
Mark Dickinson | 37a79fb | 2011-03-12 11:12:52 +0000 | [diff] [blame] | 1097 | if context is None: |
| 1098 | context = getcontext() |
| 1099 | |
| 1100 | if not self and context.rounding != ROUND_FLOOR: |
| 1101 | # -Decimal('0') is Decimal('0'), not Decimal('-0'), except |
| 1102 | # in ROUND_FLOOR rounding mode. |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 1103 | ans = self.copy_abs() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1104 | else: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1105 | ans = self.copy_negate() |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1106 | |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1107 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1108 | |
| 1109 | def __pos__(self, context=None): |
| 1110 | """Returns a copy, unless it is a sNaN. |
| 1111 | |
| 1112 | Rounds the number (if more then precision digits) |
| 1113 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1114 | if self._is_special: |
| 1115 | ans = self._check_nans(context=context) |
| 1116 | if ans: |
| 1117 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1118 | |
Mark Dickinson | 37a79fb | 2011-03-12 11:12:52 +0000 | [diff] [blame] | 1119 | if context is None: |
| 1120 | context = getcontext() |
| 1121 | |
| 1122 | if not self and context.rounding != ROUND_FLOOR: |
| 1123 | # + (-0) = 0, except in ROUND_FLOOR rounding mode. |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 1124 | ans = self.copy_abs() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1125 | else: |
| 1126 | ans = Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1127 | |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1128 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1129 | |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1130 | def __abs__(self, round=True, context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1131 | """Returns the absolute value of self. |
| 1132 | |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1133 | If the keyword argument 'round' is false, do not round. The |
| 1134 | expression self.__abs__(round=False) is equivalent to |
| 1135 | self.copy_abs(). |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1136 | """ |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1137 | if not round: |
| 1138 | return self.copy_abs() |
| 1139 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1140 | if self._is_special: |
| 1141 | ans = self._check_nans(context=context) |
| 1142 | if ans: |
| 1143 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1144 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1145 | if self._sign: |
| 1146 | ans = self.__neg__(context=context) |
| 1147 | else: |
| 1148 | ans = self.__pos__(context=context) |
| 1149 | |
| 1150 | return ans |
| 1151 | |
| 1152 | def __add__(self, other, context=None): |
| 1153 | """Returns self + other. |
| 1154 | |
| 1155 | -INF + INF (or the reverse) cause InvalidOperation errors. |
| 1156 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1157 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1158 | if other is NotImplemented: |
| 1159 | return other |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1160 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1161 | if context is None: |
| 1162 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1163 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1164 | if self._is_special or other._is_special: |
| 1165 | ans = self._check_nans(other, context) |
| 1166 | if ans: |
| 1167 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1168 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1169 | if self._isinfinity(): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1170 | # If both INF, same sign => same as both, opposite => error. |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1171 | if self._sign != other._sign and other._isinfinity(): |
| 1172 | return context._raise_error(InvalidOperation, '-INF + INF') |
| 1173 | return Decimal(self) |
| 1174 | if other._isinfinity(): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1175 | return Decimal(other) # Can't both be infinity here |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1176 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1177 | exp = min(self._exp, other._exp) |
| 1178 | negativezero = 0 |
| 1179 | if context.rounding == ROUND_FLOOR and self._sign != other._sign: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1180 | # 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] | 1181 | negativezero = 1 |
| 1182 | |
| 1183 | if not self and not other: |
| 1184 | sign = min(self._sign, other._sign) |
| 1185 | if negativezero: |
| 1186 | sign = 1 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1187 | ans = _dec_from_triple(sign, '0', exp) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1188 | ans = ans._fix(context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1189 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1190 | if not self: |
Facundo Batista | 99b5548 | 2004-10-26 23:38:46 +0000 | [diff] [blame] | 1191 | exp = max(exp, other._exp - context.prec-1) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1192 | ans = other._rescale(exp, context.rounding) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1193 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1194 | return ans |
| 1195 | if not other: |
Facundo Batista | 99b5548 | 2004-10-26 23:38:46 +0000 | [diff] [blame] | 1196 | exp = max(exp, self._exp - context.prec-1) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1197 | ans = self._rescale(exp, context.rounding) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1198 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1199 | return ans |
| 1200 | |
| 1201 | op1 = _WorkRep(self) |
| 1202 | op2 = _WorkRep(other) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1203 | op1, op2 = _normalize(op1, op2, context.prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1204 | |
| 1205 | result = _WorkRep() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1206 | if op1.sign != op2.sign: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1207 | # Equal and opposite |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1208 | if op1.int == op2.int: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1209 | ans = _dec_from_triple(negativezero, '0', exp) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1210 | ans = ans._fix(context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1211 | return ans |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1212 | if op1.int < op2.int: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1213 | op1, op2 = op2, op1 |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1214 | # OK, now abs(op1) > abs(op2) |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1215 | if op1.sign == 1: |
| 1216 | result.sign = 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1217 | op1.sign, op2.sign = op2.sign, op1.sign |
| 1218 | else: |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1219 | result.sign = 0 |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1220 | # So we know the sign, and op1 > 0. |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1221 | elif op1.sign == 1: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1222 | result.sign = 1 |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1223 | op1.sign, op2.sign = (0, 0) |
| 1224 | else: |
| 1225 | result.sign = 0 |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1226 | # Now, op1 > abs(op2) > 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1227 | |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 1228 | if op2.sign == 0: |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1229 | result.int = op1.int + op2.int |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1230 | else: |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1231 | result.int = op1.int - op2.int |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1232 | |
| 1233 | result.exp = op1.exp |
| 1234 | ans = Decimal(result) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1235 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1236 | return ans |
| 1237 | |
| 1238 | __radd__ = __add__ |
| 1239 | |
| 1240 | def __sub__(self, other, context=None): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1241 | """Return self - other""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1242 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1243 | if other is NotImplemented: |
| 1244 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1245 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1246 | if self._is_special or other._is_special: |
| 1247 | ans = self._check_nans(other, context=context) |
| 1248 | if ans: |
| 1249 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1250 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1251 | # self - other is computed as self + other.copy_negate() |
| 1252 | return self.__add__(other.copy_negate(), context=context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1253 | |
| 1254 | def __rsub__(self, other, context=None): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1255 | """Return other - self""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1256 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1257 | if other is NotImplemented: |
| 1258 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1259 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1260 | return other.__sub__(self, context=context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1261 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1262 | def __mul__(self, other, context=None): |
| 1263 | """Return self * other. |
| 1264 | |
| 1265 | (+-) INF * 0 (or its reverse) raise InvalidOperation. |
| 1266 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1267 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1268 | if other is NotImplemented: |
| 1269 | return other |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1270 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1271 | if context is None: |
| 1272 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1273 | |
Raymond Hettinger | d87ac8f | 2004-07-09 10:52:54 +0000 | [diff] [blame] | 1274 | resultsign = self._sign ^ other._sign |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1275 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1276 | if self._is_special or other._is_special: |
| 1277 | ans = self._check_nans(other, context) |
| 1278 | if ans: |
| 1279 | return ans |
| 1280 | |
| 1281 | if self._isinfinity(): |
| 1282 | if not other: |
| 1283 | return context._raise_error(InvalidOperation, '(+-)INF * 0') |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 1284 | return _SignedInfinity[resultsign] |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1285 | |
| 1286 | if other._isinfinity(): |
| 1287 | if not self: |
| 1288 | return context._raise_error(InvalidOperation, '0 * (+-)INF') |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 1289 | return _SignedInfinity[resultsign] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1290 | |
| 1291 | resultexp = self._exp + other._exp |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1292 | |
| 1293 | # Special case for multiplying by zero |
| 1294 | if not self or not other: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1295 | ans = _dec_from_triple(resultsign, '0', resultexp) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1296 | # Fixing in case the exponent is out of bounds |
| 1297 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1298 | return ans |
| 1299 | |
| 1300 | # Special case for multiplying by power of 10 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1301 | if self._int == '1': |
| 1302 | ans = _dec_from_triple(resultsign, other._int, resultexp) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1303 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1304 | return ans |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1305 | if other._int == '1': |
| 1306 | ans = _dec_from_triple(resultsign, self._int, resultexp) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1307 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1308 | return ans |
| 1309 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1310 | op1 = _WorkRep(self) |
| 1311 | op2 = _WorkRep(other) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1312 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1313 | ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1314 | ans = ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1315 | |
| 1316 | return ans |
| 1317 | __rmul__ = __mul__ |
| 1318 | |
Neal Norwitz | bcc0db8 | 2006-03-24 08:14:36 +0000 | [diff] [blame] | 1319 | def __truediv__(self, other, context=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1320 | """Return self / other.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1321 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1322 | if other is NotImplemented: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1323 | return NotImplemented |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1324 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1325 | if context is None: |
| 1326 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1327 | |
Raymond Hettinger | d87ac8f | 2004-07-09 10:52:54 +0000 | [diff] [blame] | 1328 | sign = self._sign ^ other._sign |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1329 | |
| 1330 | if self._is_special or other._is_special: |
| 1331 | ans = self._check_nans(other, context) |
| 1332 | if ans: |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1333 | return ans |
| 1334 | |
| 1335 | if self._isinfinity() and other._isinfinity(): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1336 | return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1337 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1338 | if self._isinfinity(): |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 1339 | return _SignedInfinity[sign] |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1340 | |
| 1341 | if other._isinfinity(): |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1342 | context._raise_error(Clamped, 'Division by infinity') |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1343 | return _dec_from_triple(sign, '0', context.Etiny()) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1344 | |
| 1345 | # Special cases for zeroes |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1346 | if not other: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1347 | if not self: |
| 1348 | return context._raise_error(DivisionUndefined, '0 / 0') |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1349 | return context._raise_error(DivisionByZero, 'x / 0', sign) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1350 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1351 | if not self: |
| 1352 | exp = self._exp - other._exp |
| 1353 | coeff = 0 |
| 1354 | else: |
| 1355 | # OK, so neither = 0, INF or NaN |
| 1356 | shift = len(other._int) - len(self._int) + context.prec + 1 |
| 1357 | exp = self._exp - other._exp - shift |
| 1358 | op1 = _WorkRep(self) |
| 1359 | op2 = _WorkRep(other) |
| 1360 | if shift >= 0: |
| 1361 | coeff, remainder = divmod(op1.int * 10**shift, op2.int) |
| 1362 | else: |
| 1363 | coeff, remainder = divmod(op1.int, op2.int * 10**-shift) |
| 1364 | if remainder: |
| 1365 | # result is not exact; adjust to ensure correct rounding |
| 1366 | if coeff % 5 == 0: |
| 1367 | coeff += 1 |
| 1368 | else: |
| 1369 | # result is exact; get as close to ideal exponent as possible |
| 1370 | ideal_exp = self._exp - other._exp |
| 1371 | while exp < ideal_exp and coeff % 10 == 0: |
| 1372 | coeff //= 10 |
| 1373 | exp += 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1374 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1375 | ans = _dec_from_triple(sign, str(coeff), exp) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1376 | return ans._fix(context) |
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 | def _divide(self, other, context): |
| 1379 | """Return (self // other, self % other), to context.prec precision. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1380 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1381 | Assumes that neither self nor other is a NaN, that self is not |
| 1382 | infinite and that other is nonzero. |
| 1383 | """ |
| 1384 | sign = self._sign ^ other._sign |
| 1385 | if other._isinfinity(): |
| 1386 | ideal_exp = self._exp |
| 1387 | else: |
| 1388 | ideal_exp = min(self._exp, other._exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1389 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1390 | expdiff = self.adjusted() - other.adjusted() |
| 1391 | if not self or other._isinfinity() or expdiff <= -2: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1392 | return (_dec_from_triple(sign, '0', 0), |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1393 | self._rescale(ideal_exp, context.rounding)) |
| 1394 | if expdiff <= context.prec: |
| 1395 | op1 = _WorkRep(self) |
| 1396 | op2 = _WorkRep(other) |
| 1397 | if op1.exp >= op2.exp: |
| 1398 | op1.int *= 10**(op1.exp - op2.exp) |
| 1399 | else: |
| 1400 | op2.int *= 10**(op2.exp - op1.exp) |
| 1401 | q, r = divmod(op1.int, op2.int) |
| 1402 | if q < 10**context.prec: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1403 | return (_dec_from_triple(sign, str(q), 0), |
| 1404 | _dec_from_triple(self._sign, str(r), ideal_exp)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1405 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1406 | # Here the quotient is too large to be representable |
| 1407 | ans = context._raise_error(DivisionImpossible, |
| 1408 | 'quotient too large in //, % or divmod') |
| 1409 | return ans, ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1410 | |
Neal Norwitz | bcc0db8 | 2006-03-24 08:14:36 +0000 | [diff] [blame] | 1411 | def __rtruediv__(self, other, context=None): |
| 1412 | """Swaps self/other and returns __truediv__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1413 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1414 | if other is NotImplemented: |
| 1415 | return other |
Neal Norwitz | bcc0db8 | 2006-03-24 08:14:36 +0000 | [diff] [blame] | 1416 | return other.__truediv__(self, context=context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1417 | |
| 1418 | def __divmod__(self, other, context=None): |
| 1419 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1420 | Return (self // other, self % other) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1421 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1422 | other = _convert_other(other) |
| 1423 | if other is NotImplemented: |
| 1424 | return other |
| 1425 | |
| 1426 | if context is None: |
| 1427 | context = getcontext() |
| 1428 | |
| 1429 | ans = self._check_nans(other, context) |
| 1430 | if ans: |
| 1431 | return (ans, ans) |
| 1432 | |
| 1433 | sign = self._sign ^ other._sign |
| 1434 | if self._isinfinity(): |
| 1435 | if other._isinfinity(): |
| 1436 | ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)') |
| 1437 | return ans, ans |
| 1438 | else: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 1439 | return (_SignedInfinity[sign], |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1440 | context._raise_error(InvalidOperation, 'INF % x')) |
| 1441 | |
| 1442 | if not other: |
| 1443 | if not self: |
| 1444 | ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)') |
| 1445 | return ans, ans |
| 1446 | else: |
| 1447 | return (context._raise_error(DivisionByZero, 'x // 0', sign), |
| 1448 | context._raise_error(InvalidOperation, 'x % 0')) |
| 1449 | |
| 1450 | quotient, remainder = self._divide(other, context) |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1451 | remainder = remainder._fix(context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1452 | return quotient, remainder |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1453 | |
| 1454 | def __rdivmod__(self, other, context=None): |
| 1455 | """Swaps self/other and returns __divmod__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1456 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1457 | if other is NotImplemented: |
| 1458 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1459 | return other.__divmod__(self, context=context) |
| 1460 | |
| 1461 | def __mod__(self, other, context=None): |
| 1462 | """ |
| 1463 | self % other |
| 1464 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1465 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1466 | if other is NotImplemented: |
| 1467 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1468 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1469 | if context is None: |
| 1470 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1471 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1472 | ans = self._check_nans(other, context) |
| 1473 | if ans: |
| 1474 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1475 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1476 | if self._isinfinity(): |
| 1477 | return context._raise_error(InvalidOperation, 'INF % x') |
| 1478 | elif not other: |
| 1479 | if self: |
| 1480 | return context._raise_error(InvalidOperation, 'x % 0') |
| 1481 | else: |
| 1482 | return context._raise_error(DivisionUndefined, '0 % 0') |
| 1483 | |
| 1484 | remainder = self._divide(other, context)[1] |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 1485 | remainder = remainder._fix(context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1486 | return remainder |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1487 | |
| 1488 | def __rmod__(self, other, context=None): |
| 1489 | """Swaps self/other and returns __mod__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1490 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1491 | if other is NotImplemented: |
| 1492 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1493 | return other.__mod__(self, context=context) |
| 1494 | |
| 1495 | def remainder_near(self, other, context=None): |
| 1496 | """ |
| 1497 | Remainder nearest to 0- abs(remainder-near) <= other/2 |
| 1498 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1499 | if context is None: |
| 1500 | context = getcontext() |
| 1501 | |
| 1502 | other = _convert_other(other, raiseit=True) |
| 1503 | |
| 1504 | ans = self._check_nans(other, context) |
| 1505 | if ans: |
| 1506 | return ans |
| 1507 | |
| 1508 | # self == +/-infinity -> InvalidOperation |
| 1509 | if self._isinfinity(): |
| 1510 | return context._raise_error(InvalidOperation, |
| 1511 | 'remainder_near(infinity, x)') |
| 1512 | |
| 1513 | # other == 0 -> either InvalidOperation or DivisionUndefined |
| 1514 | if not other: |
| 1515 | if self: |
| 1516 | return context._raise_error(InvalidOperation, |
| 1517 | 'remainder_near(x, 0)') |
| 1518 | else: |
| 1519 | return context._raise_error(DivisionUndefined, |
| 1520 | 'remainder_near(0, 0)') |
| 1521 | |
| 1522 | # other = +/-infinity -> remainder = self |
| 1523 | if other._isinfinity(): |
| 1524 | ans = Decimal(self) |
| 1525 | return ans._fix(context) |
| 1526 | |
| 1527 | # self = 0 -> remainder = self, with ideal exponent |
| 1528 | ideal_exponent = min(self._exp, other._exp) |
| 1529 | if not self: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1530 | ans = _dec_from_triple(self._sign, '0', ideal_exponent) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1531 | return ans._fix(context) |
| 1532 | |
| 1533 | # catch most cases of large or small quotient |
| 1534 | expdiff = self.adjusted() - other.adjusted() |
| 1535 | if expdiff >= context.prec + 1: |
| 1536 | # expdiff >= prec+1 => abs(self/other) > 10**prec |
| 1537 | return context._raise_error(DivisionImpossible) |
| 1538 | if expdiff <= -2: |
| 1539 | # expdiff <= -2 => abs(self/other) < 0.1 |
| 1540 | ans = self._rescale(ideal_exponent, context.rounding) |
| 1541 | return ans._fix(context) |
| 1542 | |
| 1543 | # adjust both arguments to have the same exponent, then divide |
| 1544 | op1 = _WorkRep(self) |
| 1545 | op2 = _WorkRep(other) |
| 1546 | if op1.exp >= op2.exp: |
| 1547 | op1.int *= 10**(op1.exp - op2.exp) |
| 1548 | else: |
| 1549 | op2.int *= 10**(op2.exp - op1.exp) |
| 1550 | q, r = divmod(op1.int, op2.int) |
| 1551 | # remainder is r*10**ideal_exponent; other is +/-op2.int * |
| 1552 | # 10**ideal_exponent. Apply correction to ensure that |
| 1553 | # abs(remainder) <= abs(other)/2 |
| 1554 | if 2*r + (q&1) > op2.int: |
| 1555 | r -= op2.int |
| 1556 | q += 1 |
| 1557 | |
| 1558 | if q >= 10**context.prec: |
| 1559 | return context._raise_error(DivisionImpossible) |
| 1560 | |
| 1561 | # result has same sign as self unless r is negative |
| 1562 | sign = self._sign |
| 1563 | if r < 0: |
| 1564 | sign = 1-sign |
| 1565 | r = -r |
| 1566 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1567 | ans = _dec_from_triple(sign, str(r), ideal_exponent) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1568 | return ans._fix(context) |
| 1569 | |
| 1570 | def __floordiv__(self, other, context=None): |
| 1571 | """self // other""" |
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 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1576 | if context is None: |
| 1577 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1578 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1579 | ans = self._check_nans(other, context) |
| 1580 | if ans: |
| 1581 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1582 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1583 | if self._isinfinity(): |
| 1584 | if other._isinfinity(): |
| 1585 | return context._raise_error(InvalidOperation, 'INF // INF') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1586 | else: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 1587 | return _SignedInfinity[self._sign ^ other._sign] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1588 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1589 | if not other: |
| 1590 | if self: |
| 1591 | return context._raise_error(DivisionByZero, 'x // 0', |
| 1592 | self._sign ^ other._sign) |
| 1593 | else: |
| 1594 | return context._raise_error(DivisionUndefined, '0 // 0') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1595 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1596 | return self._divide(other, context)[0] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1597 | |
| 1598 | def __rfloordiv__(self, other, context=None): |
| 1599 | """Swaps self/other and returns __floordiv__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1600 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 1601 | if other is NotImplemented: |
| 1602 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1603 | return other.__floordiv__(self, context=context) |
| 1604 | |
| 1605 | def __float__(self): |
| 1606 | """Float representation.""" |
Mark Dickinson | fc33d4c | 2012-08-24 18:53:10 +0100 | [diff] [blame] | 1607 | if self._isnan(): |
| 1608 | if self.is_snan(): |
| 1609 | raise ValueError("Cannot convert signaling NaN to float") |
| 1610 | s = "-nan" if self._sign else "nan" |
| 1611 | else: |
| 1612 | s = str(self) |
| 1613 | return float(s) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1614 | |
| 1615 | def __int__(self): |
Brett Cannon | 46b0802 | 2005-03-01 03:12:26 +0000 | [diff] [blame] | 1616 | """Converts self to an int, truncating if necessary.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1617 | if self._is_special: |
| 1618 | if self._isnan(): |
Mark Dickinson | 825fce3 | 2009-09-07 18:08:12 +0000 | [diff] [blame] | 1619 | raise ValueError("Cannot convert NaN to integer") |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1620 | elif self._isinfinity(): |
Mark Dickinson | 825fce3 | 2009-09-07 18:08:12 +0000 | [diff] [blame] | 1621 | raise OverflowError("Cannot convert infinity to integer") |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1622 | s = (-1)**self._sign |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1623 | if self._exp >= 0: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1624 | return s*int(self._int)*10**self._exp |
Raymond Hettinger | 605ed02 | 2004-11-24 07:28:48 +0000 | [diff] [blame] | 1625 | else: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1626 | return s*int(self._int[:self._exp] or '0') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1627 | |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 1628 | __trunc__ = __int__ |
| 1629 | |
Christian Heimes | 0bd4e11 | 2008-02-12 22:59:25 +0000 | [diff] [blame] | 1630 | def real(self): |
| 1631 | return self |
Mark Dickinson | 315a20a | 2009-01-04 21:34:18 +0000 | [diff] [blame] | 1632 | real = property(real) |
Christian Heimes | 0bd4e11 | 2008-02-12 22:59:25 +0000 | [diff] [blame] | 1633 | |
Christian Heimes | 0bd4e11 | 2008-02-12 22:59:25 +0000 | [diff] [blame] | 1634 | def imag(self): |
| 1635 | return Decimal(0) |
Mark Dickinson | 315a20a | 2009-01-04 21:34:18 +0000 | [diff] [blame] | 1636 | imag = property(imag) |
Christian Heimes | 0bd4e11 | 2008-02-12 22:59:25 +0000 | [diff] [blame] | 1637 | |
| 1638 | def conjugate(self): |
| 1639 | return self |
| 1640 | |
| 1641 | def __complex__(self): |
| 1642 | return complex(float(self)) |
| 1643 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1644 | def _fix_nan(self, context): |
| 1645 | """Decapitate the payload of a NaN to fit the context""" |
| 1646 | payload = self._int |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1647 | |
Mark Dickinson | b1d8e32 | 2010-05-22 18:35:36 +0000 | [diff] [blame] | 1648 | # maximum length of payload is precision if clamp=0, |
| 1649 | # precision-1 if clamp=1. |
| 1650 | max_payload_len = context.prec - context.clamp |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1651 | if len(payload) > max_payload_len: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1652 | payload = payload[len(payload)-max_payload_len:].lstrip('0') |
| 1653 | return _dec_from_triple(self._sign, payload, self._exp, True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1654 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1655 | |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 1656 | def _fix(self, context): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1657 | """Round if it is necessary to keep self within prec precision. |
| 1658 | |
| 1659 | Rounds and fixes the exponent. Does not raise on a sNaN. |
| 1660 | |
| 1661 | Arguments: |
| 1662 | self - Decimal instance |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1663 | context - context used. |
| 1664 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1665 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1666 | if self._is_special: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1667 | if self._isnan(): |
| 1668 | # decapitate payload if necessary |
| 1669 | return self._fix_nan(context) |
| 1670 | else: |
| 1671 | # self is +/-Infinity; return unaltered |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 1672 | return Decimal(self) |
| 1673 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1674 | # if self is zero then exponent should be between Etiny and |
Mark Dickinson | b1d8e32 | 2010-05-22 18:35:36 +0000 | [diff] [blame] | 1675 | # Emax if clamp==0, and between Etiny and Etop if clamp==1. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1676 | Etiny = context.Etiny() |
| 1677 | Etop = context.Etop() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1678 | if not self: |
Mark Dickinson | b1d8e32 | 2010-05-22 18:35:36 +0000 | [diff] [blame] | 1679 | exp_max = [context.Emax, Etop][context.clamp] |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1680 | new_exp = min(max(self._exp, Etiny), exp_max) |
| 1681 | if new_exp != self._exp: |
| 1682 | context._raise_error(Clamped) |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1683 | return _dec_from_triple(self._sign, '0', new_exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1684 | else: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1685 | return Decimal(self) |
| 1686 | |
| 1687 | # exp_min is the smallest allowable exponent of the result, |
| 1688 | # equal to max(self.adjusted()-context.prec+1, Etiny) |
| 1689 | exp_min = len(self._int) + self._exp - context.prec |
| 1690 | if exp_min > Etop: |
| 1691 | # overflow: exp_min > Etop iff self.adjusted() > Emax |
Mark Dickinson | c69160e | 2010-05-04 14:35:33 +0000 | [diff] [blame] | 1692 | ans = context._raise_error(Overflow, 'above Emax', self._sign) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1693 | context._raise_error(Inexact) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1694 | context._raise_error(Rounded) |
Mark Dickinson | c69160e | 2010-05-04 14:35:33 +0000 | [diff] [blame] | 1695 | return ans |
| 1696 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1697 | self_is_subnormal = exp_min < Etiny |
| 1698 | if self_is_subnormal: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1699 | exp_min = Etiny |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1700 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1701 | # round if self has too many digits |
| 1702 | if self._exp < exp_min: |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1703 | digits = len(self._int) + self._exp - exp_min |
| 1704 | if digits < 0: |
| 1705 | self = _dec_from_triple(self._sign, '1', exp_min-1) |
| 1706 | digits = 0 |
Mark Dickinson | c69160e | 2010-05-04 14:35:33 +0000 | [diff] [blame] | 1707 | rounding_method = self._pick_rounding_function[context.rounding] |
Alexander Belopolsky | 1a20c12 | 2011-04-12 23:03:39 -0400 | [diff] [blame] | 1708 | changed = rounding_method(self, digits) |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1709 | coeff = self._int[:digits] or '0' |
Mark Dickinson | c69160e | 2010-05-04 14:35:33 +0000 | [diff] [blame] | 1710 | if changed > 0: |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1711 | coeff = str(int(coeff)+1) |
Mark Dickinson | c69160e | 2010-05-04 14:35:33 +0000 | [diff] [blame] | 1712 | if len(coeff) > context.prec: |
| 1713 | coeff = coeff[:-1] |
| 1714 | exp_min += 1 |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1715 | |
Mark Dickinson | c69160e | 2010-05-04 14:35:33 +0000 | [diff] [blame] | 1716 | # check whether the rounding pushed the exponent out of range |
| 1717 | if exp_min > Etop: |
| 1718 | ans = context._raise_error(Overflow, 'above Emax', self._sign) |
| 1719 | else: |
| 1720 | ans = _dec_from_triple(self._sign, coeff, exp_min) |
| 1721 | |
| 1722 | # raise the appropriate signals, taking care to respect |
| 1723 | # the precedence described in the specification |
| 1724 | if changed and self_is_subnormal: |
| 1725 | context._raise_error(Underflow) |
| 1726 | if self_is_subnormal: |
| 1727 | context._raise_error(Subnormal) |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1728 | if changed: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1729 | context._raise_error(Inexact) |
Mark Dickinson | c69160e | 2010-05-04 14:35:33 +0000 | [diff] [blame] | 1730 | context._raise_error(Rounded) |
| 1731 | if not ans: |
| 1732 | # raise Clamped on underflow to 0 |
| 1733 | context._raise_error(Clamped) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1734 | return ans |
| 1735 | |
Mark Dickinson | c69160e | 2010-05-04 14:35:33 +0000 | [diff] [blame] | 1736 | if self_is_subnormal: |
| 1737 | context._raise_error(Subnormal) |
| 1738 | |
Mark Dickinson | b1d8e32 | 2010-05-22 18:35:36 +0000 | [diff] [blame] | 1739 | # fold down if clamp == 1 and self has too few digits |
| 1740 | if context.clamp == 1 and self._exp > Etop: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1741 | context._raise_error(Clamped) |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1742 | self_padded = self._int + '0'*(self._exp - Etop) |
| 1743 | return _dec_from_triple(self._sign, self_padded, Etop) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1744 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1745 | # here self was representable to begin with; return unchanged |
| 1746 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1747 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1748 | # for each of the rounding functions below: |
| 1749 | # self is a finite, nonzero Decimal |
| 1750 | # prec is an integer satisfying 0 <= prec < len(self._int) |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1751 | # |
| 1752 | # each function returns either -1, 0, or 1, as follows: |
| 1753 | # 1 indicates that self should be rounded up (away from zero) |
| 1754 | # 0 indicates that self should be truncated, and that all the |
| 1755 | # digits to be truncated are zeros (so the value is unchanged) |
| 1756 | # -1 indicates that there are nonzero digits to be truncated |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1757 | |
| 1758 | def _round_down(self, prec): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1759 | """Also known as round-towards-0, truncate.""" |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1760 | if _all_zeros(self._int, prec): |
| 1761 | return 0 |
| 1762 | else: |
| 1763 | return -1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1764 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1765 | def _round_up(self, prec): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1766 | """Rounds away from 0.""" |
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_half_up(self, prec): |
| 1770 | """Rounds 5 up (away from 0)""" |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 1771 | if self._int[prec] in '56789': |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1772 | return 1 |
| 1773 | elif _all_zeros(self._int, prec): |
| 1774 | return 0 |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1775 | else: |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1776 | return -1 |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1777 | |
| 1778 | def _round_half_down(self, prec): |
| 1779 | """Round 5 down""" |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1780 | if _exact_half(self._int, prec): |
| 1781 | return -1 |
| 1782 | else: |
| 1783 | return self._round_half_up(prec) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1784 | |
| 1785 | def _round_half_even(self, prec): |
| 1786 | """Round 5 to even, rest to nearest.""" |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1787 | if _exact_half(self._int, prec) and \ |
| 1788 | (prec == 0 or self._int[prec-1] in '02468'): |
| 1789 | return -1 |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1790 | else: |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1791 | return self._round_half_up(prec) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1792 | |
| 1793 | def _round_ceiling(self, prec): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1794 | """Rounds up (not away from 0 if negative.)""" |
| 1795 | if self._sign: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1796 | return self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1797 | else: |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1798 | return -self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1799 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1800 | def _round_floor(self, prec): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1801 | """Rounds down (not towards 0 if negative)""" |
| 1802 | if not self._sign: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1803 | return self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1804 | else: |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1805 | return -self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1806 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1807 | def _round_05up(self, prec): |
| 1808 | """Round down unless digit prec-1 is 0 or 5.""" |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1809 | if prec and self._int[prec-1] not in '05': |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1810 | return self._round_down(prec) |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 1811 | else: |
| 1812 | return -self._round_down(prec) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1813 | |
Alexander Belopolsky | 1a20c12 | 2011-04-12 23:03:39 -0400 | [diff] [blame] | 1814 | _pick_rounding_function = dict( |
| 1815 | ROUND_DOWN = _round_down, |
| 1816 | ROUND_UP = _round_up, |
| 1817 | ROUND_HALF_UP = _round_half_up, |
| 1818 | ROUND_HALF_DOWN = _round_half_down, |
| 1819 | ROUND_HALF_EVEN = _round_half_even, |
| 1820 | ROUND_CEILING = _round_ceiling, |
| 1821 | ROUND_FLOOR = _round_floor, |
| 1822 | ROUND_05UP = _round_05up, |
| 1823 | ) |
| 1824 | |
Mark Dickinson | b27406c | 2008-05-09 13:42:33 +0000 | [diff] [blame] | 1825 | def __round__(self, n=None): |
| 1826 | """Round self to the nearest integer, or to a given precision. |
| 1827 | |
| 1828 | If only one argument is supplied, round a finite Decimal |
| 1829 | instance self to the nearest integer. If self is infinite or |
| 1830 | a NaN then a Python exception is raised. If self is finite |
| 1831 | and lies exactly halfway between two integers then it is |
| 1832 | rounded to the integer with even last digit. |
| 1833 | |
| 1834 | >>> round(Decimal('123.456')) |
| 1835 | 123 |
| 1836 | >>> round(Decimal('-456.789')) |
| 1837 | -457 |
| 1838 | >>> round(Decimal('-3.0')) |
| 1839 | -3 |
| 1840 | >>> round(Decimal('2.5')) |
| 1841 | 2 |
| 1842 | >>> round(Decimal('3.5')) |
| 1843 | 4 |
| 1844 | >>> round(Decimal('Inf')) |
| 1845 | Traceback (most recent call last): |
| 1846 | ... |
Mark Dickinson | b27406c | 2008-05-09 13:42:33 +0000 | [diff] [blame] | 1847 | OverflowError: cannot round an infinity |
| 1848 | >>> round(Decimal('NaN')) |
| 1849 | Traceback (most recent call last): |
| 1850 | ... |
Mark Dickinson | b27406c | 2008-05-09 13:42:33 +0000 | [diff] [blame] | 1851 | ValueError: cannot round a NaN |
| 1852 | |
| 1853 | If a second argument n is supplied, self is rounded to n |
| 1854 | decimal places using the rounding mode for the current |
| 1855 | context. |
| 1856 | |
| 1857 | For an integer n, round(self, -n) is exactly equivalent to |
| 1858 | self.quantize(Decimal('1En')). |
| 1859 | |
| 1860 | >>> round(Decimal('123.456'), 0) |
| 1861 | Decimal('123') |
| 1862 | >>> round(Decimal('123.456'), 2) |
| 1863 | Decimal('123.46') |
| 1864 | >>> round(Decimal('123.456'), -2) |
| 1865 | Decimal('1E+2') |
| 1866 | >>> round(Decimal('-Infinity'), 37) |
| 1867 | Decimal('NaN') |
| 1868 | >>> round(Decimal('sNaN123'), 0) |
| 1869 | Decimal('NaN123') |
| 1870 | |
| 1871 | """ |
| 1872 | if n is not None: |
| 1873 | # two-argument form: use the equivalent quantize call |
| 1874 | if not isinstance(n, int): |
| 1875 | raise TypeError('Second argument to round should be integral') |
| 1876 | exp = _dec_from_triple(0, '1', -n) |
| 1877 | return self.quantize(exp) |
| 1878 | |
| 1879 | # one-argument form |
| 1880 | if self._is_special: |
| 1881 | if self.is_nan(): |
| 1882 | raise ValueError("cannot round a NaN") |
| 1883 | else: |
| 1884 | raise OverflowError("cannot round an infinity") |
| 1885 | return int(self._rescale(0, ROUND_HALF_EVEN)) |
| 1886 | |
| 1887 | def __floor__(self): |
| 1888 | """Return the floor of self, as an integer. |
| 1889 | |
| 1890 | For a finite Decimal instance self, return the greatest |
| 1891 | integer n such that n <= self. If self is infinite or a NaN |
| 1892 | then a Python exception is raised. |
| 1893 | |
| 1894 | """ |
| 1895 | if self._is_special: |
| 1896 | if self.is_nan(): |
| 1897 | raise ValueError("cannot round a NaN") |
| 1898 | else: |
| 1899 | raise OverflowError("cannot round an infinity") |
| 1900 | return int(self._rescale(0, ROUND_FLOOR)) |
| 1901 | |
| 1902 | def __ceil__(self): |
| 1903 | """Return the ceiling of self, as an integer. |
| 1904 | |
| 1905 | For a finite Decimal instance self, return the least integer n |
| 1906 | such that n >= self. If self is infinite or a NaN then a |
| 1907 | Python exception is raised. |
| 1908 | |
| 1909 | """ |
| 1910 | if self._is_special: |
| 1911 | if self.is_nan(): |
| 1912 | raise ValueError("cannot round a NaN") |
| 1913 | else: |
| 1914 | raise OverflowError("cannot round an infinity") |
| 1915 | return int(self._rescale(0, ROUND_CEILING)) |
| 1916 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1917 | def fma(self, other, third, context=None): |
| 1918 | """Fused multiply-add. |
| 1919 | |
| 1920 | Returns self*other+third with no rounding of the intermediate |
| 1921 | product self*other. |
| 1922 | |
| 1923 | self and other are multiplied together, with no rounding of |
| 1924 | the result. The third operand is then added to the result, |
| 1925 | and a single final rounding is performed. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1926 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1927 | |
| 1928 | other = _convert_other(other, raiseit=True) |
Mark Dickinson | b455e58 | 2011-05-22 12:53:18 +0100 | [diff] [blame] | 1929 | third = _convert_other(third, raiseit=True) |
Christian Heimes | 8b0facf | 2007-12-04 19:30:01 +0000 | [diff] [blame] | 1930 | |
| 1931 | # compute product; raise InvalidOperation if either operand is |
| 1932 | # a signaling NaN or if the product is zero times infinity. |
| 1933 | if self._is_special or other._is_special: |
| 1934 | if context is None: |
| 1935 | context = getcontext() |
| 1936 | if self._exp == 'N': |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 1937 | return context._raise_error(InvalidOperation, 'sNaN', self) |
Christian Heimes | 8b0facf | 2007-12-04 19:30:01 +0000 | [diff] [blame] | 1938 | if other._exp == 'N': |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 1939 | return context._raise_error(InvalidOperation, 'sNaN', other) |
Christian Heimes | 8b0facf | 2007-12-04 19:30:01 +0000 | [diff] [blame] | 1940 | if self._exp == 'n': |
| 1941 | product = self |
| 1942 | elif other._exp == 'n': |
| 1943 | product = other |
| 1944 | elif self._exp == 'F': |
| 1945 | if not other: |
| 1946 | return context._raise_error(InvalidOperation, |
| 1947 | 'INF * 0 in fma') |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 1948 | product = _SignedInfinity[self._sign ^ other._sign] |
Christian Heimes | 8b0facf | 2007-12-04 19:30:01 +0000 | [diff] [blame] | 1949 | elif other._exp == 'F': |
| 1950 | if not self: |
| 1951 | return context._raise_error(InvalidOperation, |
| 1952 | '0 * INF in fma') |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 1953 | product = _SignedInfinity[self._sign ^ other._sign] |
Christian Heimes | 8b0facf | 2007-12-04 19:30:01 +0000 | [diff] [blame] | 1954 | else: |
| 1955 | product = _dec_from_triple(self._sign ^ other._sign, |
| 1956 | str(int(self._int) * int(other._int)), |
| 1957 | self._exp + other._exp) |
| 1958 | |
Christian Heimes | 8b0facf | 2007-12-04 19:30:01 +0000 | [diff] [blame] | 1959 | return product.__add__(third, context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1960 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1961 | def _power_modulo(self, other, modulo, context=None): |
| 1962 | """Three argument version of __pow__""" |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1963 | |
Stefan Krah | 1919b7e | 2012-03-21 18:25:23 +0100 | [diff] [blame] | 1964 | other = _convert_other(other) |
| 1965 | if other is NotImplemented: |
| 1966 | return other |
| 1967 | modulo = _convert_other(modulo) |
| 1968 | if modulo is NotImplemented: |
| 1969 | return modulo |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1970 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1971 | if context is None: |
| 1972 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1973 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1974 | # deal with NaNs: if there are any sNaNs then first one wins, |
| 1975 | # (i.e. behaviour for NaNs is identical to that of fma) |
| 1976 | self_is_nan = self._isnan() |
| 1977 | other_is_nan = other._isnan() |
| 1978 | modulo_is_nan = modulo._isnan() |
| 1979 | if self_is_nan or other_is_nan or modulo_is_nan: |
| 1980 | if self_is_nan == 2: |
| 1981 | return context._raise_error(InvalidOperation, 'sNaN', |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 1982 | self) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1983 | if other_is_nan == 2: |
| 1984 | return context._raise_error(InvalidOperation, 'sNaN', |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 1985 | other) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1986 | if modulo_is_nan == 2: |
| 1987 | return context._raise_error(InvalidOperation, 'sNaN', |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 1988 | modulo) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1989 | if self_is_nan: |
| 1990 | return self._fix_nan(context) |
| 1991 | if other_is_nan: |
| 1992 | return other._fix_nan(context) |
| 1993 | return modulo._fix_nan(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1994 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1995 | # check inputs: we apply same restrictions as Python's pow() |
| 1996 | if not (self._isinteger() and |
| 1997 | other._isinteger() and |
| 1998 | modulo._isinteger()): |
| 1999 | return context._raise_error(InvalidOperation, |
| 2000 | 'pow() 3rd argument not allowed ' |
| 2001 | 'unless all arguments are integers') |
| 2002 | if other < 0: |
| 2003 | return context._raise_error(InvalidOperation, |
| 2004 | 'pow() 2nd argument cannot be ' |
| 2005 | 'negative when 3rd argument specified') |
| 2006 | if not modulo: |
| 2007 | return context._raise_error(InvalidOperation, |
| 2008 | 'pow() 3rd argument cannot be 0') |
| 2009 | |
| 2010 | # additional restriction for decimal: the modulus must be less |
| 2011 | # than 10**prec in absolute value |
| 2012 | if modulo.adjusted() >= context.prec: |
| 2013 | return context._raise_error(InvalidOperation, |
| 2014 | 'insufficient precision: pow() 3rd ' |
| 2015 | 'argument must not have more than ' |
| 2016 | 'precision digits') |
| 2017 | |
| 2018 | # define 0**0 == NaN, for consistency with two-argument pow |
| 2019 | # (even though it hurts!) |
| 2020 | if not other and not self: |
| 2021 | return context._raise_error(InvalidOperation, |
| 2022 | 'at least one of pow() 1st argument ' |
| 2023 | 'and 2nd argument must be nonzero ;' |
| 2024 | '0**0 is not defined') |
| 2025 | |
| 2026 | # compute sign of result |
| 2027 | if other._iseven(): |
| 2028 | sign = 0 |
| 2029 | else: |
| 2030 | sign = self._sign |
| 2031 | |
| 2032 | # convert modulo to a Python integer, and self and other to |
| 2033 | # Decimal integers (i.e. force their exponents to be >= 0) |
| 2034 | modulo = abs(int(modulo)) |
| 2035 | base = _WorkRep(self.to_integral_value()) |
| 2036 | exponent = _WorkRep(other.to_integral_value()) |
| 2037 | |
| 2038 | # compute result using integer pow() |
| 2039 | base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo |
| 2040 | for i in range(exponent.exp): |
| 2041 | base = pow(base, 10, modulo) |
| 2042 | base = pow(base, exponent.int, modulo) |
| 2043 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2044 | return _dec_from_triple(sign, str(base), 0) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2045 | |
| 2046 | def _power_exact(self, other, p): |
| 2047 | """Attempt to compute self**other exactly. |
| 2048 | |
| 2049 | Given Decimals self and other and an integer p, attempt to |
| 2050 | compute an exact result for the power self**other, with p |
| 2051 | digits of precision. Return None if self**other is not |
| 2052 | exactly representable in p digits. |
| 2053 | |
| 2054 | Assumes that elimination of special cases has already been |
| 2055 | performed: self and other must both be nonspecial; self must |
| 2056 | be positive and not numerically equal to 1; other must be |
| 2057 | nonzero. For efficiency, other._exp should not be too large, |
| 2058 | so that 10**abs(other._exp) is a feasible calculation.""" |
| 2059 | |
Mark Dickinson | 7ce0fa8 | 2011-06-04 18:14:23 +0100 | [diff] [blame] | 2060 | # In the comments below, we write x for the value of self and y for the |
| 2061 | # value of other. Write x = xc*10**xe and abs(y) = yc*10**ye, with xc |
| 2062 | # and yc positive integers not divisible by 10. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2063 | |
| 2064 | # The main purpose of this method is to identify the *failure* |
| 2065 | # of x**y to be exactly representable with as little effort as |
| 2066 | # possible. So we look for cheap and easy tests that |
| 2067 | # eliminate the possibility of x**y being exact. Only if all |
| 2068 | # these tests are passed do we go on to actually compute x**y. |
| 2069 | |
Mark Dickinson | 7ce0fa8 | 2011-06-04 18:14:23 +0100 | [diff] [blame] | 2070 | # Here's the main idea. Express y as a rational number m/n, with m and |
| 2071 | # n relatively prime and n>0. Then for x**y to be exactly |
| 2072 | # representable (at *any* precision), xc must be the nth power of a |
| 2073 | # positive integer and xe must be divisible by n. If y is negative |
| 2074 | # then additionally xc must be a power of either 2 or 5, hence a power |
| 2075 | # of 2**n or 5**n. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2076 | # |
| 2077 | # There's a limit to how small |y| can be: if y=m/n as above |
| 2078 | # then: |
| 2079 | # |
| 2080 | # (1) if xc != 1 then for the result to be representable we |
| 2081 | # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So |
| 2082 | # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <= |
| 2083 | # 2**(1/|y|), hence xc**|y| < 2 and the result is not |
| 2084 | # representable. |
| 2085 | # |
| 2086 | # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if |
| 2087 | # |y| < 1/|xe| then the result is not representable. |
| 2088 | # |
| 2089 | # Note that since x is not equal to 1, at least one of (1) and |
| 2090 | # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) < |
| 2091 | # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye. |
| 2092 | # |
| 2093 | # There's also a limit to how large y can be, at least if it's |
| 2094 | # positive: the normalized result will have coefficient xc**y, |
| 2095 | # so if it's representable then xc**y < 10**p, and y < |
| 2096 | # p/log10(xc). Hence if y*log10(xc) >= p then the result is |
| 2097 | # not exactly representable. |
| 2098 | |
| 2099 | # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye, |
| 2100 | # so |y| < 1/xe and the result is not representable. |
| 2101 | # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y| |
| 2102 | # < 1/nbits(xc). |
| 2103 | |
| 2104 | x = _WorkRep(self) |
| 2105 | xc, xe = x.int, x.exp |
| 2106 | while xc % 10 == 0: |
| 2107 | xc //= 10 |
| 2108 | xe += 1 |
| 2109 | |
| 2110 | y = _WorkRep(other) |
| 2111 | yc, ye = y.int, y.exp |
| 2112 | while yc % 10 == 0: |
| 2113 | yc //= 10 |
| 2114 | ye += 1 |
| 2115 | |
| 2116 | # case where xc == 1: result is 10**(xe*y), with xe*y |
| 2117 | # required to be an integer |
| 2118 | if xc == 1: |
Mark Dickinson | a123631 | 2010-07-08 19:03:34 +0000 | [diff] [blame] | 2119 | xe *= yc |
| 2120 | # result is now 10**(xe * 10**ye); xe * 10**ye must be integral |
| 2121 | while xe % 10 == 0: |
| 2122 | xe //= 10 |
| 2123 | ye += 1 |
| 2124 | if ye < 0: |
| 2125 | return None |
| 2126 | exponent = xe * 10**ye |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2127 | if y.sign == 1: |
| 2128 | exponent = -exponent |
| 2129 | # if other is a nonnegative integer, use ideal exponent |
| 2130 | if other._isinteger() and other._sign == 0: |
| 2131 | ideal_exponent = self._exp*int(other) |
| 2132 | zeros = min(exponent-ideal_exponent, p-1) |
| 2133 | else: |
| 2134 | zeros = 0 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2135 | return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2136 | |
| 2137 | # case where y is negative: xc must be either a power |
| 2138 | # of 2 or a power of 5. |
| 2139 | if y.sign == 1: |
| 2140 | last_digit = xc % 10 |
| 2141 | if last_digit in (2,4,6,8): |
| 2142 | # quick test for power of 2 |
| 2143 | if xc & -xc != xc: |
| 2144 | return None |
| 2145 | # now xc is a power of 2; e is its exponent |
| 2146 | e = _nbits(xc)-1 |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2147 | |
Mark Dickinson | 7ce0fa8 | 2011-06-04 18:14:23 +0100 | [diff] [blame] | 2148 | # We now have: |
| 2149 | # |
| 2150 | # x = 2**e * 10**xe, e > 0, and y < 0. |
| 2151 | # |
| 2152 | # The exact result is: |
| 2153 | # |
| 2154 | # x**y = 5**(-e*y) * 10**(e*y + xe*y) |
| 2155 | # |
| 2156 | # provided that both e*y and xe*y are integers. Note that if |
| 2157 | # 5**(-e*y) >= 10**p, then the result can't be expressed |
| 2158 | # exactly with p digits of precision. |
| 2159 | # |
| 2160 | # Using the above, we can guard against large values of ye. |
| 2161 | # 93/65 is an upper bound for log(10)/log(5), so if |
| 2162 | # |
| 2163 | # ye >= len(str(93*p//65)) |
| 2164 | # |
| 2165 | # then |
| 2166 | # |
| 2167 | # -e*y >= -y >= 10**ye > 93*p/65 > p*log(10)/log(5), |
| 2168 | # |
| 2169 | # so 5**(-e*y) >= 10**p, and the coefficient of the result |
| 2170 | # can't be expressed in p digits. |
| 2171 | |
| 2172 | # emax >= largest e such that 5**e < 10**p. |
| 2173 | emax = p*93//65 |
| 2174 | if ye >= len(str(emax)): |
| 2175 | return None |
| 2176 | |
| 2177 | # Find -e*y and -xe*y; both must be integers |
| 2178 | e = _decimal_lshift_exact(e * yc, ye) |
| 2179 | xe = _decimal_lshift_exact(xe * yc, ye) |
| 2180 | if e is None or xe is None: |
| 2181 | return None |
| 2182 | |
| 2183 | if e > emax: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2184 | return None |
| 2185 | xc = 5**e |
| 2186 | |
| 2187 | elif last_digit == 5: |
| 2188 | # e >= log_5(xc) if xc is a power of 5; we have |
| 2189 | # equality all the way up to xc=5**2658 |
| 2190 | e = _nbits(xc)*28//65 |
| 2191 | xc, remainder = divmod(5**e, xc) |
| 2192 | if remainder: |
| 2193 | return None |
| 2194 | while xc % 5 == 0: |
| 2195 | xc //= 5 |
| 2196 | e -= 1 |
Mark Dickinson | 7ce0fa8 | 2011-06-04 18:14:23 +0100 | [diff] [blame] | 2197 | |
| 2198 | # Guard against large values of ye, using the same logic as in |
| 2199 | # the 'xc is a power of 2' branch. 10/3 is an upper bound for |
| 2200 | # log(10)/log(2). |
| 2201 | emax = p*10//3 |
| 2202 | if ye >= len(str(emax)): |
| 2203 | return None |
| 2204 | |
| 2205 | e = _decimal_lshift_exact(e * yc, ye) |
| 2206 | xe = _decimal_lshift_exact(xe * yc, ye) |
| 2207 | if e is None or xe is None: |
| 2208 | return None |
| 2209 | |
| 2210 | if e > emax: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2211 | return None |
| 2212 | xc = 2**e |
| 2213 | else: |
| 2214 | return None |
| 2215 | |
| 2216 | if xc >= 10**p: |
| 2217 | return None |
| 2218 | xe = -e-xe |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2219 | return _dec_from_triple(0, str(xc), xe) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2220 | |
| 2221 | # now y is positive; find m and n such that y = m/n |
| 2222 | if ye >= 0: |
| 2223 | m, n = yc*10**ye, 1 |
| 2224 | else: |
| 2225 | if xe != 0 and len(str(abs(yc*xe))) <= -ye: |
| 2226 | return None |
| 2227 | xc_bits = _nbits(xc) |
| 2228 | if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye: |
| 2229 | return None |
| 2230 | m, n = yc, 10**(-ye) |
| 2231 | while m % 2 == n % 2 == 0: |
| 2232 | m //= 2 |
| 2233 | n //= 2 |
| 2234 | while m % 5 == n % 5 == 0: |
| 2235 | m //= 5 |
| 2236 | n //= 5 |
| 2237 | |
| 2238 | # compute nth root of xc*10**xe |
| 2239 | if n > 1: |
| 2240 | # if 1 < xc < 2**n then xc isn't an nth power |
| 2241 | if xc != 1 and xc_bits <= n: |
| 2242 | return None |
| 2243 | |
| 2244 | xe, rem = divmod(xe, n) |
| 2245 | if rem != 0: |
| 2246 | return None |
| 2247 | |
| 2248 | # compute nth root of xc using Newton's method |
| 2249 | a = 1 << -(-_nbits(xc)//n) # initial estimate |
| 2250 | while True: |
| 2251 | q, r = divmod(xc, a**(n-1)) |
| 2252 | if a <= q: |
| 2253 | break |
| 2254 | else: |
| 2255 | a = (a*(n-1) + q)//n |
| 2256 | if not (a == q and r == 0): |
| 2257 | return None |
| 2258 | xc = a |
| 2259 | |
| 2260 | # now xc*10**xe is the nth root of the original xc*10**xe |
| 2261 | # compute mth power of xc*10**xe |
| 2262 | |
| 2263 | # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m > |
| 2264 | # 10**p and the result is not representable. |
| 2265 | if xc > 1 and m > p*100//_log10_lb(xc): |
| 2266 | return None |
| 2267 | xc = xc**m |
| 2268 | xe *= m |
| 2269 | if xc > 10**p: |
| 2270 | return None |
| 2271 | |
| 2272 | # by this point the result *is* exactly representable |
| 2273 | # adjust the exponent to get as close as possible to the ideal |
| 2274 | # exponent, if necessary |
| 2275 | str_xc = str(xc) |
| 2276 | if other._isinteger() and other._sign == 0: |
| 2277 | ideal_exponent = self._exp*int(other) |
| 2278 | zeros = min(xe-ideal_exponent, p-len(str_xc)) |
| 2279 | else: |
| 2280 | zeros = 0 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2281 | return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2282 | |
| 2283 | def __pow__(self, other, modulo=None, context=None): |
| 2284 | """Return self ** other [ % modulo]. |
| 2285 | |
| 2286 | With two arguments, compute self**other. |
| 2287 | |
| 2288 | With three arguments, compute (self**other) % modulo. For the |
| 2289 | three argument form, the following restrictions on the |
| 2290 | arguments hold: |
| 2291 | |
| 2292 | - all three arguments must be integral |
| 2293 | - other must be nonnegative |
| 2294 | - either self or other (or both) must be nonzero |
| 2295 | - modulo must be nonzero and must have at most p digits, |
| 2296 | where p is the context precision. |
| 2297 | |
| 2298 | If any of these restrictions is violated the InvalidOperation |
| 2299 | flag is raised. |
| 2300 | |
| 2301 | The result of pow(self, other, modulo) is identical to the |
| 2302 | result that would be obtained by computing (self**other) % |
| 2303 | modulo with unbounded precision, but is computed more |
| 2304 | efficiently. It is always exact. |
| 2305 | """ |
| 2306 | |
| 2307 | if modulo is not None: |
| 2308 | return self._power_modulo(other, modulo, context) |
| 2309 | |
| 2310 | other = _convert_other(other) |
| 2311 | if other is NotImplemented: |
| 2312 | return other |
| 2313 | |
| 2314 | if context is None: |
| 2315 | context = getcontext() |
| 2316 | |
| 2317 | # either argument is a NaN => result is NaN |
| 2318 | ans = self._check_nans(other, context) |
| 2319 | if ans: |
| 2320 | return ans |
| 2321 | |
| 2322 | # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity) |
| 2323 | if not other: |
| 2324 | if not self: |
| 2325 | return context._raise_error(InvalidOperation, '0 ** 0') |
| 2326 | else: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2327 | return _One |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2328 | |
| 2329 | # result has sign 1 iff self._sign is 1 and other is an odd integer |
| 2330 | result_sign = 0 |
| 2331 | if self._sign == 1: |
| 2332 | if other._isinteger(): |
| 2333 | if not other._iseven(): |
| 2334 | result_sign = 1 |
| 2335 | else: |
| 2336 | # -ve**noninteger = NaN |
| 2337 | # (-0)**noninteger = 0**noninteger |
| 2338 | if self: |
| 2339 | return context._raise_error(InvalidOperation, |
| 2340 | 'x ** y with x negative and y not an integer') |
| 2341 | # negate self, without doing any unwanted rounding |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2342 | self = self.copy_negate() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2343 | |
| 2344 | # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity |
| 2345 | if not self: |
| 2346 | if other._sign == 0: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2347 | return _dec_from_triple(result_sign, '0', 0) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2348 | else: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2349 | return _SignedInfinity[result_sign] |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2350 | |
| 2351 | # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2352 | if self._isinfinity(): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2353 | if other._sign == 0: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2354 | return _SignedInfinity[result_sign] |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2355 | else: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2356 | return _dec_from_triple(result_sign, '0', 0) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2357 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2358 | # 1**other = 1, but the choice of exponent and the flags |
| 2359 | # depend on the exponent of self, and on whether other is a |
| 2360 | # positive integer, a negative integer, or neither |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2361 | if self == _One: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2362 | if other._isinteger(): |
| 2363 | # exp = max(self._exp*max(int(other), 0), |
| 2364 | # 1-context.prec) but evaluating int(other) directly |
| 2365 | # is dangerous until we know other is small (other |
| 2366 | # could be 1e999999999) |
| 2367 | if other._sign == 1: |
| 2368 | multiplier = 0 |
| 2369 | elif other > context.prec: |
| 2370 | multiplier = context.prec |
| 2371 | else: |
| 2372 | multiplier = int(other) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2373 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2374 | exp = self._exp * multiplier |
| 2375 | if exp < 1-context.prec: |
| 2376 | exp = 1-context.prec |
| 2377 | context._raise_error(Rounded) |
| 2378 | else: |
| 2379 | context._raise_error(Inexact) |
| 2380 | context._raise_error(Rounded) |
| 2381 | exp = 1-context.prec |
| 2382 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2383 | return _dec_from_triple(result_sign, '1'+'0'*-exp, exp) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2384 | |
| 2385 | # compute adjusted exponent of self |
| 2386 | self_adj = self.adjusted() |
| 2387 | |
| 2388 | # self ** infinity is infinity if self > 1, 0 if self < 1 |
| 2389 | # self ** -infinity is infinity if self < 1, 0 if self > 1 |
| 2390 | if other._isinfinity(): |
| 2391 | if (other._sign == 0) == (self_adj < 0): |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2392 | return _dec_from_triple(result_sign, '0', 0) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2393 | else: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2394 | return _SignedInfinity[result_sign] |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2395 | |
| 2396 | # from here on, the result always goes through the call |
| 2397 | # to _fix at the end of this function. |
| 2398 | ans = None |
Mark Dickinson | c69160e | 2010-05-04 14:35:33 +0000 | [diff] [blame] | 2399 | exact = False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2400 | |
| 2401 | # crude test to catch cases of extreme overflow/underflow. If |
| 2402 | # log10(self)*other >= 10**bound and bound >= len(str(Emax)) |
| 2403 | # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence |
| 2404 | # self**other >= 10**(Emax+1), so overflow occurs. The test |
| 2405 | # for underflow is similar. |
| 2406 | bound = self._log10_exp_bound() + other.adjusted() |
| 2407 | if (self_adj >= 0) == (other._sign == 0): |
| 2408 | # self > 1 and other +ve, or self < 1 and other -ve |
| 2409 | # possibility of overflow |
| 2410 | if bound >= len(str(context.Emax)): |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2411 | ans = _dec_from_triple(result_sign, '1', context.Emax+1) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2412 | else: |
| 2413 | # self > 1 and other -ve, or self < 1 and other +ve |
| 2414 | # possibility of underflow to 0 |
| 2415 | Etiny = context.Etiny() |
| 2416 | if bound >= len(str(-Etiny)): |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2417 | ans = _dec_from_triple(result_sign, '1', Etiny-1) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2418 | |
| 2419 | # try for an exact result with precision +1 |
| 2420 | if ans is None: |
| 2421 | ans = self._power_exact(other, context.prec + 1) |
Mark Dickinson | e42f1bb | 2010-07-08 19:09:16 +0000 | [diff] [blame] | 2422 | if ans is not None: |
| 2423 | if result_sign == 1: |
| 2424 | ans = _dec_from_triple(1, ans._int, ans._exp) |
| 2425 | exact = True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2426 | |
| 2427 | # usual case: inexact result, x**y computed directly as exp(y*log(x)) |
| 2428 | if ans is None: |
| 2429 | p = context.prec |
| 2430 | x = _WorkRep(self) |
| 2431 | xc, xe = x.int, x.exp |
| 2432 | y = _WorkRep(other) |
| 2433 | yc, ye = y.int, y.exp |
| 2434 | if y.sign == 1: |
| 2435 | yc = -yc |
| 2436 | |
| 2437 | # compute correctly rounded result: start with precision +3, |
| 2438 | # then increase precision until result is unambiguously roundable |
| 2439 | extra = 3 |
| 2440 | while True: |
| 2441 | coeff, exp = _dpower(xc, xe, yc, ye, p+extra) |
| 2442 | if coeff % (5*10**(len(str(coeff))-p-1)): |
| 2443 | break |
| 2444 | extra += 3 |
| 2445 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2446 | ans = _dec_from_triple(result_sign, str(coeff), exp) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2447 | |
Mark Dickinson | c69160e | 2010-05-04 14:35:33 +0000 | [diff] [blame] | 2448 | # unlike exp, ln and log10, the power function respects the |
| 2449 | # rounding mode; no need to switch to ROUND_HALF_EVEN here |
| 2450 | |
| 2451 | # There's a difficulty here when 'other' is not an integer and |
| 2452 | # the result is exact. In this case, the specification |
| 2453 | # requires that the Inexact flag be raised (in spite of |
| 2454 | # exactness), but since the result is exact _fix won't do this |
| 2455 | # for us. (Correspondingly, the Underflow signal should also |
| 2456 | # be raised for subnormal results.) We can't directly raise |
| 2457 | # these signals either before or after calling _fix, since |
| 2458 | # that would violate the precedence for signals. So we wrap |
| 2459 | # the ._fix call in a temporary context, and reraise |
| 2460 | # afterwards. |
| 2461 | if exact and not other._isinteger(): |
| 2462 | # pad with zeros up to length context.prec+1 if necessary; this |
| 2463 | # ensures that the Rounded signal will be raised. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2464 | if len(ans._int) <= context.prec: |
Mark Dickinson | c69160e | 2010-05-04 14:35:33 +0000 | [diff] [blame] | 2465 | expdiff = context.prec + 1 - len(ans._int) |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2466 | ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff, |
| 2467 | ans._exp-expdiff) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2468 | |
Mark Dickinson | c69160e | 2010-05-04 14:35:33 +0000 | [diff] [blame] | 2469 | # create a copy of the current context, with cleared flags/traps |
| 2470 | newcontext = context.copy() |
| 2471 | newcontext.clear_flags() |
| 2472 | for exception in _signals: |
| 2473 | newcontext.traps[exception] = 0 |
| 2474 | |
| 2475 | # round in the new context |
| 2476 | ans = ans._fix(newcontext) |
| 2477 | |
| 2478 | # raise Inexact, and if necessary, Underflow |
| 2479 | newcontext._raise_error(Inexact) |
| 2480 | if newcontext.flags[Subnormal]: |
| 2481 | newcontext._raise_error(Underflow) |
| 2482 | |
| 2483 | # propagate signals to the original context; _fix could |
| 2484 | # have raised any of Overflow, Underflow, Subnormal, |
| 2485 | # Inexact, Rounded, Clamped. Overflow needs the correct |
| 2486 | # arguments. Note that the order of the exceptions is |
| 2487 | # important here. |
| 2488 | if newcontext.flags[Overflow]: |
| 2489 | context._raise_error(Overflow, 'above Emax', ans._sign) |
| 2490 | for exception in Underflow, Subnormal, Inexact, Rounded, Clamped: |
| 2491 | if newcontext.flags[exception]: |
| 2492 | context._raise_error(exception) |
| 2493 | |
| 2494 | else: |
| 2495 | ans = ans._fix(context) |
| 2496 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2497 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2498 | |
| 2499 | def __rpow__(self, other, context=None): |
| 2500 | """Swaps self/other and returns __pow__.""" |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2501 | other = _convert_other(other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 2502 | if other is NotImplemented: |
| 2503 | return other |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2504 | return other.__pow__(self, context=context) |
| 2505 | |
| 2506 | def normalize(self, context=None): |
| 2507 | """Normalize- strip trailing 0s, change anything equal to 0 to 0e0""" |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2508 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2509 | if context is None: |
| 2510 | context = getcontext() |
| 2511 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2512 | if self._is_special: |
| 2513 | ans = self._check_nans(context=context) |
| 2514 | if ans: |
| 2515 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2516 | |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 2517 | dup = self._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2518 | if dup._isinfinity(): |
| 2519 | return dup |
| 2520 | |
| 2521 | if not dup: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2522 | return _dec_from_triple(dup._sign, '0', 0) |
Mark Dickinson | b1d8e32 | 2010-05-22 18:35:36 +0000 | [diff] [blame] | 2523 | exp_max = [context.Emax, context.Etop()][context.clamp] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2524 | end = len(dup._int) |
| 2525 | exp = dup._exp |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2526 | while dup._int[end-1] == '0' and exp < exp_max: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2527 | exp += 1 |
| 2528 | end -= 1 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2529 | return _dec_from_triple(dup._sign, dup._int[:end], exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2530 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2531 | def quantize(self, exp, rounding=None, context=None, watchexp=True): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2532 | """Quantize self so its exponent is the same as that of exp. |
| 2533 | |
| 2534 | Similar to self._rescale(exp._exp) but with error checking. |
| 2535 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2536 | exp = _convert_other(exp, raiseit=True) |
| 2537 | |
| 2538 | if context is None: |
| 2539 | context = getcontext() |
| 2540 | if rounding is None: |
| 2541 | rounding = context.rounding |
| 2542 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2543 | if self._is_special or exp._is_special: |
| 2544 | ans = self._check_nans(exp, context) |
| 2545 | if ans: |
| 2546 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2547 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2548 | if exp._isinfinity() or self._isinfinity(): |
| 2549 | if exp._isinfinity() and self._isinfinity(): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2550 | return Decimal(self) # if both are inf, it is OK |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2551 | return context._raise_error(InvalidOperation, |
| 2552 | 'quantize with one INF') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2553 | |
| 2554 | # if we're not watching exponents, do a simple rescale |
| 2555 | if not watchexp: |
| 2556 | ans = self._rescale(exp._exp, rounding) |
| 2557 | # raise Inexact and Rounded where appropriate |
| 2558 | if ans._exp > self._exp: |
| 2559 | context._raise_error(Rounded) |
| 2560 | if ans != self: |
| 2561 | context._raise_error(Inexact) |
| 2562 | return ans |
| 2563 | |
| 2564 | # exp._exp should be between Etiny and Emax |
| 2565 | if not (context.Etiny() <= exp._exp <= context.Emax): |
| 2566 | return context._raise_error(InvalidOperation, |
| 2567 | 'target exponent out of bounds in quantize') |
| 2568 | |
| 2569 | if not self: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2570 | ans = _dec_from_triple(self._sign, '0', exp._exp) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2571 | return ans._fix(context) |
| 2572 | |
| 2573 | self_adjusted = self.adjusted() |
| 2574 | if self_adjusted > context.Emax: |
| 2575 | return context._raise_error(InvalidOperation, |
| 2576 | 'exponent of quantize result too large for current context') |
| 2577 | if self_adjusted - exp._exp + 1 > context.prec: |
| 2578 | return context._raise_error(InvalidOperation, |
| 2579 | 'quantize result has too many digits for current context') |
| 2580 | |
| 2581 | ans = self._rescale(exp._exp, rounding) |
| 2582 | if ans.adjusted() > context.Emax: |
| 2583 | return context._raise_error(InvalidOperation, |
| 2584 | 'exponent of quantize result too large for current context') |
| 2585 | if len(ans._int) > context.prec: |
| 2586 | return context._raise_error(InvalidOperation, |
| 2587 | 'quantize result has too many digits for current context') |
| 2588 | |
| 2589 | # raise appropriate flags |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2590 | if ans and ans.adjusted() < context.Emin: |
| 2591 | context._raise_error(Subnormal) |
Mark Dickinson | c69160e | 2010-05-04 14:35:33 +0000 | [diff] [blame] | 2592 | if ans._exp > self._exp: |
| 2593 | if ans != self: |
| 2594 | context._raise_error(Inexact) |
| 2595 | context._raise_error(Rounded) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2596 | |
Mark Dickinson | c69160e | 2010-05-04 14:35:33 +0000 | [diff] [blame] | 2597 | # call to fix takes care of any necessary folddown, and |
| 2598 | # signals Clamped if necessary |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2599 | ans = ans._fix(context) |
| 2600 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2601 | |
Stefan Krah | 040e311 | 2012-12-15 22:33:33 +0100 | [diff] [blame] | 2602 | def same_quantum(self, other, context=None): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2603 | """Return True if self and other have the same exponent; otherwise |
| 2604 | return False. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2605 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2606 | If either operand is a special value, the following rules are used: |
| 2607 | * return True if both operands are infinities |
| 2608 | * return True if both operands are NaNs |
| 2609 | * otherwise, return False. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2610 | """ |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2611 | other = _convert_other(other, raiseit=True) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2612 | if self._is_special or other._is_special: |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 2613 | return (self.is_nan() and other.is_nan() or |
| 2614 | self.is_infinite() and other.is_infinite()) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2615 | return self._exp == other._exp |
| 2616 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2617 | def _rescale(self, exp, rounding): |
| 2618 | """Rescale self so that the exponent is exp, either by padding with zeros |
| 2619 | or by truncating digits, using the given rounding mode. |
| 2620 | |
| 2621 | Specials are returned without change. This operation is |
| 2622 | quiet: it raises no flags, and uses no information from the |
| 2623 | context. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2624 | |
| 2625 | exp = exp to scale to (an integer) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2626 | rounding = rounding mode |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2627 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2628 | if self._is_special: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2629 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2630 | if not self: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2631 | return _dec_from_triple(self._sign, '0', exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2632 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2633 | if self._exp >= exp: |
| 2634 | # pad answer with zeros if necessary |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2635 | return _dec_from_triple(self._sign, |
| 2636 | self._int + '0'*(self._exp - exp), exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2637 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2638 | # too many digits; round and lose data. If self.adjusted() < |
| 2639 | # exp-1, replace self by 10**(exp-1) before rounding |
| 2640 | digits = len(self._int) + self._exp - exp |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2641 | if digits < 0: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2642 | self = _dec_from_triple(self._sign, '1', exp-1) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2643 | digits = 0 |
Alexander Belopolsky | 1a20c12 | 2011-04-12 23:03:39 -0400 | [diff] [blame] | 2644 | this_function = self._pick_rounding_function[rounding] |
| 2645 | changed = this_function(self, digits) |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 2646 | coeff = self._int[:digits] or '0' |
| 2647 | if changed == 1: |
| 2648 | coeff = str(int(coeff)+1) |
| 2649 | return _dec_from_triple(self._sign, coeff, exp) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2650 | |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 2651 | def _round(self, places, rounding): |
| 2652 | """Round a nonzero, nonspecial Decimal to a fixed number of |
| 2653 | significant figures, using the given rounding mode. |
| 2654 | |
| 2655 | Infinities, NaNs and zeros are returned unaltered. |
| 2656 | |
| 2657 | This operation is quiet: it raises no flags, and uses no |
| 2658 | information from the context. |
| 2659 | |
| 2660 | """ |
| 2661 | if places <= 0: |
| 2662 | raise ValueError("argument should be at least 1 in _round") |
| 2663 | if self._is_special or not self: |
| 2664 | return Decimal(self) |
| 2665 | ans = self._rescale(self.adjusted()+1-places, rounding) |
| 2666 | # it can happen that the rescale alters the adjusted exponent; |
| 2667 | # for example when rounding 99.97 to 3 significant figures. |
| 2668 | # When this happens we end up with an extra 0 at the end of |
| 2669 | # the number; a second rescale fixes this. |
| 2670 | if ans.adjusted() != self.adjusted(): |
| 2671 | ans = ans._rescale(ans.adjusted()+1-places, rounding) |
| 2672 | return ans |
| 2673 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2674 | def to_integral_exact(self, rounding=None, context=None): |
| 2675 | """Rounds to a nearby integer. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2676 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2677 | If no rounding mode is specified, take the rounding mode from |
| 2678 | the context. This method raises the Rounded and Inexact flags |
| 2679 | when appropriate. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2680 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2681 | See also: to_integral_value, which does exactly the same as |
| 2682 | this method except that it doesn't raise Inexact or Rounded. |
| 2683 | """ |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2684 | if self._is_special: |
| 2685 | ans = self._check_nans(context=context) |
| 2686 | if ans: |
| 2687 | return ans |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2688 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2689 | if self._exp >= 0: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2690 | return Decimal(self) |
| 2691 | if not self: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2692 | return _dec_from_triple(self._sign, '0', 0) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2693 | if context is None: |
| 2694 | context = getcontext() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2695 | if rounding is None: |
| 2696 | rounding = context.rounding |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2697 | ans = self._rescale(0, rounding) |
| 2698 | if ans != self: |
| 2699 | context._raise_error(Inexact) |
Mark Dickinson | c69160e | 2010-05-04 14:35:33 +0000 | [diff] [blame] | 2700 | context._raise_error(Rounded) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2701 | return ans |
| 2702 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2703 | def to_integral_value(self, rounding=None, context=None): |
| 2704 | """Rounds to the nearest integer, without raising inexact, rounded.""" |
| 2705 | if context is None: |
| 2706 | context = getcontext() |
| 2707 | if rounding is None: |
| 2708 | rounding = context.rounding |
| 2709 | if self._is_special: |
| 2710 | ans = self._check_nans(context=context) |
| 2711 | if ans: |
| 2712 | return ans |
| 2713 | return Decimal(self) |
| 2714 | if self._exp >= 0: |
| 2715 | return Decimal(self) |
| 2716 | else: |
| 2717 | return self._rescale(0, rounding) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2718 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2719 | # the method name changed, but we provide also the old one, for compatibility |
| 2720 | to_integral = to_integral_value |
| 2721 | |
| 2722 | def sqrt(self, context=None): |
| 2723 | """Return the square root of self.""" |
Christian Heimes | 0348fb6 | 2008-03-26 12:55:56 +0000 | [diff] [blame] | 2724 | if context is None: |
| 2725 | context = getcontext() |
| 2726 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2727 | if self._is_special: |
| 2728 | ans = self._check_nans(context=context) |
| 2729 | if ans: |
| 2730 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2731 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2732 | if self._isinfinity() and self._sign == 0: |
| 2733 | return Decimal(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2734 | |
| 2735 | if not self: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2736 | # exponent = self._exp // 2. sqrt(-0) = -0 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2737 | ans = _dec_from_triple(self._sign, '0', self._exp // 2) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2738 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2739 | |
| 2740 | if self._sign == 1: |
| 2741 | return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0') |
| 2742 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2743 | # At this point self represents a positive number. Let p be |
| 2744 | # the desired precision and express self in the form c*100**e |
| 2745 | # with c a positive real number and e an integer, c and e |
| 2746 | # being chosen so that 100**(p-1) <= c < 100**p. Then the |
| 2747 | # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1) |
| 2748 | # <= sqrt(c) < 10**p, so the closest representable Decimal at |
| 2749 | # precision p is n*10**e where n = round_half_even(sqrt(c)), |
| 2750 | # the closest integer to sqrt(c) with the even integer chosen |
| 2751 | # in the case of a tie. |
| 2752 | # |
| 2753 | # To ensure correct rounding in all cases, we use the |
| 2754 | # following trick: we compute the square root to an extra |
| 2755 | # place (precision p+1 instead of precision p), rounding down. |
| 2756 | # Then, if the result is inexact and its last digit is 0 or 5, |
| 2757 | # we increase the last digit to 1 or 6 respectively; if it's |
| 2758 | # exact we leave the last digit alone. Now the final round to |
| 2759 | # p places (or fewer in the case of underflow) will round |
| 2760 | # correctly and raise the appropriate flags. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2761 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2762 | # use an extra digit of precision |
| 2763 | prec = context.prec+1 |
| 2764 | |
| 2765 | # write argument in the form c*100**e where e = self._exp//2 |
| 2766 | # is the 'ideal' exponent, to be used if the square root is |
| 2767 | # exactly representable. l is the number of 'digits' of c in |
| 2768 | # base 100, so that 100**(l-1) <= c < 100**l. |
| 2769 | op = _WorkRep(self) |
| 2770 | e = op.exp >> 1 |
| 2771 | if op.exp & 1: |
| 2772 | c = op.int * 10 |
| 2773 | l = (len(self._int) >> 1) + 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2774 | else: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2775 | c = op.int |
| 2776 | l = len(self._int)+1 >> 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2777 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2778 | # rescale so that c has exactly prec base 100 'digits' |
| 2779 | shift = prec-l |
| 2780 | if shift >= 0: |
| 2781 | c *= 100**shift |
| 2782 | exact = True |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2783 | else: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2784 | c, remainder = divmod(c, 100**-shift) |
| 2785 | exact = not remainder |
| 2786 | e -= shift |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2787 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2788 | # find n = floor(sqrt(c)) using Newton's method |
| 2789 | n = 10**prec |
| 2790 | while True: |
| 2791 | q = c//n |
| 2792 | if n <= q: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2793 | break |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2794 | else: |
| 2795 | n = n + q >> 1 |
| 2796 | exact = exact and n*n == c |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2797 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2798 | if exact: |
| 2799 | # result is exact; rescale to use ideal exponent e |
| 2800 | if shift >= 0: |
| 2801 | # assert n % 10**shift == 0 |
| 2802 | n //= 10**shift |
| 2803 | else: |
| 2804 | n *= 10**-shift |
| 2805 | e += shift |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2806 | else: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2807 | # result is not exact; fix last digit as described above |
| 2808 | if n % 5 == 0: |
| 2809 | n += 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2810 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2811 | ans = _dec_from_triple(0, str(n), e) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2812 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2813 | # round, and fit to current context |
| 2814 | context = context._shallow_copy() |
| 2815 | rounding = context._set_rounding(ROUND_HALF_EVEN) |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 2816 | ans = ans._fix(context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2817 | context.rounding = rounding |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2818 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2819 | return ans |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2820 | |
| 2821 | def max(self, other, context=None): |
| 2822 | """Returns the larger value. |
| 2823 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2824 | Like max(self, other) except if one is not a number, returns |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2825 | NaN (and signals if one is sNaN). Also rounds. |
| 2826 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2827 | other = _convert_other(other, raiseit=True) |
| 2828 | |
| 2829 | if context is None: |
| 2830 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2831 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2832 | if self._is_special or other._is_special: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2833 | # 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] | 2834 | # number is always returned |
| 2835 | sn = self._isnan() |
| 2836 | on = other._isnan() |
| 2837 | if sn or on: |
Facundo Batista | 708d581 | 2008-12-11 04:20:07 +0000 | [diff] [blame] | 2838 | if on == 1 and sn == 0: |
| 2839 | return self._fix(context) |
| 2840 | if sn == 1 and on == 0: |
| 2841 | return other._fix(context) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2842 | return self._check_nans(other, context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2843 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 2844 | c = self._cmp(other) |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2845 | if c == 0: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2846 | # If both operands are finite and equal in numerical value |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2847 | # then an ordering is applied: |
| 2848 | # |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2849 | # If the signs differ then max returns the operand with the |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2850 | # positive sign and min returns the operand with the negative sign |
| 2851 | # |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2852 | # 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] | 2853 | # the result. This is exactly the ordering used in compare_total. |
| 2854 | c = self.compare_total(other) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2855 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2856 | if c == -1: |
| 2857 | ans = other |
| 2858 | else: |
| 2859 | ans = self |
| 2860 | |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 2861 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2862 | |
| 2863 | def min(self, other, context=None): |
| 2864 | """Returns the smaller value. |
| 2865 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2866 | Like min(self, other) except if one is not a number, returns |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2867 | NaN (and signals if one is sNaN). Also rounds. |
| 2868 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2869 | other = _convert_other(other, raiseit=True) |
| 2870 | |
| 2871 | if context is None: |
| 2872 | context = getcontext() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2873 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2874 | if self._is_special or other._is_special: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2875 | # 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] | 2876 | # number is always returned |
| 2877 | sn = self._isnan() |
| 2878 | on = other._isnan() |
| 2879 | if sn or on: |
Facundo Batista | 708d581 | 2008-12-11 04:20:07 +0000 | [diff] [blame] | 2880 | if on == 1 and sn == 0: |
| 2881 | return self._fix(context) |
| 2882 | if sn == 1 and on == 0: |
| 2883 | return other._fix(context) |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2884 | return self._check_nans(other, context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2885 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 2886 | c = self._cmp(other) |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 2887 | if c == 0: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2888 | c = self.compare_total(other) |
| 2889 | |
| 2890 | if c == -1: |
| 2891 | ans = self |
| 2892 | else: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2893 | ans = other |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 2894 | |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 2895 | return ans._fix(context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2896 | |
| 2897 | def _isinteger(self): |
| 2898 | """Returns whether self is an integer""" |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2899 | if self._is_special: |
| 2900 | return False |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2901 | if self._exp >= 0: |
| 2902 | return True |
| 2903 | rest = self._int[self._exp:] |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2904 | return rest == '0'*len(rest) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2905 | |
| 2906 | def _iseven(self): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2907 | """Returns True if self is even. Assumes self is an integer.""" |
| 2908 | if not self or self._exp > 0: |
| 2909 | return True |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 2910 | return self._int[-1+self._exp] in '02468' |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2911 | |
| 2912 | def adjusted(self): |
| 2913 | """Return the adjusted exponent of self""" |
| 2914 | try: |
| 2915 | return self._exp + len(self._int) - 1 |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2916 | # If NaN or Infinity, self._exp is string |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 2917 | except TypeError: |
| 2918 | return 0 |
| 2919 | |
Stefan Krah | 040e311 | 2012-12-15 22:33:33 +0100 | [diff] [blame] | 2920 | def canonical(self): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2921 | """Returns the same Decimal object. |
| 2922 | |
| 2923 | As we do not have different encodings for the same number, the |
| 2924 | received object already is in its canonical form. |
| 2925 | """ |
| 2926 | return self |
| 2927 | |
| 2928 | def compare_signal(self, other, context=None): |
| 2929 | """Compares self to the other operand numerically. |
| 2930 | |
| 2931 | It's pretty much like compare(), but all NaNs signal, with signaling |
| 2932 | NaNs taking precedence over quiet NaNs. |
| 2933 | """ |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 2934 | other = _convert_other(other, raiseit = True) |
| 2935 | ans = self._compare_check_nans(other, context) |
| 2936 | if ans: |
| 2937 | return ans |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2938 | return self.compare(other, context=context) |
| 2939 | |
Stefan Krah | 040e311 | 2012-12-15 22:33:33 +0100 | [diff] [blame] | 2940 | def compare_total(self, other, context=None): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2941 | """Compares self to other using the abstract representations. |
| 2942 | |
| 2943 | This is not like the standard compare, which use their numerical |
| 2944 | value. Note that a total ordering is defined for all possible abstract |
| 2945 | representations. |
| 2946 | """ |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 2947 | other = _convert_other(other, raiseit=True) |
| 2948 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2949 | # if one is negative and the other is positive, it's easy |
| 2950 | if self._sign and not other._sign: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2951 | return _NegativeOne |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2952 | if not self._sign and other._sign: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2953 | return _One |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2954 | sign = self._sign |
| 2955 | |
| 2956 | # let's handle both NaN types |
| 2957 | self_nan = self._isnan() |
| 2958 | other_nan = other._isnan() |
| 2959 | if self_nan or other_nan: |
| 2960 | if self_nan == other_nan: |
Mark Dickinson | d314e1b | 2009-08-28 13:39:53 +0000 | [diff] [blame] | 2961 | # compare payloads as though they're integers |
| 2962 | self_key = len(self._int), self._int |
| 2963 | other_key = len(other._int), other._int |
| 2964 | if self_key < other_key: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2965 | if sign: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2966 | return _One |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2967 | else: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2968 | return _NegativeOne |
Mark Dickinson | d314e1b | 2009-08-28 13:39:53 +0000 | [diff] [blame] | 2969 | if self_key > other_key: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2970 | if sign: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2971 | return _NegativeOne |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2972 | else: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2973 | return _One |
| 2974 | return _Zero |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2975 | |
| 2976 | if sign: |
| 2977 | if self_nan == 1: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2978 | return _NegativeOne |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2979 | if other_nan == 1: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2980 | return _One |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2981 | if self_nan == 2: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2982 | return _NegativeOne |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2983 | if other_nan == 2: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2984 | return _One |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2985 | else: |
| 2986 | if self_nan == 1: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2987 | return _One |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2988 | if other_nan == 1: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2989 | return _NegativeOne |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2990 | if self_nan == 2: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2991 | return _One |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2992 | if other_nan == 2: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2993 | return _NegativeOne |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2994 | |
| 2995 | if self < other: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2996 | return _NegativeOne |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2997 | if self > other: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 2998 | return _One |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 2999 | |
| 3000 | if self._exp < other._exp: |
| 3001 | if sign: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3002 | return _One |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3003 | else: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3004 | return _NegativeOne |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3005 | if self._exp > other._exp: |
| 3006 | if sign: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3007 | return _NegativeOne |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3008 | else: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3009 | return _One |
| 3010 | return _Zero |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3011 | |
| 3012 | |
Stefan Krah | 040e311 | 2012-12-15 22:33:33 +0100 | [diff] [blame] | 3013 | def compare_total_mag(self, other, context=None): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3014 | """Compares self to other using abstract repr., ignoring sign. |
| 3015 | |
| 3016 | Like compare_total, but with operand's sign ignored and assumed to be 0. |
| 3017 | """ |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 3018 | other = _convert_other(other, raiseit=True) |
| 3019 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3020 | s = self.copy_abs() |
| 3021 | o = other.copy_abs() |
| 3022 | return s.compare_total(o) |
| 3023 | |
| 3024 | def copy_abs(self): |
| 3025 | """Returns a copy with the sign set to 0. """ |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3026 | return _dec_from_triple(0, self._int, self._exp, self._is_special) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3027 | |
| 3028 | def copy_negate(self): |
| 3029 | """Returns a copy with the sign inverted.""" |
| 3030 | if self._sign: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3031 | return _dec_from_triple(0, self._int, self._exp, self._is_special) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3032 | else: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3033 | return _dec_from_triple(1, self._int, self._exp, self._is_special) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3034 | |
Stefan Krah | 040e311 | 2012-12-15 22:33:33 +0100 | [diff] [blame] | 3035 | def copy_sign(self, other, context=None): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3036 | """Returns self with the sign of other.""" |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 3037 | other = _convert_other(other, raiseit=True) |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3038 | return _dec_from_triple(other._sign, self._int, |
| 3039 | self._exp, self._is_special) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3040 | |
| 3041 | def exp(self, context=None): |
| 3042 | """Returns e ** self.""" |
| 3043 | |
| 3044 | if context is None: |
| 3045 | context = getcontext() |
| 3046 | |
| 3047 | # exp(NaN) = NaN |
| 3048 | ans = self._check_nans(context=context) |
| 3049 | if ans: |
| 3050 | return ans |
| 3051 | |
| 3052 | # exp(-Infinity) = 0 |
| 3053 | if self._isinfinity() == -1: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3054 | return _Zero |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3055 | |
| 3056 | # exp(0) = 1 |
| 3057 | if not self: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3058 | return _One |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3059 | |
| 3060 | # exp(Infinity) = Infinity |
| 3061 | if self._isinfinity() == 1: |
| 3062 | return Decimal(self) |
| 3063 | |
| 3064 | # the result is now guaranteed to be inexact (the true |
| 3065 | # mathematical result is transcendental). There's no need to |
| 3066 | # raise Rounded and Inexact here---they'll always be raised as |
| 3067 | # a result of the call to _fix. |
| 3068 | p = context.prec |
| 3069 | adj = self.adjusted() |
| 3070 | |
| 3071 | # we only need to do any computation for quite a small range |
| 3072 | # of adjusted exponents---for example, -29 <= adj <= 10 for |
| 3073 | # the default context. For smaller exponent the result is |
| 3074 | # indistinguishable from 1 at the given precision, while for |
| 3075 | # larger exponent the result either overflows or underflows. |
| 3076 | if self._sign == 0 and adj > len(str((context.Emax+1)*3)): |
| 3077 | # overflow |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3078 | ans = _dec_from_triple(0, '1', context.Emax+1) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3079 | elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)): |
| 3080 | # underflow to 0 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3081 | ans = _dec_from_triple(0, '1', context.Etiny()-1) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3082 | elif self._sign == 0 and adj < -p: |
| 3083 | # p+1 digits; final round will raise correct flags |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3084 | ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3085 | elif self._sign == 1 and adj < -p-1: |
| 3086 | # p+1 digits; final round will raise correct flags |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3087 | ans = _dec_from_triple(0, '9'*(p+1), -p-1) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3088 | # general case |
| 3089 | else: |
| 3090 | op = _WorkRep(self) |
| 3091 | c, e = op.int, op.exp |
| 3092 | if op.sign == 1: |
| 3093 | c = -c |
| 3094 | |
| 3095 | # compute correctly rounded result: increase precision by |
| 3096 | # 3 digits at a time until we get an unambiguously |
| 3097 | # roundable result |
| 3098 | extra = 3 |
| 3099 | while True: |
| 3100 | coeff, exp = _dexp(c, e, p+extra) |
| 3101 | if coeff % (5*10**(len(str(coeff))-p-1)): |
| 3102 | break |
| 3103 | extra += 3 |
| 3104 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3105 | ans = _dec_from_triple(0, str(coeff), exp) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3106 | |
| 3107 | # at this stage, ans should round correctly with *any* |
| 3108 | # rounding mode, not just with ROUND_HALF_EVEN |
| 3109 | context = context._shallow_copy() |
| 3110 | rounding = context._set_rounding(ROUND_HALF_EVEN) |
| 3111 | ans = ans._fix(context) |
| 3112 | context.rounding = rounding |
| 3113 | |
| 3114 | return ans |
| 3115 | |
| 3116 | def is_canonical(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3117 | """Return True if self is canonical; otherwise return False. |
| 3118 | |
| 3119 | Currently, the encoding of a Decimal instance is always |
| 3120 | canonical, so this method returns True for any Decimal. |
| 3121 | """ |
| 3122 | return True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3123 | |
| 3124 | def is_finite(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3125 | """Return True if self is finite; otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3126 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3127 | A Decimal instance is considered finite if it is neither |
| 3128 | infinite nor a NaN. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3129 | """ |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3130 | return not self._is_special |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3131 | |
| 3132 | def is_infinite(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3133 | """Return True if self is infinite; otherwise return False.""" |
| 3134 | return self._exp == 'F' |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3135 | |
| 3136 | def is_nan(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3137 | """Return True if self is a qNaN or sNaN; otherwise return False.""" |
| 3138 | return self._exp in ('n', 'N') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3139 | |
| 3140 | def is_normal(self, context=None): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3141 | """Return True if self is a normal number; otherwise return False.""" |
| 3142 | if self._is_special or not self: |
| 3143 | return False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3144 | if context is None: |
| 3145 | context = getcontext() |
Mark Dickinson | 06bb674 | 2009-10-20 13:38:04 +0000 | [diff] [blame] | 3146 | return context.Emin <= self.adjusted() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3147 | |
| 3148 | def is_qnan(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3149 | """Return True if self is a quiet NaN; otherwise return False.""" |
| 3150 | return self._exp == 'n' |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3151 | |
| 3152 | def is_signed(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3153 | """Return True if self is negative; otherwise return False.""" |
| 3154 | return self._sign == 1 |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3155 | |
| 3156 | def is_snan(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3157 | """Return True if self is a signaling NaN; otherwise return False.""" |
| 3158 | return self._exp == 'N' |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3159 | |
| 3160 | def is_subnormal(self, context=None): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3161 | """Return True if self is subnormal; otherwise return False.""" |
| 3162 | if self._is_special or not self: |
| 3163 | return False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3164 | if context is None: |
| 3165 | context = getcontext() |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3166 | return self.adjusted() < context.Emin |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3167 | |
| 3168 | def is_zero(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 3169 | """Return True if self is a zero; otherwise return False.""" |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3170 | return not self._is_special and self._int == '0' |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3171 | |
| 3172 | def _ln_exp_bound(self): |
| 3173 | """Compute a lower bound for the adjusted exponent of self.ln(). |
| 3174 | In other words, compute r such that self.ln() >= 10**r. Assumes |
| 3175 | that self is finite and positive and that self != 1. |
| 3176 | """ |
| 3177 | |
| 3178 | # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1 |
| 3179 | adj = self._exp + len(self._int) - 1 |
| 3180 | if adj >= 1: |
| 3181 | # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10) |
| 3182 | return len(str(adj*23//10)) - 1 |
| 3183 | if adj <= -2: |
| 3184 | # argument <= 0.1 |
| 3185 | return len(str((-1-adj)*23//10)) - 1 |
| 3186 | op = _WorkRep(self) |
| 3187 | c, e = op.int, op.exp |
| 3188 | if adj == 0: |
| 3189 | # 1 < self < 10 |
| 3190 | num = str(c-10**-e) |
| 3191 | den = str(c) |
| 3192 | return len(num) - len(den) - (num < den) |
| 3193 | # adj == -1, 0.1 <= self < 1 |
| 3194 | return e + len(str(10**-e - c)) - 1 |
| 3195 | |
| 3196 | |
| 3197 | def ln(self, context=None): |
| 3198 | """Returns the natural (base e) logarithm of self.""" |
| 3199 | |
| 3200 | if context is None: |
| 3201 | context = getcontext() |
| 3202 | |
| 3203 | # ln(NaN) = NaN |
| 3204 | ans = self._check_nans(context=context) |
| 3205 | if ans: |
| 3206 | return ans |
| 3207 | |
| 3208 | # ln(0.0) == -Infinity |
| 3209 | if not self: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3210 | return _NegativeInfinity |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3211 | |
| 3212 | # ln(Infinity) = Infinity |
| 3213 | if self._isinfinity() == 1: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3214 | return _Infinity |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3215 | |
| 3216 | # ln(1.0) == 0.0 |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3217 | if self == _One: |
| 3218 | return _Zero |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3219 | |
| 3220 | # ln(negative) raises InvalidOperation |
| 3221 | if self._sign == 1: |
| 3222 | return context._raise_error(InvalidOperation, |
| 3223 | 'ln of a negative value') |
| 3224 | |
| 3225 | # result is irrational, so necessarily inexact |
| 3226 | op = _WorkRep(self) |
| 3227 | c, e = op.int, op.exp |
| 3228 | p = context.prec |
| 3229 | |
| 3230 | # correctly rounded result: repeatedly increase precision by 3 |
| 3231 | # until we get an unambiguously roundable result |
| 3232 | places = p - self._ln_exp_bound() + 2 # at least p+3 places |
| 3233 | while True: |
| 3234 | coeff = _dlog(c, e, places) |
| 3235 | # assert len(str(abs(coeff)))-p >= 1 |
| 3236 | if coeff % (5*10**(len(str(abs(coeff)))-p-1)): |
| 3237 | break |
| 3238 | places += 3 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3239 | ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3240 | |
| 3241 | context = context._shallow_copy() |
| 3242 | rounding = context._set_rounding(ROUND_HALF_EVEN) |
| 3243 | ans = ans._fix(context) |
| 3244 | context.rounding = rounding |
| 3245 | return ans |
| 3246 | |
| 3247 | def _log10_exp_bound(self): |
| 3248 | """Compute a lower bound for the adjusted exponent of self.log10(). |
| 3249 | In other words, find r such that self.log10() >= 10**r. |
| 3250 | Assumes that self is finite and positive and that self != 1. |
| 3251 | """ |
| 3252 | |
| 3253 | # For x >= 10 or x < 0.1 we only need a bound on the integer |
| 3254 | # part of log10(self), and this comes directly from the |
| 3255 | # exponent of x. For 0.1 <= x <= 10 we use the inequalities |
| 3256 | # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| > |
| 3257 | # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0 |
| 3258 | |
| 3259 | adj = self._exp + len(self._int) - 1 |
| 3260 | if adj >= 1: |
| 3261 | # self >= 10 |
| 3262 | return len(str(adj))-1 |
| 3263 | if adj <= -2: |
| 3264 | # self < 0.1 |
| 3265 | return len(str(-1-adj))-1 |
| 3266 | op = _WorkRep(self) |
| 3267 | c, e = op.int, op.exp |
| 3268 | if adj == 0: |
| 3269 | # 1 < self < 10 |
| 3270 | num = str(c-10**-e) |
| 3271 | den = str(231*c) |
| 3272 | return len(num) - len(den) - (num < den) + 2 |
| 3273 | # adj == -1, 0.1 <= self < 1 |
| 3274 | num = str(10**-e-c) |
| 3275 | return len(num) + e - (num < "231") - 1 |
| 3276 | |
| 3277 | def log10(self, context=None): |
| 3278 | """Returns the base 10 logarithm of self.""" |
| 3279 | |
| 3280 | if context is None: |
| 3281 | context = getcontext() |
| 3282 | |
| 3283 | # log10(NaN) = NaN |
| 3284 | ans = self._check_nans(context=context) |
| 3285 | if ans: |
| 3286 | return ans |
| 3287 | |
| 3288 | # log10(0.0) == -Infinity |
| 3289 | if not self: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3290 | return _NegativeInfinity |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3291 | |
| 3292 | # log10(Infinity) = Infinity |
| 3293 | if self._isinfinity() == 1: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3294 | return _Infinity |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3295 | |
| 3296 | # log10(negative or -Infinity) raises InvalidOperation |
| 3297 | if self._sign == 1: |
| 3298 | return context._raise_error(InvalidOperation, |
| 3299 | 'log10 of a negative value') |
| 3300 | |
| 3301 | # log10(10**n) = n |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3302 | 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] | 3303 | # answer may need rounding |
| 3304 | ans = Decimal(self._exp + len(self._int) - 1) |
| 3305 | else: |
| 3306 | # result is irrational, so necessarily inexact |
| 3307 | op = _WorkRep(self) |
| 3308 | c, e = op.int, op.exp |
| 3309 | p = context.prec |
| 3310 | |
| 3311 | # correctly rounded result: repeatedly increase precision |
| 3312 | # until result is unambiguously roundable |
| 3313 | places = p-self._log10_exp_bound()+2 |
| 3314 | while True: |
| 3315 | coeff = _dlog10(c, e, places) |
| 3316 | # assert len(str(abs(coeff)))-p >= 1 |
| 3317 | if coeff % (5*10**(len(str(abs(coeff)))-p-1)): |
| 3318 | break |
| 3319 | places += 3 |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3320 | ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3321 | |
| 3322 | context = context._shallow_copy() |
| 3323 | rounding = context._set_rounding(ROUND_HALF_EVEN) |
| 3324 | ans = ans._fix(context) |
| 3325 | context.rounding = rounding |
| 3326 | return ans |
| 3327 | |
| 3328 | def logb(self, context=None): |
| 3329 | """ Returns the exponent of the magnitude of self's MSD. |
| 3330 | |
| 3331 | The result is the integer which is the exponent of the magnitude |
| 3332 | of the most significant digit of self (as though it were truncated |
| 3333 | to a single digit while maintaining the value of that digit and |
| 3334 | without limiting the resulting exponent). |
| 3335 | """ |
| 3336 | # logb(NaN) = NaN |
| 3337 | ans = self._check_nans(context=context) |
| 3338 | if ans: |
| 3339 | return ans |
| 3340 | |
| 3341 | if context is None: |
| 3342 | context = getcontext() |
| 3343 | |
| 3344 | # logb(+/-Inf) = +Inf |
| 3345 | if self._isinfinity(): |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3346 | return _Infinity |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3347 | |
| 3348 | # logb(0) = -Inf, DivisionByZero |
| 3349 | if not self: |
| 3350 | return context._raise_error(DivisionByZero, 'logb(0)', 1) |
| 3351 | |
| 3352 | # otherwise, simply return the adjusted exponent of self, as a |
| 3353 | # Decimal. Note that no attempt is made to fit the result |
| 3354 | # into the current context. |
Mark Dickinson | 56df887 | 2009-10-07 19:23:50 +0000 | [diff] [blame] | 3355 | ans = Decimal(self.adjusted()) |
| 3356 | return ans._fix(context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3357 | |
| 3358 | def _islogical(self): |
| 3359 | """Return True if self is a logical operand. |
| 3360 | |
Christian Heimes | 679db4a | 2008-01-18 09:56:22 +0000 | [diff] [blame] | 3361 | 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] | 3362 | an exponent of 0, and a coefficient whose digits must all be |
| 3363 | either 0 or 1. |
| 3364 | """ |
| 3365 | if self._sign != 0 or self._exp != 0: |
| 3366 | return False |
| 3367 | for dig in self._int: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3368 | if dig not in '01': |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3369 | return False |
| 3370 | return True |
| 3371 | |
| 3372 | def _fill_logical(self, context, opa, opb): |
| 3373 | dif = context.prec - len(opa) |
| 3374 | if dif > 0: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3375 | opa = '0'*dif + opa |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3376 | elif dif < 0: |
| 3377 | opa = opa[-context.prec:] |
| 3378 | dif = context.prec - len(opb) |
| 3379 | if dif > 0: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3380 | opb = '0'*dif + opb |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3381 | elif dif < 0: |
| 3382 | opb = opb[-context.prec:] |
| 3383 | return opa, opb |
| 3384 | |
| 3385 | def logical_and(self, other, context=None): |
| 3386 | """Applies an 'and' operation between self and other's digits.""" |
| 3387 | if context is None: |
| 3388 | context = getcontext() |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 3389 | |
| 3390 | other = _convert_other(other, raiseit=True) |
| 3391 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3392 | if not self._islogical() or not other._islogical(): |
| 3393 | return context._raise_error(InvalidOperation) |
| 3394 | |
| 3395 | # fill to context.prec |
| 3396 | (opa, opb) = self._fill_logical(context, self._int, other._int) |
| 3397 | |
| 3398 | # make the operation, and clean starting zeroes |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3399 | result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)]) |
| 3400 | return _dec_from_triple(0, result.lstrip('0') or '0', 0) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3401 | |
| 3402 | def logical_invert(self, context=None): |
| 3403 | """Invert all its digits.""" |
| 3404 | if context is None: |
| 3405 | context = getcontext() |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3406 | return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0), |
| 3407 | context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3408 | |
| 3409 | def logical_or(self, other, context=None): |
| 3410 | """Applies an 'or' operation between self and other's digits.""" |
| 3411 | if context is None: |
| 3412 | context = getcontext() |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 3413 | |
| 3414 | other = _convert_other(other, raiseit=True) |
| 3415 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3416 | if not self._islogical() or not other._islogical(): |
| 3417 | return context._raise_error(InvalidOperation) |
| 3418 | |
| 3419 | # fill to context.prec |
| 3420 | (opa, opb) = self._fill_logical(context, self._int, other._int) |
| 3421 | |
| 3422 | # make the operation, and clean starting zeroes |
Mark Dickinson | 315a20a | 2009-01-04 21:34:18 +0000 | [diff] [blame] | 3423 | 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] | 3424 | return _dec_from_triple(0, result.lstrip('0') or '0', 0) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3425 | |
| 3426 | def logical_xor(self, other, context=None): |
| 3427 | """Applies an 'xor' operation between self and other's digits.""" |
| 3428 | if context is None: |
| 3429 | context = getcontext() |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 3430 | |
| 3431 | other = _convert_other(other, raiseit=True) |
| 3432 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3433 | if not self._islogical() or not other._islogical(): |
| 3434 | return context._raise_error(InvalidOperation) |
| 3435 | |
| 3436 | # fill to context.prec |
| 3437 | (opa, opb) = self._fill_logical(context, self._int, other._int) |
| 3438 | |
| 3439 | # make the operation, and clean starting zeroes |
Mark Dickinson | 315a20a | 2009-01-04 21:34:18 +0000 | [diff] [blame] | 3440 | 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] | 3441 | return _dec_from_triple(0, result.lstrip('0') or '0', 0) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3442 | |
| 3443 | def max_mag(self, other, context=None): |
| 3444 | """Compares the values numerically with their sign ignored.""" |
| 3445 | other = _convert_other(other, raiseit=True) |
| 3446 | |
| 3447 | if context is None: |
| 3448 | context = getcontext() |
| 3449 | |
| 3450 | if self._is_special or other._is_special: |
| 3451 | # If one operand is a quiet NaN and the other is number, then the |
| 3452 | # number is always returned |
| 3453 | sn = self._isnan() |
| 3454 | on = other._isnan() |
| 3455 | if sn or on: |
Facundo Batista | 708d581 | 2008-12-11 04:20:07 +0000 | [diff] [blame] | 3456 | if on == 1 and sn == 0: |
| 3457 | return self._fix(context) |
| 3458 | if sn == 1 and on == 0: |
| 3459 | return other._fix(context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3460 | return self._check_nans(other, context) |
| 3461 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 3462 | c = self.copy_abs()._cmp(other.copy_abs()) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3463 | if c == 0: |
| 3464 | c = self.compare_total(other) |
| 3465 | |
| 3466 | if c == -1: |
| 3467 | ans = other |
| 3468 | else: |
| 3469 | ans = self |
| 3470 | |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 3471 | return ans._fix(context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3472 | |
| 3473 | def min_mag(self, other, context=None): |
| 3474 | """Compares the values numerically with their sign ignored.""" |
| 3475 | other = _convert_other(other, raiseit=True) |
| 3476 | |
| 3477 | if context is None: |
| 3478 | context = getcontext() |
| 3479 | |
| 3480 | if self._is_special or other._is_special: |
| 3481 | # If one operand is a quiet NaN and the other is number, then the |
| 3482 | # number is always returned |
| 3483 | sn = self._isnan() |
| 3484 | on = other._isnan() |
| 3485 | if sn or on: |
Facundo Batista | 708d581 | 2008-12-11 04:20:07 +0000 | [diff] [blame] | 3486 | if on == 1 and sn == 0: |
| 3487 | return self._fix(context) |
| 3488 | if sn == 1 and on == 0: |
| 3489 | return other._fix(context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3490 | return self._check_nans(other, context) |
| 3491 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 3492 | c = self.copy_abs()._cmp(other.copy_abs()) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3493 | if c == 0: |
| 3494 | c = self.compare_total(other) |
| 3495 | |
| 3496 | if c == -1: |
| 3497 | ans = self |
| 3498 | else: |
| 3499 | ans = other |
| 3500 | |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 3501 | return ans._fix(context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3502 | |
| 3503 | def next_minus(self, context=None): |
| 3504 | """Returns the largest representable number smaller than itself.""" |
| 3505 | if context is None: |
| 3506 | context = getcontext() |
| 3507 | |
| 3508 | ans = self._check_nans(context=context) |
| 3509 | if ans: |
| 3510 | return ans |
| 3511 | |
| 3512 | if self._isinfinity() == -1: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3513 | return _NegativeInfinity |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3514 | if self._isinfinity() == 1: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3515 | return _dec_from_triple(0, '9'*context.prec, context.Etop()) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3516 | |
| 3517 | context = context.copy() |
| 3518 | context._set_rounding(ROUND_FLOOR) |
| 3519 | context._ignore_all_flags() |
| 3520 | new_self = self._fix(context) |
| 3521 | if new_self != self: |
| 3522 | return new_self |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3523 | return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1), |
| 3524 | context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3525 | |
| 3526 | def next_plus(self, context=None): |
| 3527 | """Returns the smallest representable number larger than itself.""" |
| 3528 | if context is None: |
| 3529 | context = getcontext() |
| 3530 | |
| 3531 | ans = self._check_nans(context=context) |
| 3532 | if ans: |
| 3533 | return ans |
| 3534 | |
| 3535 | if self._isinfinity() == 1: |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 3536 | return _Infinity |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3537 | if self._isinfinity() == -1: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3538 | return _dec_from_triple(1, '9'*context.prec, context.Etop()) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3539 | |
| 3540 | context = context.copy() |
| 3541 | context._set_rounding(ROUND_CEILING) |
| 3542 | context._ignore_all_flags() |
| 3543 | new_self = self._fix(context) |
| 3544 | if new_self != self: |
| 3545 | return new_self |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3546 | return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1), |
| 3547 | context) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3548 | |
| 3549 | def next_toward(self, other, context=None): |
| 3550 | """Returns the number closest to self, in the direction towards other. |
| 3551 | |
| 3552 | The result is the closest representable number to self |
| 3553 | (excluding self) that is in the direction towards other, |
| 3554 | unless both have the same value. If the two operands are |
| 3555 | numerically equal, then the result is a copy of self with the |
| 3556 | sign set to be the same as the sign of other. |
| 3557 | """ |
| 3558 | other = _convert_other(other, raiseit=True) |
| 3559 | |
| 3560 | if context is None: |
| 3561 | context = getcontext() |
| 3562 | |
| 3563 | ans = self._check_nans(other, context) |
| 3564 | if ans: |
| 3565 | return ans |
| 3566 | |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 3567 | comparison = self._cmp(other) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3568 | if comparison == 0: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3569 | return self.copy_sign(other) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3570 | |
| 3571 | if comparison == -1: |
| 3572 | ans = self.next_plus(context) |
| 3573 | else: # comparison == 1 |
| 3574 | ans = self.next_minus(context) |
| 3575 | |
| 3576 | # decide which flags to raise using value of ans |
| 3577 | if ans._isinfinity(): |
| 3578 | context._raise_error(Overflow, |
| 3579 | 'Infinite result from next_toward', |
| 3580 | ans._sign) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3581 | context._raise_error(Inexact) |
Mark Dickinson | c69160e | 2010-05-04 14:35:33 +0000 | [diff] [blame] | 3582 | context._raise_error(Rounded) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3583 | elif ans.adjusted() < context.Emin: |
| 3584 | context._raise_error(Underflow) |
| 3585 | context._raise_error(Subnormal) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3586 | context._raise_error(Inexact) |
Mark Dickinson | c69160e | 2010-05-04 14:35:33 +0000 | [diff] [blame] | 3587 | context._raise_error(Rounded) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3588 | # if precision == 1 then we don't raise Clamped for a |
| 3589 | # result 0E-Etiny. |
| 3590 | if not ans: |
| 3591 | context._raise_error(Clamped) |
| 3592 | |
| 3593 | return ans |
| 3594 | |
| 3595 | def number_class(self, context=None): |
| 3596 | """Returns an indication of the class of self. |
| 3597 | |
| 3598 | The class is one of the following strings: |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 3599 | sNaN |
| 3600 | NaN |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3601 | -Infinity |
| 3602 | -Normal |
| 3603 | -Subnormal |
| 3604 | -Zero |
| 3605 | +Zero |
| 3606 | +Subnormal |
| 3607 | +Normal |
| 3608 | +Infinity |
| 3609 | """ |
| 3610 | if self.is_snan(): |
| 3611 | return "sNaN" |
| 3612 | if self.is_qnan(): |
| 3613 | return "NaN" |
| 3614 | inf = self._isinfinity() |
| 3615 | if inf == 1: |
| 3616 | return "+Infinity" |
| 3617 | if inf == -1: |
| 3618 | return "-Infinity" |
| 3619 | if self.is_zero(): |
| 3620 | if self._sign: |
| 3621 | return "-Zero" |
| 3622 | else: |
| 3623 | return "+Zero" |
| 3624 | if context is None: |
| 3625 | context = getcontext() |
| 3626 | if self.is_subnormal(context=context): |
| 3627 | if self._sign: |
| 3628 | return "-Subnormal" |
| 3629 | else: |
| 3630 | return "+Subnormal" |
| 3631 | # just a normal, regular, boring number, :) |
| 3632 | if self._sign: |
| 3633 | return "-Normal" |
| 3634 | else: |
| 3635 | return "+Normal" |
| 3636 | |
| 3637 | def radix(self): |
| 3638 | """Just returns 10, as this is Decimal, :)""" |
| 3639 | return Decimal(10) |
| 3640 | |
| 3641 | def rotate(self, other, context=None): |
| 3642 | """Returns a rotated copy of self, value-of-other times.""" |
| 3643 | if context is None: |
| 3644 | context = getcontext() |
| 3645 | |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 3646 | other = _convert_other(other, raiseit=True) |
| 3647 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3648 | ans = self._check_nans(other, context) |
| 3649 | if ans: |
| 3650 | return ans |
| 3651 | |
| 3652 | if other._exp != 0: |
| 3653 | return context._raise_error(InvalidOperation) |
| 3654 | if not (-context.prec <= int(other) <= context.prec): |
| 3655 | return context._raise_error(InvalidOperation) |
| 3656 | |
| 3657 | if self._isinfinity(): |
| 3658 | return Decimal(self) |
| 3659 | |
| 3660 | # get values, pad if necessary |
| 3661 | torot = int(other) |
| 3662 | rotdig = self._int |
| 3663 | topad = context.prec - len(rotdig) |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 3664 | if topad > 0: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3665 | rotdig = '0'*topad + rotdig |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 3666 | elif topad < 0: |
| 3667 | rotdig = rotdig[-topad:] |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3668 | |
| 3669 | # let's rotate! |
| 3670 | rotated = rotdig[torot:] + rotdig[:torot] |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3671 | return _dec_from_triple(self._sign, |
| 3672 | rotated.lstrip('0') or '0', self._exp) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3673 | |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 3674 | def scaleb(self, other, context=None): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3675 | """Returns self operand after adding the second value to its exp.""" |
| 3676 | if context is None: |
| 3677 | context = getcontext() |
| 3678 | |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 3679 | other = _convert_other(other, raiseit=True) |
| 3680 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3681 | ans = self._check_nans(other, context) |
| 3682 | if ans: |
| 3683 | return ans |
| 3684 | |
| 3685 | if other._exp != 0: |
| 3686 | return context._raise_error(InvalidOperation) |
| 3687 | liminf = -2 * (context.Emax + context.prec) |
| 3688 | limsup = 2 * (context.Emax + context.prec) |
| 3689 | if not (liminf <= int(other) <= limsup): |
| 3690 | return context._raise_error(InvalidOperation) |
| 3691 | |
| 3692 | if self._isinfinity(): |
| 3693 | return Decimal(self) |
| 3694 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3695 | d = _dec_from_triple(self._sign, self._int, self._exp + int(other)) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3696 | d = d._fix(context) |
| 3697 | return d |
| 3698 | |
| 3699 | def shift(self, other, context=None): |
| 3700 | """Returns a shifted copy of self, value-of-other times.""" |
| 3701 | if context is None: |
| 3702 | context = getcontext() |
| 3703 | |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 3704 | other = _convert_other(other, raiseit=True) |
| 3705 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3706 | ans = self._check_nans(other, context) |
| 3707 | if ans: |
| 3708 | return ans |
| 3709 | |
| 3710 | if other._exp != 0: |
| 3711 | return context._raise_error(InvalidOperation) |
| 3712 | if not (-context.prec <= int(other) <= context.prec): |
| 3713 | return context._raise_error(InvalidOperation) |
| 3714 | |
| 3715 | if self._isinfinity(): |
| 3716 | return Decimal(self) |
| 3717 | |
| 3718 | # get values, pad if necessary |
| 3719 | torot = int(other) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3720 | rotdig = self._int |
| 3721 | topad = context.prec - len(rotdig) |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 3722 | if topad > 0: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3723 | rotdig = '0'*topad + rotdig |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 3724 | elif topad < 0: |
| 3725 | rotdig = rotdig[-topad:] |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3726 | |
| 3727 | # let's shift! |
| 3728 | if torot < 0: |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 3729 | shifted = rotdig[:torot] |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3730 | else: |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 3731 | shifted = rotdig + '0'*torot |
| 3732 | shifted = shifted[-context.prec:] |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3733 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3734 | return _dec_from_triple(self._sign, |
Mark Dickinson | a2d1fe0 | 2009-10-29 12:23:02 +0000 | [diff] [blame] | 3735 | shifted.lstrip('0') or '0', self._exp) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 3736 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3737 | # Support for pickling, copy, and deepcopy |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3738 | def __reduce__(self): |
| 3739 | return (self.__class__, (str(self),)) |
| 3740 | |
| 3741 | def __copy__(self): |
Benjamin Peterson | d69fe2a | 2010-02-03 02:59:43 +0000 | [diff] [blame] | 3742 | if type(self) is Decimal: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3743 | return self # I'm immutable; therefore I am my own clone |
| 3744 | return self.__class__(str(self)) |
| 3745 | |
| 3746 | def __deepcopy__(self, memo): |
Benjamin Peterson | d69fe2a | 2010-02-03 02:59:43 +0000 | [diff] [blame] | 3747 | if type(self) is Decimal: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3748 | return self # My components are also immutable |
| 3749 | return self.__class__(str(self)) |
| 3750 | |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 3751 | # PEP 3101 support. the _localeconv keyword argument should be |
| 3752 | # considered private: it's provided for ease of testing only. |
| 3753 | def __format__(self, specifier, context=None, _localeconv=None): |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3754 | """Format a Decimal instance according to the given specifier. |
| 3755 | |
| 3756 | The specifier should be a standard format specifier, with the |
| 3757 | form described in PEP 3101. Formatting types 'e', 'E', 'f', |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 3758 | 'F', 'g', 'G', 'n' and '%' are supported. If the formatting |
| 3759 | type is omitted it defaults to 'g' or 'G', depending on the |
| 3760 | value of context.capitals. |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3761 | """ |
| 3762 | |
| 3763 | # Note: PEP 3101 says that if the type is not present then |
| 3764 | # there should be at least one digit after the decimal point. |
| 3765 | # We take the liberty of ignoring this requirement for |
| 3766 | # Decimal---it's presumably there to make sure that |
| 3767 | # format(float, '') behaves similarly to str(float). |
| 3768 | if context is None: |
| 3769 | context = getcontext() |
| 3770 | |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 3771 | spec = _parse_format_specifier(specifier, _localeconv=_localeconv) |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3772 | |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 3773 | # special values don't care about the type or precision |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3774 | if self._is_special: |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 3775 | sign = _format_sign(self._sign, spec) |
| 3776 | body = str(self.copy_abs()) |
Stefan Krah | 298131a | 2014-08-26 20:46:49 +0200 | [diff] [blame] | 3777 | if spec['type'] == '%': |
| 3778 | body += '%' |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 3779 | return _format_align(sign, body, spec) |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3780 | |
| 3781 | # a type of None defaults to 'g' or 'G', depending on context |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3782 | if spec['type'] is None: |
| 3783 | spec['type'] = ['g', 'G'][context.capitals] |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 3784 | |
| 3785 | # if type is '%', adjust exponent of self accordingly |
| 3786 | if spec['type'] == '%': |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3787 | self = _dec_from_triple(self._sign, self._int, self._exp+2) |
| 3788 | |
| 3789 | # round if necessary, taking rounding mode from the context |
| 3790 | rounding = context.rounding |
| 3791 | precision = spec['precision'] |
| 3792 | if precision is not None: |
| 3793 | if spec['type'] in 'eE': |
| 3794 | self = self._round(precision+1, rounding) |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3795 | elif spec['type'] in 'fF%': |
| 3796 | self = self._rescale(-precision, rounding) |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 3797 | elif spec['type'] in 'gG' and len(self._int) > precision: |
| 3798 | self = self._round(precision, rounding) |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3799 | # special case: zeros with a positive exponent can't be |
| 3800 | # represented in fixed point; rescale them to 0e0. |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 3801 | if not self and self._exp > 0 and spec['type'] in 'fF%': |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3802 | self = self._rescale(0, rounding) |
| 3803 | |
| 3804 | # figure out placement of the decimal point |
| 3805 | leftdigits = self._exp + len(self._int) |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 3806 | if spec['type'] in 'eE': |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3807 | if not self and precision is not None: |
| 3808 | dotplace = 1 - precision |
| 3809 | else: |
| 3810 | dotplace = 1 |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 3811 | elif spec['type'] in 'fF%': |
| 3812 | dotplace = leftdigits |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3813 | elif spec['type'] in 'gG': |
| 3814 | if self._exp <= 0 and leftdigits > -6: |
| 3815 | dotplace = leftdigits |
| 3816 | else: |
| 3817 | dotplace = 1 |
| 3818 | |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 3819 | # find digits before and after decimal point, and get exponent |
| 3820 | if dotplace < 0: |
| 3821 | intpart = '0' |
| 3822 | fracpart = '0'*(-dotplace) + self._int |
| 3823 | elif dotplace > len(self._int): |
| 3824 | intpart = self._int + '0'*(dotplace-len(self._int)) |
| 3825 | fracpart = '' |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3826 | else: |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 3827 | intpart = self._int[:dotplace] or '0' |
| 3828 | fracpart = self._int[dotplace:] |
| 3829 | exp = leftdigits-dotplace |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3830 | |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 3831 | # done with the decimal-specific stuff; hand over the rest |
| 3832 | # of the formatting to the _format_number function |
| 3833 | return _format_number(self._sign, intpart, fracpart, exp, spec) |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 3834 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 3835 | def _dec_from_triple(sign, coefficient, exponent, special=False): |
| 3836 | """Create a decimal instance directly, without any validation, |
| 3837 | normalization (e.g. removal of leading zeros) or argument |
| 3838 | conversion. |
| 3839 | |
| 3840 | This function is for *internal use only*. |
| 3841 | """ |
| 3842 | |
| 3843 | self = object.__new__(Decimal) |
| 3844 | self._sign = sign |
| 3845 | self._int = coefficient |
| 3846 | self._exp = exponent |
| 3847 | self._is_special = special |
| 3848 | |
| 3849 | return self |
| 3850 | |
Raymond Hettinger | 82417ca | 2009-02-03 03:54:28 +0000 | [diff] [blame] | 3851 | # Register Decimal as a kind of Number (an abstract base class). |
| 3852 | # However, do not register it as Real (because Decimals are not |
| 3853 | # interoperable with floats). |
| 3854 | _numbers.Number.register(Decimal) |
| 3855 | |
| 3856 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3857 | ##### Context class ####################################################### |
Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 3858 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 3859 | class _ContextManager(object): |
| 3860 | """Context manager class to support localcontext(). |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 3861 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 3862 | Sets a copy of the supplied context in __enter__() and restores |
| 3863 | the previous decimal context in __exit__() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 3864 | """ |
| 3865 | def __init__(self, new_context): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 3866 | self.new_context = new_context.copy() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 3867 | def __enter__(self): |
| 3868 | self.saved_context = getcontext() |
| 3869 | setcontext(self.new_context) |
| 3870 | return self.new_context |
| 3871 | def __exit__(self, t, v, tb): |
| 3872 | setcontext(self.saved_context) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 3873 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3874 | class Context(object): |
| 3875 | """Contains the context for a Decimal instance. |
| 3876 | |
| 3877 | Contains: |
| 3878 | prec - precision (for use in rounding, division, square roots..) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3879 | rounding - rounding type (how you round) |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3880 | traps - If traps[exception] = 1, then the exception is |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3881 | raised when it is caused. Otherwise, a value is |
| 3882 | substituted in. |
Raymond Hettinger | 86173da | 2008-02-01 20:38:12 +0000 | [diff] [blame] | 3883 | flags - When an exception is caused, flags[exception] is set. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3884 | (Whether or not the trap_enabler is set) |
| 3885 | Should be reset by user of Decimal instance. |
Raymond Hettinger | 0ea241e | 2004-07-04 13:53:24 +0000 | [diff] [blame] | 3886 | Emin - Minimum exponent |
| 3887 | Emax - Maximum exponent |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3888 | capitals - If 1, 1*10^1 is printed as 1E+1. |
| 3889 | If 0, printed as 1e1 |
Mark Dickinson | b1d8e32 | 2010-05-22 18:35:36 +0000 | [diff] [blame] | 3890 | clamp - If 1, change exponents if too high (Default 0) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3891 | """ |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 3892 | |
Stefan Krah | 1919b7e | 2012-03-21 18:25:23 +0100 | [diff] [blame] | 3893 | def __init__(self, prec=None, rounding=None, Emin=None, Emax=None, |
| 3894 | capitals=None, clamp=None, flags=None, traps=None, |
| 3895 | _ignored_flags=None): |
Mark Dickinson | 0dd8f78 | 2010-07-08 21:15:36 +0000 | [diff] [blame] | 3896 | # Set defaults; for everything except flags and _ignored_flags, |
| 3897 | # inherit from DefaultContext. |
| 3898 | try: |
| 3899 | dc = DefaultContext |
| 3900 | except NameError: |
| 3901 | pass |
| 3902 | |
| 3903 | self.prec = prec if prec is not None else dc.prec |
| 3904 | self.rounding = rounding if rounding is not None else dc.rounding |
| 3905 | self.Emin = Emin if Emin is not None else dc.Emin |
| 3906 | self.Emax = Emax if Emax is not None else dc.Emax |
| 3907 | self.capitals = capitals if capitals is not None else dc.capitals |
| 3908 | self.clamp = clamp if clamp is not None else dc.clamp |
| 3909 | |
Raymond Hettinger | abf8a56 | 2004-10-12 09:12:16 +0000 | [diff] [blame] | 3910 | if _ignored_flags is None: |
Mark Dickinson | 0dd8f78 | 2010-07-08 21:15:36 +0000 | [diff] [blame] | 3911 | self._ignored_flags = [] |
| 3912 | else: |
| 3913 | self._ignored_flags = _ignored_flags |
| 3914 | |
| 3915 | if traps is None: |
| 3916 | self.traps = dc.traps.copy() |
| 3917 | elif not isinstance(traps, dict): |
Stefan Krah | 1919b7e | 2012-03-21 18:25:23 +0100 | [diff] [blame] | 3918 | self.traps = dict((s, int(s in traps)) for s in _signals + traps) |
Mark Dickinson | 0dd8f78 | 2010-07-08 21:15:36 +0000 | [diff] [blame] | 3919 | else: |
| 3920 | self.traps = traps |
| 3921 | |
| 3922 | if flags is None: |
| 3923 | self.flags = dict.fromkeys(_signals, 0) |
| 3924 | elif not isinstance(flags, dict): |
Stefan Krah | 1919b7e | 2012-03-21 18:25:23 +0100 | [diff] [blame] | 3925 | self.flags = dict((s, int(s in flags)) for s in _signals + flags) |
Mark Dickinson | 0dd8f78 | 2010-07-08 21:15:36 +0000 | [diff] [blame] | 3926 | else: |
| 3927 | self.flags = flags |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 3928 | |
Stefan Krah | 1919b7e | 2012-03-21 18:25:23 +0100 | [diff] [blame] | 3929 | def _set_integer_check(self, name, value, vmin, vmax): |
| 3930 | if not isinstance(value, int): |
| 3931 | raise TypeError("%s must be an integer" % name) |
| 3932 | if vmin == '-inf': |
| 3933 | if value > vmax: |
| 3934 | raise ValueError("%s must be in [%s, %d]. got: %s" % (name, vmin, vmax, value)) |
| 3935 | elif vmax == 'inf': |
| 3936 | if value < vmin: |
| 3937 | raise ValueError("%s must be in [%d, %s]. got: %s" % (name, vmin, vmax, value)) |
| 3938 | else: |
| 3939 | if value < vmin or value > vmax: |
| 3940 | raise ValueError("%s must be in [%d, %d]. got %s" % (name, vmin, vmax, value)) |
| 3941 | return object.__setattr__(self, name, value) |
| 3942 | |
| 3943 | def _set_signal_dict(self, name, d): |
| 3944 | if not isinstance(d, dict): |
| 3945 | raise TypeError("%s must be a signal dict" % d) |
| 3946 | for key in d: |
| 3947 | if not key in _signals: |
| 3948 | raise KeyError("%s is not a valid signal dict" % d) |
| 3949 | for key in _signals: |
| 3950 | if not key in d: |
| 3951 | raise KeyError("%s is not a valid signal dict" % d) |
| 3952 | return object.__setattr__(self, name, d) |
| 3953 | |
| 3954 | def __setattr__(self, name, value): |
| 3955 | if name == 'prec': |
| 3956 | return self._set_integer_check(name, value, 1, 'inf') |
| 3957 | elif name == 'Emin': |
| 3958 | return self._set_integer_check(name, value, '-inf', 0) |
| 3959 | elif name == 'Emax': |
| 3960 | return self._set_integer_check(name, value, 0, 'inf') |
| 3961 | elif name == 'capitals': |
| 3962 | return self._set_integer_check(name, value, 0, 1) |
| 3963 | elif name == 'clamp': |
| 3964 | return self._set_integer_check(name, value, 0, 1) |
| 3965 | elif name == 'rounding': |
| 3966 | if not value in _rounding_modes: |
| 3967 | # raise TypeError even for strings to have consistency |
| 3968 | # among various implementations. |
| 3969 | raise TypeError("%s: invalid rounding mode" % value) |
| 3970 | return object.__setattr__(self, name, value) |
| 3971 | elif name == 'flags' or name == 'traps': |
| 3972 | return self._set_signal_dict(name, value) |
| 3973 | elif name == '_ignored_flags': |
| 3974 | return object.__setattr__(self, name, value) |
| 3975 | else: |
| 3976 | raise AttributeError( |
| 3977 | "'decimal.Context' object has no attribute '%s'" % name) |
| 3978 | |
| 3979 | def __delattr__(self, name): |
| 3980 | raise AttributeError("%s cannot be deleted" % name) |
| 3981 | |
| 3982 | # Support for pickling, copy, and deepcopy |
| 3983 | def __reduce__(self): |
| 3984 | flags = [sig for sig, v in self.flags.items() if v] |
| 3985 | traps = [sig for sig, v in self.traps.items() if v] |
| 3986 | return (self.__class__, |
| 3987 | (self.prec, self.rounding, self.Emin, self.Emax, |
| 3988 | self.capitals, self.clamp, flags, traps)) |
| 3989 | |
Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 3990 | def __repr__(self): |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 3991 | """Show the current context.""" |
Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 3992 | s = [] |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3993 | s.append('Context(prec=%(prec)d, rounding=%(rounding)s, ' |
Mark Dickinson | b1d8e32 | 2010-05-22 18:35:36 +0000 | [diff] [blame] | 3994 | 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d, ' |
| 3995 | 'clamp=%(clamp)d' |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3996 | % vars(self)) |
| 3997 | names = [f.__name__ for f, v in self.flags.items() if v] |
| 3998 | s.append('flags=[' + ', '.join(names) + ']') |
| 3999 | names = [t.__name__ for t, v in self.traps.items() if v] |
| 4000 | s.append('traps=[' + ', '.join(names) + ']') |
Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 4001 | return ', '.join(s) + ')' |
| 4002 | |
Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 4003 | def clear_flags(self): |
| 4004 | """Reset all flags to zero""" |
| 4005 | for flag in self.flags: |
Raymond Hettinger | b1b605e | 2004-07-04 01:55:39 +0000 | [diff] [blame] | 4006 | self.flags[flag] = 0 |
Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 4007 | |
Stefan Krah | 1919b7e | 2012-03-21 18:25:23 +0100 | [diff] [blame] | 4008 | def clear_traps(self): |
| 4009 | """Reset all traps to zero""" |
| 4010 | for flag in self.traps: |
| 4011 | self.traps[flag] = 0 |
| 4012 | |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 4013 | def _shallow_copy(self): |
| 4014 | """Returns a shallow copy from self.""" |
Stefan Krah | 1919b7e | 2012-03-21 18:25:23 +0100 | [diff] [blame] | 4015 | nc = Context(self.prec, self.rounding, self.Emin, self.Emax, |
| 4016 | self.capitals, self.clamp, self.flags, self.traps, |
| 4017 | self._ignored_flags) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4018 | return nc |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 4019 | |
| 4020 | def copy(self): |
| 4021 | """Returns a deep copy from self.""" |
Stefan Krah | 1919b7e | 2012-03-21 18:25:23 +0100 | [diff] [blame] | 4022 | nc = Context(self.prec, self.rounding, self.Emin, self.Emax, |
| 4023 | self.capitals, self.clamp, |
| 4024 | self.flags.copy(), self.traps.copy(), |
| 4025 | self._ignored_flags) |
Raymond Hettinger | 9fce44b | 2004-08-08 04:03:24 +0000 | [diff] [blame] | 4026 | return nc |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4027 | __copy__ = copy |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4028 | |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 4029 | def _raise_error(self, condition, explanation = None, *args): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4030 | """Handles an error |
| 4031 | |
| 4032 | If the flag is in _ignored_flags, returns the default response. |
Raymond Hettinger | 86173da | 2008-02-01 20:38:12 +0000 | [diff] [blame] | 4033 | Otherwise, it sets the flag, then, if the corresponding |
Stefan Krah | 2eb4a07 | 2010-05-19 15:52:31 +0000 | [diff] [blame] | 4034 | trap_enabler is set, it reraises the exception. Otherwise, it returns |
Raymond Hettinger | 86173da | 2008-02-01 20:38:12 +0000 | [diff] [blame] | 4035 | the default value after setting the flag. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4036 | """ |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 4037 | error = _condition_map.get(condition, condition) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4038 | if error in self._ignored_flags: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 4039 | # Don't touch the flag |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4040 | return error().handle(self, *args) |
| 4041 | |
Raymond Hettinger | 86173da | 2008-02-01 20:38:12 +0000 | [diff] [blame] | 4042 | self.flags[error] = 1 |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 4043 | if not self.traps[error]: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 4044 | # The errors define how to handle themselves. |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 4045 | return condition().handle(self, *args) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4046 | |
| 4047 | # Errors should only be risked on copies of the context |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 4048 | # self._ignored_flags = [] |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 4049 | raise error(explanation) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4050 | |
| 4051 | def _ignore_all_flags(self): |
| 4052 | """Ignore all flags, if they are raised""" |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 4053 | return self._ignore_flags(*_signals) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4054 | |
| 4055 | def _ignore_flags(self, *flags): |
| 4056 | """Ignore the flags, if they are raised""" |
| 4057 | # Do not mutate-- This way, copies of a context leave the original |
| 4058 | # alone. |
| 4059 | self._ignored_flags = (self._ignored_flags + list(flags)) |
| 4060 | return list(flags) |
| 4061 | |
| 4062 | def _regard_flags(self, *flags): |
| 4063 | """Stop ignoring the flags, if they are raised""" |
| 4064 | if flags and isinstance(flags[0], (tuple,list)): |
| 4065 | flags = flags[0] |
| 4066 | for flag in flags: |
| 4067 | self._ignored_flags.remove(flag) |
| 4068 | |
Nick Coghlan | d1abd25 | 2008-07-15 15:46:38 +0000 | [diff] [blame] | 4069 | # We inherit object.__hash__, so we must deny this explicitly |
| 4070 | __hash__ = None |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 4071 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4072 | def Etiny(self): |
| 4073 | """Returns Etiny (= Emin - prec + 1)""" |
| 4074 | return int(self.Emin - self.prec + 1) |
| 4075 | |
| 4076 | def Etop(self): |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 4077 | """Returns maximum exponent (= Emax - prec + 1)""" |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4078 | return int(self.Emax - self.prec + 1) |
| 4079 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4080 | def _set_rounding(self, type): |
| 4081 | """Sets the rounding type. |
| 4082 | |
| 4083 | Sets the rounding type, and returns the current (previous) |
| 4084 | rounding type. Often used like: |
| 4085 | |
| 4086 | context = context.copy() |
| 4087 | # so you don't change the calling context |
| 4088 | # if an error occurs in the middle. |
| 4089 | rounding = context._set_rounding(ROUND_UP) |
| 4090 | val = self.__sub__(other, context=context) |
| 4091 | context._set_rounding(rounding) |
| 4092 | |
| 4093 | This will make it round up for that operation. |
| 4094 | """ |
| 4095 | rounding = self.rounding |
| 4096 | self.rounding= type |
| 4097 | return rounding |
| 4098 | |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 4099 | def create_decimal(self, num='0'): |
Christian Heimes | a62da1d | 2008-01-12 19:39:10 +0000 | [diff] [blame] | 4100 | """Creates a new Decimal instance but using self as context. |
| 4101 | |
| 4102 | This method implements the to-number operation of the |
| 4103 | IBM Decimal specification.""" |
| 4104 | |
| 4105 | if isinstance(num, str) and num != num.strip(): |
| 4106 | return self._raise_error(ConversionSyntax, |
| 4107 | "no trailing or leading whitespace is " |
| 4108 | "permitted.") |
| 4109 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4110 | d = Decimal(num, context=self) |
Mark Dickinson | b1d8e32 | 2010-05-22 18:35:36 +0000 | [diff] [blame] | 4111 | if d._isnan() and len(d._int) > self.prec - self.clamp: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4112 | return self._raise_error(ConversionSyntax, |
| 4113 | "diagnostic info too long in NaN") |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 4114 | return d._fix(self) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4115 | |
Raymond Hettinger | 771ed76 | 2009-01-03 19:20:32 +0000 | [diff] [blame] | 4116 | def create_decimal_from_float(self, f): |
| 4117 | """Creates a new Decimal instance from a float but rounding using self |
| 4118 | as the context. |
| 4119 | |
| 4120 | >>> context = Context(prec=5, rounding=ROUND_DOWN) |
| 4121 | >>> context.create_decimal_from_float(3.1415926535897932) |
| 4122 | Decimal('3.1415') |
| 4123 | >>> context = Context(prec=5, traps=[Inexact]) |
| 4124 | >>> context.create_decimal_from_float(3.1415926535897932) |
| 4125 | Traceback (most recent call last): |
| 4126 | ... |
| 4127 | decimal.Inexact: None |
| 4128 | |
| 4129 | """ |
| 4130 | d = Decimal.from_float(f) # An exact conversion |
| 4131 | return d._fix(self) # Apply the context rounding |
| 4132 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 4133 | # Methods |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4134 | def abs(self, a): |
| 4135 | """Returns the absolute value of the operand. |
| 4136 | |
| 4137 | 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] | 4138 | operation on the operand. Otherwise, the result is the same as using |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4139 | the plus operation on the operand. |
| 4140 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4141 | >>> ExtendedContext.abs(Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4142 | Decimal('2.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4143 | >>> ExtendedContext.abs(Decimal('-100')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4144 | Decimal('100') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4145 | >>> ExtendedContext.abs(Decimal('101.5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4146 | Decimal('101.5') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4147 | >>> ExtendedContext.abs(Decimal('-101.5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4148 | Decimal('101.5') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4149 | >>> ExtendedContext.abs(-1) |
| 4150 | Decimal('1') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4151 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4152 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4153 | return a.__abs__(context=self) |
| 4154 | |
| 4155 | def add(self, a, b): |
| 4156 | """Return the sum of the two operands. |
| 4157 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4158 | >>> ExtendedContext.add(Decimal('12'), Decimal('7.00')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4159 | Decimal('19.00') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4160 | >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4161 | Decimal('1.02E+4') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4162 | >>> ExtendedContext.add(1, Decimal(2)) |
| 4163 | Decimal('3') |
| 4164 | >>> ExtendedContext.add(Decimal(8), 5) |
| 4165 | Decimal('13') |
| 4166 | >>> ExtendedContext.add(5, 5) |
| 4167 | Decimal('10') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4168 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4169 | a = _convert_other(a, raiseit=True) |
| 4170 | r = a.__add__(b, context=self) |
| 4171 | if r is NotImplemented: |
| 4172 | raise TypeError("Unable to convert %s to Decimal" % b) |
| 4173 | else: |
| 4174 | return r |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4175 | |
| 4176 | def _apply(self, a): |
Raymond Hettinger | dab988d | 2004-10-09 07:10:44 +0000 | [diff] [blame] | 4177 | return str(a._fix(self)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4178 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4179 | def canonical(self, a): |
| 4180 | """Returns the same Decimal object. |
| 4181 | |
| 4182 | As we do not have different encodings for the same number, the |
| 4183 | received object already is in its canonical form. |
| 4184 | |
| 4185 | >>> ExtendedContext.canonical(Decimal('2.50')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4186 | Decimal('2.50') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4187 | """ |
Stefan Krah | 1919b7e | 2012-03-21 18:25:23 +0100 | [diff] [blame] | 4188 | if not isinstance(a, Decimal): |
| 4189 | raise TypeError("canonical requires a Decimal as an argument.") |
Stefan Krah | 040e311 | 2012-12-15 22:33:33 +0100 | [diff] [blame] | 4190 | return a.canonical() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4191 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4192 | def compare(self, a, b): |
| 4193 | """Compares values numerically. |
| 4194 | |
| 4195 | If the signs of the operands differ, a value representing each operand |
| 4196 | ('-1' if the operand is less than zero, '0' if the operand is zero or |
| 4197 | negative zero, or '1' if the operand is greater than zero) is used in |
| 4198 | place of that operand for the comparison instead of the actual |
| 4199 | operand. |
| 4200 | |
| 4201 | The comparison is then effected by subtracting the second operand from |
| 4202 | the first and then returning a value according to the result of the |
| 4203 | subtraction: '-1' if the result is less than zero, '0' if the result is |
| 4204 | zero or negative zero, or '1' if the result is greater than zero. |
| 4205 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4206 | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4207 | Decimal('-1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4208 | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4209 | Decimal('0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4210 | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4211 | Decimal('0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4212 | >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4213 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4214 | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4215 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4216 | >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4217 | Decimal('-1') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4218 | >>> ExtendedContext.compare(1, 2) |
| 4219 | Decimal('-1') |
| 4220 | >>> ExtendedContext.compare(Decimal(1), 2) |
| 4221 | Decimal('-1') |
| 4222 | >>> ExtendedContext.compare(1, Decimal(2)) |
| 4223 | Decimal('-1') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4224 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4225 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4226 | return a.compare(b, context=self) |
| 4227 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4228 | def compare_signal(self, a, b): |
| 4229 | """Compares the values of the two operands numerically. |
| 4230 | |
| 4231 | It's pretty much like compare(), but all NaNs signal, with signaling |
| 4232 | NaNs taking precedence over quiet NaNs. |
| 4233 | |
| 4234 | >>> c = ExtendedContext |
| 4235 | >>> c.compare_signal(Decimal('2.1'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4236 | Decimal('-1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4237 | >>> c.compare_signal(Decimal('2.1'), Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4238 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4239 | >>> c.flags[InvalidOperation] = 0 |
| 4240 | >>> print(c.flags[InvalidOperation]) |
| 4241 | 0 |
| 4242 | >>> c.compare_signal(Decimal('NaN'), Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4243 | Decimal('NaN') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4244 | >>> print(c.flags[InvalidOperation]) |
| 4245 | 1 |
| 4246 | >>> c.flags[InvalidOperation] = 0 |
| 4247 | >>> print(c.flags[InvalidOperation]) |
| 4248 | 0 |
| 4249 | >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4250 | Decimal('NaN') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4251 | >>> print(c.flags[InvalidOperation]) |
| 4252 | 1 |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4253 | >>> c.compare_signal(-1, 2) |
| 4254 | Decimal('-1') |
| 4255 | >>> c.compare_signal(Decimal(-1), 2) |
| 4256 | Decimal('-1') |
| 4257 | >>> c.compare_signal(-1, Decimal(2)) |
| 4258 | Decimal('-1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4259 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4260 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4261 | return a.compare_signal(b, context=self) |
| 4262 | |
| 4263 | def compare_total(self, a, b): |
| 4264 | """Compares two operands using their abstract representation. |
| 4265 | |
| 4266 | This is not like the standard compare, which use their numerical |
| 4267 | value. Note that a total ordering is defined for all possible abstract |
| 4268 | representations. |
| 4269 | |
| 4270 | >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4271 | Decimal('-1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4272 | >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4273 | Decimal('-1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4274 | >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4275 | Decimal('-1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4276 | >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4277 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4278 | >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4279 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4280 | >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4281 | Decimal('-1') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4282 | >>> ExtendedContext.compare_total(1, 2) |
| 4283 | Decimal('-1') |
| 4284 | >>> ExtendedContext.compare_total(Decimal(1), 2) |
| 4285 | Decimal('-1') |
| 4286 | >>> ExtendedContext.compare_total(1, Decimal(2)) |
| 4287 | Decimal('-1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4288 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4289 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4290 | return a.compare_total(b) |
| 4291 | |
| 4292 | def compare_total_mag(self, a, b): |
| 4293 | """Compares two operands using their abstract representation ignoring sign. |
| 4294 | |
| 4295 | Like compare_total, but with operand's sign ignored and assumed to be 0. |
| 4296 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4297 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4298 | return a.compare_total_mag(b) |
| 4299 | |
| 4300 | def copy_abs(self, a): |
| 4301 | """Returns a copy of the operand with the sign set to 0. |
| 4302 | |
| 4303 | >>> ExtendedContext.copy_abs(Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4304 | Decimal('2.1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4305 | >>> ExtendedContext.copy_abs(Decimal('-100')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4306 | Decimal('100') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4307 | >>> ExtendedContext.copy_abs(-1) |
| 4308 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4309 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4310 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4311 | return a.copy_abs() |
| 4312 | |
| 4313 | def copy_decimal(self, a): |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4314 | """Returns a copy of the decimal object. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4315 | |
| 4316 | >>> ExtendedContext.copy_decimal(Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4317 | Decimal('2.1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4318 | >>> ExtendedContext.copy_decimal(Decimal('-1.00')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4319 | Decimal('-1.00') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4320 | >>> ExtendedContext.copy_decimal(1) |
| 4321 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4322 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4323 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4324 | return Decimal(a) |
| 4325 | |
| 4326 | def copy_negate(self, a): |
| 4327 | """Returns a copy of the operand with the sign inverted. |
| 4328 | |
| 4329 | >>> ExtendedContext.copy_negate(Decimal('101.5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4330 | Decimal('-101.5') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4331 | >>> ExtendedContext.copy_negate(Decimal('-101.5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4332 | Decimal('101.5') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4333 | >>> ExtendedContext.copy_negate(1) |
| 4334 | Decimal('-1') |
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.copy_negate() |
| 4338 | |
| 4339 | def copy_sign(self, a, b): |
| 4340 | """Copies the second operand's sign to the first one. |
| 4341 | |
| 4342 | In detail, it returns a copy of the first operand with the sign |
| 4343 | equal to the sign of the second operand. |
| 4344 | |
| 4345 | >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4346 | Decimal('1.50') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4347 | >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4348 | Decimal('1.50') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4349 | >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4350 | Decimal('-1.50') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4351 | >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4352 | Decimal('-1.50') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4353 | >>> ExtendedContext.copy_sign(1, -2) |
| 4354 | Decimal('-1') |
| 4355 | >>> ExtendedContext.copy_sign(Decimal(1), -2) |
| 4356 | Decimal('-1') |
| 4357 | >>> ExtendedContext.copy_sign(1, Decimal(-2)) |
| 4358 | Decimal('-1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4359 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4360 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4361 | return a.copy_sign(b) |
| 4362 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4363 | def divide(self, a, b): |
| 4364 | """Decimal division in a specified context. |
| 4365 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4366 | >>> ExtendedContext.divide(Decimal('1'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4367 | Decimal('0.333333333') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4368 | >>> ExtendedContext.divide(Decimal('2'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4369 | Decimal('0.666666667') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4370 | >>> ExtendedContext.divide(Decimal('5'), Decimal('2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4371 | Decimal('2.5') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4372 | >>> ExtendedContext.divide(Decimal('1'), Decimal('10')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4373 | Decimal('0.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4374 | >>> ExtendedContext.divide(Decimal('12'), Decimal('12')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4375 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4376 | >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4377 | Decimal('4.00') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4378 | >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4379 | Decimal('1.20') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4380 | >>> ExtendedContext.divide(Decimal('1000'), Decimal('100')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4381 | Decimal('10') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4382 | >>> ExtendedContext.divide(Decimal('1000'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4383 | Decimal('1000') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4384 | >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4385 | Decimal('1.20E+6') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4386 | >>> ExtendedContext.divide(5, 5) |
| 4387 | Decimal('1') |
| 4388 | >>> ExtendedContext.divide(Decimal(5), 5) |
| 4389 | Decimal('1') |
| 4390 | >>> ExtendedContext.divide(5, Decimal(5)) |
| 4391 | Decimal('1') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4392 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4393 | a = _convert_other(a, raiseit=True) |
| 4394 | r = a.__truediv__(b, context=self) |
| 4395 | if r is NotImplemented: |
| 4396 | raise TypeError("Unable to convert %s to Decimal" % b) |
| 4397 | else: |
| 4398 | return r |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4399 | |
| 4400 | def divide_int(self, a, b): |
| 4401 | """Divides two numbers and returns the integer part of the result. |
| 4402 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4403 | >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4404 | Decimal('0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4405 | >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4406 | Decimal('3') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4407 | >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4408 | Decimal('3') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4409 | >>> ExtendedContext.divide_int(10, 3) |
| 4410 | Decimal('3') |
| 4411 | >>> ExtendedContext.divide_int(Decimal(10), 3) |
| 4412 | Decimal('3') |
| 4413 | >>> ExtendedContext.divide_int(10, Decimal(3)) |
| 4414 | Decimal('3') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4415 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4416 | a = _convert_other(a, raiseit=True) |
| 4417 | r = a.__floordiv__(b, context=self) |
| 4418 | if r is NotImplemented: |
| 4419 | raise TypeError("Unable to convert %s to Decimal" % b) |
| 4420 | else: |
| 4421 | return r |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4422 | |
| 4423 | def divmod(self, a, b): |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4424 | """Return (a // b, a % b). |
Mark Dickinson | c53796e | 2010-01-06 16:22:15 +0000 | [diff] [blame] | 4425 | |
| 4426 | >>> ExtendedContext.divmod(Decimal(8), Decimal(3)) |
| 4427 | (Decimal('2'), Decimal('2')) |
| 4428 | >>> ExtendedContext.divmod(Decimal(8), Decimal(4)) |
| 4429 | (Decimal('2'), Decimal('0')) |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4430 | >>> ExtendedContext.divmod(8, 4) |
| 4431 | (Decimal('2'), Decimal('0')) |
| 4432 | >>> ExtendedContext.divmod(Decimal(8), 4) |
| 4433 | (Decimal('2'), Decimal('0')) |
| 4434 | >>> ExtendedContext.divmod(8, Decimal(4)) |
| 4435 | (Decimal('2'), Decimal('0')) |
Mark Dickinson | c53796e | 2010-01-06 16:22:15 +0000 | [diff] [blame] | 4436 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4437 | a = _convert_other(a, raiseit=True) |
| 4438 | r = a.__divmod__(b, context=self) |
| 4439 | if r is NotImplemented: |
| 4440 | raise TypeError("Unable to convert %s to Decimal" % b) |
| 4441 | else: |
| 4442 | return r |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4443 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4444 | def exp(self, a): |
| 4445 | """Returns e ** a. |
| 4446 | |
| 4447 | >>> c = ExtendedContext.copy() |
| 4448 | >>> c.Emin = -999 |
| 4449 | >>> c.Emax = 999 |
| 4450 | >>> c.exp(Decimal('-Infinity')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4451 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4452 | >>> c.exp(Decimal('-1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4453 | Decimal('0.367879441') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4454 | >>> c.exp(Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4455 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4456 | >>> c.exp(Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4457 | Decimal('2.71828183') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4458 | >>> c.exp(Decimal('0.693147181')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4459 | Decimal('2.00000000') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4460 | >>> c.exp(Decimal('+Infinity')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4461 | Decimal('Infinity') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4462 | >>> c.exp(10) |
| 4463 | Decimal('22026.4658') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4464 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4465 | a =_convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4466 | return a.exp(context=self) |
| 4467 | |
| 4468 | def fma(self, a, b, c): |
| 4469 | """Returns a multiplied by b, plus c. |
| 4470 | |
| 4471 | The first two operands are multiplied together, using multiply, |
| 4472 | the third operand is then added to the result of that |
| 4473 | multiplication, using add, all with only one final rounding. |
| 4474 | |
| 4475 | >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4476 | Decimal('22') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4477 | >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4478 | Decimal('-8') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4479 | >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4480 | Decimal('1.38435736E+12') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4481 | >>> ExtendedContext.fma(1, 3, 4) |
| 4482 | Decimal('7') |
| 4483 | >>> ExtendedContext.fma(1, Decimal(3), 4) |
| 4484 | Decimal('7') |
| 4485 | >>> ExtendedContext.fma(1, 3, Decimal(4)) |
| 4486 | Decimal('7') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4487 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4488 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4489 | return a.fma(b, c, context=self) |
| 4490 | |
| 4491 | def is_canonical(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4492 | """Return True if the operand is canonical; otherwise return False. |
| 4493 | |
| 4494 | Currently, the encoding of a Decimal instance is always |
| 4495 | canonical, so this method returns True for any Decimal. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4496 | |
| 4497 | >>> ExtendedContext.is_canonical(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4498 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4499 | """ |
Stefan Krah | 1919b7e | 2012-03-21 18:25:23 +0100 | [diff] [blame] | 4500 | if not isinstance(a, Decimal): |
| 4501 | raise TypeError("is_canonical requires a Decimal as an argument.") |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4502 | return a.is_canonical() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4503 | |
| 4504 | def is_finite(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4505 | """Return True if the operand is finite; otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4506 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4507 | A Decimal instance is considered finite if it is neither |
| 4508 | infinite nor a NaN. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4509 | |
| 4510 | >>> ExtendedContext.is_finite(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4511 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4512 | >>> ExtendedContext.is_finite(Decimal('-0.3')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4513 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4514 | >>> ExtendedContext.is_finite(Decimal('0')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4515 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4516 | >>> ExtendedContext.is_finite(Decimal('Inf')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4517 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4518 | >>> ExtendedContext.is_finite(Decimal('NaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4519 | False |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4520 | >>> ExtendedContext.is_finite(1) |
| 4521 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4522 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4523 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4524 | return a.is_finite() |
| 4525 | |
| 4526 | def is_infinite(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4527 | """Return True if the operand is infinite; otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4528 | |
| 4529 | >>> ExtendedContext.is_infinite(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4530 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4531 | >>> ExtendedContext.is_infinite(Decimal('-Inf')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4532 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4533 | >>> ExtendedContext.is_infinite(Decimal('NaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4534 | False |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4535 | >>> ExtendedContext.is_infinite(1) |
| 4536 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4537 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4538 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4539 | return a.is_infinite() |
| 4540 | |
| 4541 | def is_nan(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4542 | """Return True if the operand is a qNaN or sNaN; |
| 4543 | otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4544 | |
| 4545 | >>> ExtendedContext.is_nan(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4546 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4547 | >>> ExtendedContext.is_nan(Decimal('NaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4548 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4549 | >>> ExtendedContext.is_nan(Decimal('-sNaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4550 | True |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4551 | >>> ExtendedContext.is_nan(1) |
| 4552 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4553 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4554 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4555 | return a.is_nan() |
| 4556 | |
| 4557 | def is_normal(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4558 | """Return True if the operand is a normal number; |
| 4559 | otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4560 | |
| 4561 | >>> c = ExtendedContext.copy() |
| 4562 | >>> c.Emin = -999 |
| 4563 | >>> c.Emax = 999 |
| 4564 | >>> c.is_normal(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4565 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4566 | >>> c.is_normal(Decimal('0.1E-999')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4567 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4568 | >>> c.is_normal(Decimal('0.00')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4569 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4570 | >>> c.is_normal(Decimal('-Inf')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4571 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4572 | >>> c.is_normal(Decimal('NaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4573 | False |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4574 | >>> c.is_normal(1) |
| 4575 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4576 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4577 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4578 | return a.is_normal(context=self) |
| 4579 | |
| 4580 | def is_qnan(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4581 | """Return True if the operand is a quiet NaN; otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4582 | |
| 4583 | >>> ExtendedContext.is_qnan(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4584 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4585 | >>> ExtendedContext.is_qnan(Decimal('NaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4586 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4587 | >>> ExtendedContext.is_qnan(Decimal('sNaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4588 | False |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4589 | >>> ExtendedContext.is_qnan(1) |
| 4590 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4591 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4592 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4593 | return a.is_qnan() |
| 4594 | |
| 4595 | def is_signed(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4596 | """Return True if the operand is negative; otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4597 | |
| 4598 | >>> ExtendedContext.is_signed(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4599 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4600 | >>> ExtendedContext.is_signed(Decimal('-12')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4601 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4602 | >>> ExtendedContext.is_signed(Decimal('-0')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4603 | True |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4604 | >>> ExtendedContext.is_signed(8) |
| 4605 | False |
| 4606 | >>> ExtendedContext.is_signed(-8) |
| 4607 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4608 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4609 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4610 | return a.is_signed() |
| 4611 | |
| 4612 | def is_snan(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4613 | """Return True if the operand is a signaling NaN; |
| 4614 | otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4615 | |
| 4616 | >>> ExtendedContext.is_snan(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4617 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4618 | >>> ExtendedContext.is_snan(Decimal('NaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4619 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4620 | >>> ExtendedContext.is_snan(Decimal('sNaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4621 | True |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4622 | >>> ExtendedContext.is_snan(1) |
| 4623 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4624 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4625 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4626 | return a.is_snan() |
| 4627 | |
| 4628 | def is_subnormal(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4629 | """Return True if the operand is subnormal; otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4630 | |
| 4631 | >>> c = ExtendedContext.copy() |
| 4632 | >>> c.Emin = -999 |
| 4633 | >>> c.Emax = 999 |
| 4634 | >>> c.is_subnormal(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4635 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4636 | >>> c.is_subnormal(Decimal('0.1E-999')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4637 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4638 | >>> c.is_subnormal(Decimal('0.00')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4639 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4640 | >>> c.is_subnormal(Decimal('-Inf')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4641 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4642 | >>> c.is_subnormal(Decimal('NaN')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4643 | False |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4644 | >>> c.is_subnormal(1) |
| 4645 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4646 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4647 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4648 | return a.is_subnormal(context=self) |
| 4649 | |
| 4650 | def is_zero(self, a): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4651 | """Return True if the operand is a zero; otherwise return False. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4652 | |
| 4653 | >>> ExtendedContext.is_zero(Decimal('0')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4654 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4655 | >>> ExtendedContext.is_zero(Decimal('2.50')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4656 | False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4657 | >>> ExtendedContext.is_zero(Decimal('-0E+2')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 4658 | True |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4659 | >>> ExtendedContext.is_zero(1) |
| 4660 | False |
| 4661 | >>> ExtendedContext.is_zero(0) |
| 4662 | True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4663 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4664 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4665 | return a.is_zero() |
| 4666 | |
| 4667 | def ln(self, a): |
| 4668 | """Returns the natural (base e) logarithm of the operand. |
| 4669 | |
| 4670 | >>> c = ExtendedContext.copy() |
| 4671 | >>> c.Emin = -999 |
| 4672 | >>> c.Emax = 999 |
| 4673 | >>> c.ln(Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4674 | Decimal('-Infinity') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4675 | >>> c.ln(Decimal('1.000')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4676 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4677 | >>> c.ln(Decimal('2.71828183')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4678 | Decimal('1.00000000') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4679 | >>> c.ln(Decimal('10')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4680 | Decimal('2.30258509') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4681 | >>> c.ln(Decimal('+Infinity')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4682 | Decimal('Infinity') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4683 | >>> c.ln(1) |
| 4684 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4685 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4686 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4687 | return a.ln(context=self) |
| 4688 | |
| 4689 | def log10(self, a): |
| 4690 | """Returns the base 10 logarithm of the operand. |
| 4691 | |
| 4692 | >>> c = ExtendedContext.copy() |
| 4693 | >>> c.Emin = -999 |
| 4694 | >>> c.Emax = 999 |
| 4695 | >>> c.log10(Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4696 | Decimal('-Infinity') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4697 | >>> c.log10(Decimal('0.001')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4698 | Decimal('-3') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4699 | >>> c.log10(Decimal('1.000')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4700 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4701 | >>> c.log10(Decimal('2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4702 | Decimal('0.301029996') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4703 | >>> c.log10(Decimal('10')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4704 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4705 | >>> c.log10(Decimal('70')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4706 | Decimal('1.84509804') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4707 | >>> c.log10(Decimal('+Infinity')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4708 | Decimal('Infinity') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4709 | >>> c.log10(0) |
| 4710 | Decimal('-Infinity') |
| 4711 | >>> c.log10(1) |
| 4712 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4713 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4714 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4715 | return a.log10(context=self) |
| 4716 | |
| 4717 | def logb(self, a): |
| 4718 | """ Returns the exponent of the magnitude of the operand's MSD. |
| 4719 | |
| 4720 | The result is the integer which is the exponent of the magnitude |
| 4721 | of the most significant digit of the operand (as though the |
| 4722 | operand were truncated to a single digit while maintaining the |
| 4723 | value of that digit and without limiting the resulting exponent). |
| 4724 | |
| 4725 | >>> ExtendedContext.logb(Decimal('250')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4726 | Decimal('2') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4727 | >>> ExtendedContext.logb(Decimal('2.50')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4728 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4729 | >>> ExtendedContext.logb(Decimal('0.03')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4730 | Decimal('-2') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4731 | >>> ExtendedContext.logb(Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4732 | Decimal('-Infinity') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4733 | >>> ExtendedContext.logb(1) |
| 4734 | Decimal('0') |
| 4735 | >>> ExtendedContext.logb(10) |
| 4736 | Decimal('1') |
| 4737 | >>> ExtendedContext.logb(100) |
| 4738 | Decimal('2') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4739 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4740 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4741 | return a.logb(context=self) |
| 4742 | |
| 4743 | def logical_and(self, a, b): |
| 4744 | """Applies the logical operation 'and' between each operand's digits. |
| 4745 | |
| 4746 | The operands must be both logical numbers. |
| 4747 | |
| 4748 | >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4749 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4750 | >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4751 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4752 | >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4753 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4754 | >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4755 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4756 | >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4757 | Decimal('1000') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4758 | >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4759 | Decimal('10') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4760 | >>> ExtendedContext.logical_and(110, 1101) |
| 4761 | Decimal('100') |
| 4762 | >>> ExtendedContext.logical_and(Decimal(110), 1101) |
| 4763 | Decimal('100') |
| 4764 | >>> ExtendedContext.logical_and(110, Decimal(1101)) |
| 4765 | Decimal('100') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4766 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4767 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4768 | return a.logical_and(b, context=self) |
| 4769 | |
| 4770 | def logical_invert(self, a): |
| 4771 | """Invert all the digits in the operand. |
| 4772 | |
| 4773 | The operand must be a logical number. |
| 4774 | |
| 4775 | >>> ExtendedContext.logical_invert(Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4776 | Decimal('111111111') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4777 | >>> ExtendedContext.logical_invert(Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4778 | Decimal('111111110') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4779 | >>> ExtendedContext.logical_invert(Decimal('111111111')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4780 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4781 | >>> ExtendedContext.logical_invert(Decimal('101010101')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4782 | Decimal('10101010') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4783 | >>> ExtendedContext.logical_invert(1101) |
| 4784 | Decimal('111110010') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4785 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4786 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4787 | return a.logical_invert(context=self) |
| 4788 | |
| 4789 | def logical_or(self, a, b): |
| 4790 | """Applies the logical operation 'or' between each operand's digits. |
| 4791 | |
| 4792 | The operands must be both logical numbers. |
| 4793 | |
| 4794 | >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4795 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4796 | >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4797 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4798 | >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4799 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4800 | >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4801 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4802 | >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4803 | Decimal('1110') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4804 | >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4805 | Decimal('1110') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4806 | >>> ExtendedContext.logical_or(110, 1101) |
| 4807 | Decimal('1111') |
| 4808 | >>> ExtendedContext.logical_or(Decimal(110), 1101) |
| 4809 | Decimal('1111') |
| 4810 | >>> ExtendedContext.logical_or(110, Decimal(1101)) |
| 4811 | Decimal('1111') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4812 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4813 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4814 | return a.logical_or(b, context=self) |
| 4815 | |
| 4816 | def logical_xor(self, a, b): |
| 4817 | """Applies the logical operation 'xor' between each operand's digits. |
| 4818 | |
| 4819 | The operands must be both logical numbers. |
| 4820 | |
| 4821 | >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4822 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4823 | >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4824 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4825 | >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4826 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4827 | >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4828 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4829 | >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4830 | Decimal('110') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4831 | >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4832 | Decimal('1101') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4833 | >>> ExtendedContext.logical_xor(110, 1101) |
| 4834 | Decimal('1011') |
| 4835 | >>> ExtendedContext.logical_xor(Decimal(110), 1101) |
| 4836 | Decimal('1011') |
| 4837 | >>> ExtendedContext.logical_xor(110, Decimal(1101)) |
| 4838 | Decimal('1011') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4839 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4840 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4841 | return a.logical_xor(b, context=self) |
| 4842 | |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4843 | def max(self, a, b): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4844 | """max compares two values numerically and returns the maximum. |
| 4845 | |
| 4846 | If either operand is a NaN then the general rules apply. |
Christian Heimes | 679db4a | 2008-01-18 09:56:22 +0000 | [diff] [blame] | 4847 | Otherwise, the operands are compared as though by the compare |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 4848 | operation. If they are numerically equal then the left-hand operand |
| 4849 | is chosen as the result. Otherwise the maximum (closer to positive |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4850 | infinity) of the two operands is chosen as the result. |
| 4851 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4852 | >>> ExtendedContext.max(Decimal('3'), Decimal('2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4853 | Decimal('3') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4854 | >>> ExtendedContext.max(Decimal('-10'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4855 | Decimal('3') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4856 | >>> ExtendedContext.max(Decimal('1.0'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4857 | Decimal('1') |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 4858 | >>> ExtendedContext.max(Decimal('7'), Decimal('NaN')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4859 | Decimal('7') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4860 | >>> ExtendedContext.max(1, 2) |
| 4861 | Decimal('2') |
| 4862 | >>> ExtendedContext.max(Decimal(1), 2) |
| 4863 | Decimal('2') |
| 4864 | >>> ExtendedContext.max(1, Decimal(2)) |
| 4865 | Decimal('2') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4866 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4867 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4868 | return a.max(b, context=self) |
| 4869 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4870 | def max_mag(self, a, b): |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4871 | """Compares the values numerically with their sign ignored. |
| 4872 | |
| 4873 | >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN')) |
| 4874 | Decimal('7') |
| 4875 | >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10')) |
| 4876 | Decimal('-10') |
| 4877 | >>> ExtendedContext.max_mag(1, -2) |
| 4878 | Decimal('-2') |
| 4879 | >>> ExtendedContext.max_mag(Decimal(1), -2) |
| 4880 | Decimal('-2') |
| 4881 | >>> ExtendedContext.max_mag(1, Decimal(-2)) |
| 4882 | Decimal('-2') |
| 4883 | """ |
| 4884 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4885 | return a.max_mag(b, context=self) |
| 4886 | |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4887 | def min(self, a, b): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4888 | """min compares two values numerically and returns the minimum. |
| 4889 | |
| 4890 | If either operand is a NaN then the general rules apply. |
Christian Heimes | 679db4a | 2008-01-18 09:56:22 +0000 | [diff] [blame] | 4891 | Otherwise, the operands are compared as though by the compare |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 4892 | operation. If they are numerically equal then the left-hand operand |
| 4893 | is chosen as the result. Otherwise the minimum (closer to negative |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4894 | infinity) of the two operands is chosen as the result. |
| 4895 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4896 | >>> ExtendedContext.min(Decimal('3'), Decimal('2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4897 | Decimal('2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4898 | >>> ExtendedContext.min(Decimal('-10'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4899 | Decimal('-10') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4900 | >>> ExtendedContext.min(Decimal('1.0'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4901 | Decimal('1.0') |
Raymond Hettinger | d6c700a | 2004-08-17 06:39:37 +0000 | [diff] [blame] | 4902 | >>> ExtendedContext.min(Decimal('7'), Decimal('NaN')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4903 | Decimal('7') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4904 | >>> ExtendedContext.min(1, 2) |
| 4905 | Decimal('1') |
| 4906 | >>> ExtendedContext.min(Decimal(1), 2) |
| 4907 | Decimal('1') |
| 4908 | >>> ExtendedContext.min(1, Decimal(29)) |
| 4909 | Decimal('1') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4910 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4911 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4912 | return a.min(b, context=self) |
| 4913 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4914 | def min_mag(self, a, b): |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4915 | """Compares the values numerically with their sign ignored. |
| 4916 | |
| 4917 | >>> ExtendedContext.min_mag(Decimal('3'), Decimal('-2')) |
| 4918 | Decimal('-2') |
| 4919 | >>> ExtendedContext.min_mag(Decimal('-3'), Decimal('NaN')) |
| 4920 | Decimal('-3') |
| 4921 | >>> ExtendedContext.min_mag(1, -2) |
| 4922 | Decimal('1') |
| 4923 | >>> ExtendedContext.min_mag(Decimal(1), -2) |
| 4924 | Decimal('1') |
| 4925 | >>> ExtendedContext.min_mag(1, Decimal(-2)) |
| 4926 | Decimal('1') |
| 4927 | """ |
| 4928 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4929 | return a.min_mag(b, context=self) |
| 4930 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4931 | def minus(self, a): |
| 4932 | """Minus corresponds to unary prefix minus in Python. |
| 4933 | |
| 4934 | The operation is evaluated using the same rules as subtract; the |
| 4935 | operation minus(a) is calculated as subtract('0', a) where the '0' |
| 4936 | has the same exponent as the operand. |
| 4937 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4938 | >>> ExtendedContext.minus(Decimal('1.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4939 | Decimal('-1.3') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4940 | >>> ExtendedContext.minus(Decimal('-1.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4941 | Decimal('1.3') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4942 | >>> ExtendedContext.minus(1) |
| 4943 | Decimal('-1') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4944 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4945 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4946 | return a.__neg__(context=self) |
| 4947 | |
| 4948 | def multiply(self, a, b): |
| 4949 | """multiply multiplies two operands. |
| 4950 | |
| 4951 | If either operand is a special value then the general rules apply. |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4952 | Otherwise, the operands are multiplied together |
| 4953 | ('long multiplication'), resulting in a number which may be as long as |
| 4954 | the sum of the lengths of the two operands. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4955 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4956 | >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4957 | Decimal('3.60') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4958 | >>> ExtendedContext.multiply(Decimal('7'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4959 | Decimal('21') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4960 | >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4961 | Decimal('0.72') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4962 | >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4963 | Decimal('-0.0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 4964 | >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4965 | Decimal('4.28135971E+11') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4966 | >>> ExtendedContext.multiply(7, 7) |
| 4967 | Decimal('49') |
| 4968 | >>> ExtendedContext.multiply(Decimal(7), 7) |
| 4969 | Decimal('49') |
| 4970 | >>> ExtendedContext.multiply(7, Decimal(7)) |
| 4971 | Decimal('49') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4972 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4973 | a = _convert_other(a, raiseit=True) |
| 4974 | r = a.__mul__(b, context=self) |
| 4975 | if r is NotImplemented: |
| 4976 | raise TypeError("Unable to convert %s to Decimal" % b) |
| 4977 | else: |
| 4978 | return r |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 4979 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4980 | def next_minus(self, a): |
| 4981 | """Returns the largest representable number smaller than a. |
| 4982 | |
| 4983 | >>> c = ExtendedContext.copy() |
| 4984 | >>> c.Emin = -999 |
| 4985 | >>> c.Emax = 999 |
| 4986 | >>> ExtendedContext.next_minus(Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4987 | Decimal('0.999999999') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4988 | >>> c.next_minus(Decimal('1E-1007')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4989 | Decimal('0E-1007') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4990 | >>> ExtendedContext.next_minus(Decimal('-1.00000003')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4991 | Decimal('-1.00000004') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4992 | >>> c.next_minus(Decimal('Infinity')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 4993 | Decimal('9.99999999E+999') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4994 | >>> c.next_minus(1) |
| 4995 | Decimal('0.999999999') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4996 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 4997 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 4998 | return a.next_minus(context=self) |
| 4999 | |
| 5000 | def next_plus(self, a): |
| 5001 | """Returns the smallest representable number larger than a. |
| 5002 | |
| 5003 | >>> c = ExtendedContext.copy() |
| 5004 | >>> c.Emin = -999 |
| 5005 | >>> c.Emax = 999 |
| 5006 | >>> ExtendedContext.next_plus(Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5007 | Decimal('1.00000001') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5008 | >>> c.next_plus(Decimal('-1E-1007')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5009 | Decimal('-0E-1007') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5010 | >>> ExtendedContext.next_plus(Decimal('-1.00000003')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5011 | Decimal('-1.00000002') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5012 | >>> c.next_plus(Decimal('-Infinity')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5013 | Decimal('-9.99999999E+999') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5014 | >>> c.next_plus(1) |
| 5015 | Decimal('1.00000001') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5016 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5017 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5018 | return a.next_plus(context=self) |
| 5019 | |
| 5020 | def next_toward(self, a, b): |
| 5021 | """Returns the number closest to a, in direction towards b. |
| 5022 | |
| 5023 | The result is the closest representable number from the first |
| 5024 | operand (but not the first operand) that is in the direction |
| 5025 | towards the second operand, unless the operands have the same |
| 5026 | value. |
| 5027 | |
| 5028 | >>> c = ExtendedContext.copy() |
| 5029 | >>> c.Emin = -999 |
| 5030 | >>> c.Emax = 999 |
| 5031 | >>> c.next_toward(Decimal('1'), Decimal('2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5032 | Decimal('1.00000001') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5033 | >>> c.next_toward(Decimal('-1E-1007'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5034 | Decimal('-0E-1007') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5035 | >>> c.next_toward(Decimal('-1.00000003'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5036 | Decimal('-1.00000002') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5037 | >>> c.next_toward(Decimal('1'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5038 | Decimal('0.999999999') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5039 | >>> c.next_toward(Decimal('1E-1007'), Decimal('-100')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5040 | Decimal('0E-1007') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5041 | >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5042 | Decimal('-1.00000004') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5043 | >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5044 | Decimal('-0.00') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5045 | >>> c.next_toward(0, 1) |
| 5046 | Decimal('1E-1007') |
| 5047 | >>> c.next_toward(Decimal(0), 1) |
| 5048 | Decimal('1E-1007') |
| 5049 | >>> c.next_toward(0, Decimal(1)) |
| 5050 | Decimal('1E-1007') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5051 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5052 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5053 | return a.next_toward(b, context=self) |
| 5054 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5055 | def normalize(self, a): |
Raymond Hettinger | e0f1581 | 2004-07-05 05:36:39 +0000 | [diff] [blame] | 5056 | """normalize reduces an operand to its simplest form. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5057 | |
| 5058 | Essentially a plus operation with all trailing zeros removed from the |
| 5059 | result. |
| 5060 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5061 | >>> ExtendedContext.normalize(Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5062 | Decimal('2.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5063 | >>> ExtendedContext.normalize(Decimal('-2.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.normalize(Decimal('1.200')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5066 | Decimal('1.2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5067 | >>> ExtendedContext.normalize(Decimal('-120')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5068 | Decimal('-1.2E+2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5069 | >>> ExtendedContext.normalize(Decimal('120.00')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5070 | Decimal('1.2E+2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5071 | >>> ExtendedContext.normalize(Decimal('0.00')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5072 | Decimal('0') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5073 | >>> ExtendedContext.normalize(6) |
| 5074 | Decimal('6') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5075 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5076 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5077 | return a.normalize(context=self) |
| 5078 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5079 | def number_class(self, a): |
| 5080 | """Returns an indication of the class of the operand. |
| 5081 | |
| 5082 | The class is one of the following strings: |
| 5083 | -sNaN |
| 5084 | -NaN |
| 5085 | -Infinity |
| 5086 | -Normal |
| 5087 | -Subnormal |
| 5088 | -Zero |
| 5089 | +Zero |
| 5090 | +Subnormal |
| 5091 | +Normal |
| 5092 | +Infinity |
| 5093 | |
Stefan Krah | 1919b7e | 2012-03-21 18:25:23 +0100 | [diff] [blame] | 5094 | >>> c = ExtendedContext.copy() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5095 | >>> c.Emin = -999 |
| 5096 | >>> c.Emax = 999 |
| 5097 | >>> c.number_class(Decimal('Infinity')) |
| 5098 | '+Infinity' |
| 5099 | >>> c.number_class(Decimal('1E-10')) |
| 5100 | '+Normal' |
| 5101 | >>> c.number_class(Decimal('2.50')) |
| 5102 | '+Normal' |
| 5103 | >>> c.number_class(Decimal('0.1E-999')) |
| 5104 | '+Subnormal' |
| 5105 | >>> c.number_class(Decimal('0')) |
| 5106 | '+Zero' |
| 5107 | >>> c.number_class(Decimal('-0')) |
| 5108 | '-Zero' |
| 5109 | >>> c.number_class(Decimal('-0.1E-999')) |
| 5110 | '-Subnormal' |
| 5111 | >>> c.number_class(Decimal('-1E-10')) |
| 5112 | '-Normal' |
| 5113 | >>> c.number_class(Decimal('-2.50')) |
| 5114 | '-Normal' |
| 5115 | >>> c.number_class(Decimal('-Infinity')) |
| 5116 | '-Infinity' |
| 5117 | >>> c.number_class(Decimal('NaN')) |
| 5118 | 'NaN' |
| 5119 | >>> c.number_class(Decimal('-NaN')) |
| 5120 | 'NaN' |
| 5121 | >>> c.number_class(Decimal('sNaN')) |
| 5122 | 'sNaN' |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5123 | >>> c.number_class(123) |
| 5124 | '+Normal' |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5125 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5126 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5127 | return a.number_class(context=self) |
| 5128 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5129 | def plus(self, a): |
| 5130 | """Plus corresponds to unary prefix plus in Python. |
| 5131 | |
| 5132 | The operation is evaluated using the same rules as add; the |
| 5133 | operation plus(a) is calculated as add('0', a) where the '0' |
| 5134 | has the same exponent as the operand. |
| 5135 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5136 | >>> ExtendedContext.plus(Decimal('1.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5137 | Decimal('1.3') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5138 | >>> ExtendedContext.plus(Decimal('-1.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5139 | Decimal('-1.3') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5140 | >>> ExtendedContext.plus(-1) |
| 5141 | Decimal('-1') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5142 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5143 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5144 | return a.__pos__(context=self) |
| 5145 | |
| 5146 | def power(self, a, b, modulo=None): |
| 5147 | """Raises a to the power of b, to modulo if given. |
| 5148 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5149 | With two arguments, compute a**b. If a is negative then b |
| 5150 | must be integral. The result will be inexact unless b is |
| 5151 | integral and the result is finite and can be expressed exactly |
| 5152 | in 'precision' digits. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5153 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5154 | With three arguments, compute (a**b) % modulo. For the |
| 5155 | three argument form, the following restrictions on the |
| 5156 | arguments hold: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5157 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5158 | - all three arguments must be integral |
| 5159 | - b must be nonnegative |
| 5160 | - at least one of a or b must be nonzero |
| 5161 | - modulo must be nonzero and have at most 'precision' digits |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5162 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5163 | The result of pow(a, b, modulo) is identical to the result |
| 5164 | that would be obtained by computing (a**b) % modulo with |
| 5165 | unbounded precision, but is computed more efficiently. It is |
| 5166 | always exact. |
| 5167 | |
| 5168 | >>> c = ExtendedContext.copy() |
| 5169 | >>> c.Emin = -999 |
| 5170 | >>> c.Emax = 999 |
| 5171 | >>> c.power(Decimal('2'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5172 | Decimal('8') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5173 | >>> c.power(Decimal('-2'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5174 | Decimal('-8') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5175 | >>> c.power(Decimal('2'), Decimal('-3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5176 | Decimal('0.125') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5177 | >>> c.power(Decimal('1.7'), Decimal('8')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5178 | Decimal('69.7575744') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5179 | >>> c.power(Decimal('10'), Decimal('0.301029996')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5180 | Decimal('2.00000000') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5181 | >>> c.power(Decimal('Infinity'), Decimal('-1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5182 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5183 | >>> c.power(Decimal('Infinity'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5184 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5185 | >>> c.power(Decimal('Infinity'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5186 | Decimal('Infinity') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5187 | >>> c.power(Decimal('-Infinity'), Decimal('-1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5188 | Decimal('-0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5189 | >>> c.power(Decimal('-Infinity'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5190 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5191 | >>> c.power(Decimal('-Infinity'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5192 | Decimal('-Infinity') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5193 | >>> c.power(Decimal('-Infinity'), Decimal('2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5194 | Decimal('Infinity') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5195 | >>> c.power(Decimal('0'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5196 | Decimal('NaN') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5197 | |
| 5198 | >>> c.power(Decimal('3'), Decimal('7'), Decimal('16')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5199 | Decimal('11') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5200 | >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5201 | Decimal('-11') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5202 | >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5203 | Decimal('1') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5204 | >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5205 | Decimal('11') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5206 | >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5207 | Decimal('11729830') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5208 | >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5209 | Decimal('-0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5210 | >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5211 | Decimal('1') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5212 | >>> ExtendedContext.power(7, 7) |
| 5213 | Decimal('823543') |
| 5214 | >>> ExtendedContext.power(Decimal(7), 7) |
| 5215 | Decimal('823543') |
| 5216 | >>> ExtendedContext.power(7, Decimal(7), 2) |
| 5217 | Decimal('1') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5218 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5219 | a = _convert_other(a, raiseit=True) |
| 5220 | r = a.__pow__(b, modulo, context=self) |
| 5221 | if r is NotImplemented: |
| 5222 | raise TypeError("Unable to convert %s to Decimal" % b) |
| 5223 | else: |
| 5224 | return r |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5225 | |
| 5226 | def quantize(self, a, b): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 5227 | """Returns a value equal to 'a' (rounded), having the exponent of 'b'. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5228 | |
| 5229 | 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] | 5230 | operand. It may be rounded using the current rounding setting (if the |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5231 | exponent is being increased), multiplied by a positive power of ten (if |
| 5232 | the exponent is being decreased), or is unchanged (if the exponent is |
| 5233 | already equal to that of the right-hand operand). |
| 5234 | |
| 5235 | Unlike other operations, if the length of the coefficient after the |
| 5236 | quantize operation would be greater than precision then an Invalid |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 5237 | operation condition is raised. This guarantees that, unless there is |
| 5238 | 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] | 5239 | equal to that of the right-hand operand. |
| 5240 | |
| 5241 | Also unlike other operations, quantize will never raise Underflow, even |
| 5242 | if the result is subnormal and inexact. |
| 5243 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5244 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5245 | Decimal('2.170') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5246 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5247 | Decimal('2.17') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5248 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5249 | Decimal('2.2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5250 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5251 | Decimal('2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5252 | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5253 | Decimal('0E+1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5254 | >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5255 | Decimal('-Infinity') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5256 | >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5257 | Decimal('NaN') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5258 | >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5259 | Decimal('-0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5260 | >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5261 | Decimal('-0E+5') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5262 | >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5263 | Decimal('NaN') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5264 | >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5265 | Decimal('NaN') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5266 | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5267 | Decimal('217.0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5268 | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5269 | Decimal('217') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5270 | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5271 | Decimal('2.2E+2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5272 | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5273 | Decimal('2E+2') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5274 | >>> ExtendedContext.quantize(1, 2) |
| 5275 | Decimal('1') |
| 5276 | >>> ExtendedContext.quantize(Decimal(1), 2) |
| 5277 | Decimal('1') |
| 5278 | >>> ExtendedContext.quantize(1, Decimal(2)) |
| 5279 | Decimal('1') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5280 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5281 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5282 | return a.quantize(b, context=self) |
| 5283 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5284 | def radix(self): |
| 5285 | """Just returns 10, as this is Decimal, :) |
| 5286 | |
| 5287 | >>> ExtendedContext.radix() |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5288 | Decimal('10') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5289 | """ |
| 5290 | return Decimal(10) |
| 5291 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5292 | def remainder(self, a, b): |
| 5293 | """Returns the remainder from integer division. |
| 5294 | |
| 5295 | 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] | 5296 | calculating integer division as described for divide-integer, rounded |
| 5297 | to precision digits if necessary. The sign of the result, if |
| 5298 | non-zero, is the same as that of the original dividend. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5299 | |
| 5300 | This operation will fail under the same conditions as integer division |
| 5301 | (that is, if integer division on the same two operands would fail, the |
| 5302 | remainder cannot be calculated). |
| 5303 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5304 | >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5305 | Decimal('2.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5306 | >>> ExtendedContext.remainder(Decimal('10'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5307 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5308 | >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5309 | Decimal('-1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5310 | >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5311 | Decimal('0.2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5312 | >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5313 | Decimal('0.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5314 | >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5315 | Decimal('1.0') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5316 | >>> ExtendedContext.remainder(22, 6) |
| 5317 | Decimal('4') |
| 5318 | >>> ExtendedContext.remainder(Decimal(22), 6) |
| 5319 | Decimal('4') |
| 5320 | >>> ExtendedContext.remainder(22, Decimal(6)) |
| 5321 | Decimal('4') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5322 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5323 | a = _convert_other(a, raiseit=True) |
| 5324 | r = a.__mod__(b, context=self) |
| 5325 | if r is NotImplemented: |
| 5326 | raise TypeError("Unable to convert %s to Decimal" % b) |
| 5327 | else: |
| 5328 | return r |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5329 | |
| 5330 | def remainder_near(self, a, b): |
| 5331 | """Returns to be "a - b * n", where n is the integer nearest the exact |
| 5332 | 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] | 5333 | 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] | 5334 | sign of a. |
| 5335 | |
| 5336 | This operation will fail under the same conditions as integer division |
| 5337 | (that is, if integer division on the same two operands would fail, the |
| 5338 | remainder cannot be calculated). |
| 5339 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5340 | >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5341 | Decimal('-0.9') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5342 | >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5343 | Decimal('-2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5344 | >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5345 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5346 | >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5347 | Decimal('-1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5348 | >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5349 | Decimal('0.2') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5350 | >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5351 | Decimal('0.1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5352 | >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5353 | Decimal('-0.3') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5354 | >>> ExtendedContext.remainder_near(3, 11) |
| 5355 | Decimal('3') |
| 5356 | >>> ExtendedContext.remainder_near(Decimal(3), 11) |
| 5357 | Decimal('3') |
| 5358 | >>> ExtendedContext.remainder_near(3, Decimal(11)) |
| 5359 | Decimal('3') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5360 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5361 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5362 | return a.remainder_near(b, context=self) |
| 5363 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5364 | def rotate(self, a, b): |
| 5365 | """Returns a rotated copy of a, b times. |
| 5366 | |
| 5367 | The coefficient of the result is a rotated copy of the digits in |
| 5368 | the coefficient of the first operand. The number of places of |
| 5369 | rotation is taken from the absolute value of the second operand, |
| 5370 | with the rotation being to the left if the second operand is |
| 5371 | positive or to the right otherwise. |
| 5372 | |
| 5373 | >>> ExtendedContext.rotate(Decimal('34'), Decimal('8')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5374 | Decimal('400000003') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5375 | >>> ExtendedContext.rotate(Decimal('12'), Decimal('9')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5376 | Decimal('12') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5377 | >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5378 | Decimal('891234567') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5379 | >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5380 | Decimal('123456789') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5381 | >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5382 | Decimal('345678912') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5383 | >>> ExtendedContext.rotate(1333333, 1) |
| 5384 | Decimal('13333330') |
| 5385 | >>> ExtendedContext.rotate(Decimal(1333333), 1) |
| 5386 | Decimal('13333330') |
| 5387 | >>> ExtendedContext.rotate(1333333, Decimal(1)) |
| 5388 | Decimal('13333330') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5389 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5390 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5391 | return a.rotate(b, context=self) |
| 5392 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5393 | def same_quantum(self, a, b): |
| 5394 | """Returns True if the two operands have the same exponent. |
| 5395 | |
| 5396 | The result is never affected by either the sign or the coefficient of |
| 5397 | either operand. |
| 5398 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5399 | >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5400 | False |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5401 | >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5402 | True |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5403 | >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5404 | False |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5405 | >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5406 | True |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5407 | >>> ExtendedContext.same_quantum(10000, -1) |
| 5408 | True |
| 5409 | >>> ExtendedContext.same_quantum(Decimal(10000), -1) |
| 5410 | True |
| 5411 | >>> ExtendedContext.same_quantum(10000, Decimal(-1)) |
| 5412 | True |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5413 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5414 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5415 | return a.same_quantum(b) |
| 5416 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5417 | def scaleb (self, a, b): |
| 5418 | """Returns the first operand after adding the second value its exp. |
| 5419 | |
| 5420 | >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5421 | Decimal('0.0750') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5422 | >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5423 | Decimal('7.50') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5424 | >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5425 | Decimal('7.50E+3') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5426 | >>> ExtendedContext.scaleb(1, 4) |
| 5427 | Decimal('1E+4') |
| 5428 | >>> ExtendedContext.scaleb(Decimal(1), 4) |
| 5429 | Decimal('1E+4') |
| 5430 | >>> ExtendedContext.scaleb(1, Decimal(4)) |
| 5431 | Decimal('1E+4') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5432 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5433 | a = _convert_other(a, raiseit=True) |
| 5434 | return a.scaleb(b, context=self) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5435 | |
| 5436 | def shift(self, a, b): |
| 5437 | """Returns a shifted copy of a, b times. |
| 5438 | |
| 5439 | The coefficient of the result is a shifted copy of the digits |
| 5440 | in the coefficient of the first operand. The number of places |
| 5441 | to shift is taken from the absolute value of the second operand, |
| 5442 | with the shift being to the left if the second operand is |
| 5443 | positive or to the right otherwise. Digits shifted into the |
| 5444 | coefficient are zeros. |
| 5445 | |
| 5446 | >>> ExtendedContext.shift(Decimal('34'), Decimal('8')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5447 | Decimal('400000000') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5448 | >>> ExtendedContext.shift(Decimal('12'), Decimal('9')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5449 | Decimal('0') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5450 | >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5451 | Decimal('1234567') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5452 | >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5453 | Decimal('123456789') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5454 | >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5455 | Decimal('345678900') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5456 | >>> ExtendedContext.shift(88888888, 2) |
| 5457 | Decimal('888888800') |
| 5458 | >>> ExtendedContext.shift(Decimal(88888888), 2) |
| 5459 | Decimal('888888800') |
| 5460 | >>> ExtendedContext.shift(88888888, Decimal(2)) |
| 5461 | Decimal('888888800') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5462 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5463 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5464 | return a.shift(b, context=self) |
| 5465 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5466 | def sqrt(self, a): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 5467 | """Square root of a non-negative number to context precision. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5468 | |
| 5469 | If the result must be inexact, it is rounded using the round-half-even |
| 5470 | algorithm. |
| 5471 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5472 | >>> ExtendedContext.sqrt(Decimal('0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5473 | Decimal('0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5474 | >>> ExtendedContext.sqrt(Decimal('-0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5475 | Decimal('-0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5476 | >>> ExtendedContext.sqrt(Decimal('0.39')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5477 | Decimal('0.624499800') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5478 | >>> ExtendedContext.sqrt(Decimal('100')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5479 | Decimal('10') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5480 | >>> ExtendedContext.sqrt(Decimal('1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5481 | Decimal('1') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5482 | >>> ExtendedContext.sqrt(Decimal('1.0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5483 | Decimal('1.0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5484 | >>> ExtendedContext.sqrt(Decimal('1.00')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5485 | Decimal('1.0') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5486 | >>> ExtendedContext.sqrt(Decimal('7')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5487 | Decimal('2.64575131') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5488 | >>> ExtendedContext.sqrt(Decimal('10')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5489 | Decimal('3.16227766') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5490 | >>> ExtendedContext.sqrt(2) |
| 5491 | Decimal('1.41421356') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5492 | >>> ExtendedContext.prec |
Raymond Hettinger | 6ea4845 | 2004-07-03 12:26:21 +0000 | [diff] [blame] | 5493 | 9 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5494 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5495 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5496 | return a.sqrt(context=self) |
| 5497 | |
| 5498 | def subtract(self, a, b): |
Georg Brandl | f33d01d | 2005-08-22 19:35:18 +0000 | [diff] [blame] | 5499 | """Return the difference between the two operands. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5500 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5501 | >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5502 | Decimal('0.23') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5503 | >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5504 | Decimal('0.00') |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 5505 | >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5506 | Decimal('-0.77') |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5507 | >>> ExtendedContext.subtract(8, 5) |
| 5508 | Decimal('3') |
| 5509 | >>> ExtendedContext.subtract(Decimal(8), 5) |
| 5510 | Decimal('3') |
| 5511 | >>> ExtendedContext.subtract(8, Decimal(5)) |
| 5512 | Decimal('3') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5513 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5514 | a = _convert_other(a, raiseit=True) |
| 5515 | r = a.__sub__(b, context=self) |
| 5516 | if r is NotImplemented: |
| 5517 | raise TypeError("Unable to convert %s to Decimal" % b) |
| 5518 | else: |
| 5519 | return r |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5520 | |
| 5521 | def to_eng_string(self, a): |
| 5522 | """Converts a number to a string, using scientific notation. |
| 5523 | |
| 5524 | The operation is not affected by the context. |
| 5525 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5526 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5527 | return a.to_eng_string(context=self) |
| 5528 | |
| 5529 | def to_sci_string(self, a): |
| 5530 | """Converts a number to a string, using scientific notation. |
| 5531 | |
| 5532 | The operation is not affected by the context. |
| 5533 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5534 | a = _convert_other(a, raiseit=True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5535 | return a.__str__(context=self) |
| 5536 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5537 | def to_integral_exact(self, a): |
| 5538 | """Rounds to an integer. |
| 5539 | |
| 5540 | When the operand has a negative exponent, the result is the same |
| 5541 | as using the quantize() operation using the given operand as the |
| 5542 | left-hand-operand, 1E+0 as the right-hand-operand, and the precision |
| 5543 | of the operand as the precision setting; Inexact and Rounded flags |
| 5544 | are allowed in this operation. The rounding mode is taken from the |
| 5545 | context. |
| 5546 | |
| 5547 | >>> ExtendedContext.to_integral_exact(Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5548 | Decimal('2') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5549 | >>> ExtendedContext.to_integral_exact(Decimal('100')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5550 | Decimal('100') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5551 | >>> ExtendedContext.to_integral_exact(Decimal('100.0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5552 | Decimal('100') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5553 | >>> ExtendedContext.to_integral_exact(Decimal('101.5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5554 | Decimal('102') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5555 | >>> ExtendedContext.to_integral_exact(Decimal('-101.5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5556 | Decimal('-102') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5557 | >>> ExtendedContext.to_integral_exact(Decimal('10E+5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5558 | Decimal('1.0E+6') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5559 | >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5560 | Decimal('7.89E+77') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5561 | >>> ExtendedContext.to_integral_exact(Decimal('-Inf')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5562 | Decimal('-Infinity') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5563 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5564 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5565 | return a.to_integral_exact(context=self) |
| 5566 | |
| 5567 | def to_integral_value(self, a): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5568 | """Rounds to an integer. |
| 5569 | |
| 5570 | When the operand has a negative exponent, the result is the same |
| 5571 | as using the quantize() operation using the given operand as the |
| 5572 | left-hand-operand, 1E+0 as the right-hand-operand, and the precision |
| 5573 | 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] | 5574 | be set. The rounding mode is taken from the context. |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5575 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5576 | >>> ExtendedContext.to_integral_value(Decimal('2.1')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5577 | Decimal('2') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5578 | >>> ExtendedContext.to_integral_value(Decimal('100')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5579 | Decimal('100') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5580 | >>> ExtendedContext.to_integral_value(Decimal('100.0')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5581 | Decimal('100') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5582 | >>> ExtendedContext.to_integral_value(Decimal('101.5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5583 | Decimal('102') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5584 | >>> ExtendedContext.to_integral_value(Decimal('-101.5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5585 | Decimal('-102') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5586 | >>> ExtendedContext.to_integral_value(Decimal('10E+5')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5587 | Decimal('1.0E+6') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5588 | >>> ExtendedContext.to_integral_value(Decimal('7.89E+77')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5589 | Decimal('7.89E+77') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5590 | >>> ExtendedContext.to_integral_value(Decimal('-Inf')) |
Christian Heimes | 68f5fbe | 2008-02-14 08:27:37 +0000 | [diff] [blame] | 5591 | Decimal('-Infinity') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5592 | """ |
Mark Dickinson | 84230a1 | 2010-02-18 14:49:50 +0000 | [diff] [blame] | 5593 | a = _convert_other(a, raiseit=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5594 | return a.to_integral_value(context=self) |
| 5595 | |
| 5596 | # the method name changed, but we provide also the old one, for compatibility |
| 5597 | to_integral = to_integral_value |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5598 | |
| 5599 | class _WorkRep(object): |
| 5600 | __slots__ = ('sign','int','exp') |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 5601 | # sign: 0 or 1 |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5602 | # int: int |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5603 | # exp: None, int, or string |
| 5604 | |
| 5605 | def __init__(self, value=None): |
| 5606 | if value is None: |
| 5607 | self.sign = None |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5608 | self.int = 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5609 | self.exp = None |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 5610 | elif isinstance(value, Decimal): |
| 5611 | self.sign = value._sign |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 5612 | self.int = int(value._int) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5613 | self.exp = value._exp |
Raymond Hettinger | 17931de | 2004-10-27 06:21:46 +0000 | [diff] [blame] | 5614 | else: |
| 5615 | # assert isinstance(value, tuple) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5616 | self.sign = value[0] |
| 5617 | self.int = value[1] |
| 5618 | self.exp = value[2] |
| 5619 | |
| 5620 | def __repr__(self): |
| 5621 | return "(%r, %r, %r)" % (self.sign, self.int, self.exp) |
| 5622 | |
| 5623 | __str__ = __repr__ |
| 5624 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5625 | |
| 5626 | |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 5627 | def _normalize(op1, op2, prec = 0): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5628 | """Normalizes op1, op2 to have the same exp and length of coefficient. |
| 5629 | |
| 5630 | Done during addition. |
| 5631 | """ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5632 | if op1.exp < op2.exp: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5633 | tmp = op2 |
| 5634 | other = op1 |
| 5635 | else: |
| 5636 | tmp = op1 |
| 5637 | other = op2 |
| 5638 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5639 | # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1). |
| 5640 | # Then adding 10**exp to tmp has the same effect (after rounding) |
| 5641 | # as adding any positive quantity smaller than 10**exp; similarly |
| 5642 | # for subtraction. So if other is smaller than 10**exp we replace |
| 5643 | # 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] | 5644 | tmp_len = len(str(tmp.int)) |
| 5645 | other_len = len(str(other.int)) |
| 5646 | exp = tmp.exp + min(-1, tmp_len - prec - 2) |
| 5647 | if other_len + other.exp - 1 < exp: |
| 5648 | other.int = 1 |
| 5649 | other.exp = exp |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5650 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5651 | tmp.int *= 10 ** (tmp.exp - other.exp) |
| 5652 | tmp.exp = other.exp |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5653 | return op1, op2 |
| 5654 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5655 | ##### Integer arithmetic functions used by ln, log10, exp and __pow__ ##### |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5656 | |
Raymond Hettinger | db213a2 | 2010-11-27 08:09:40 +0000 | [diff] [blame] | 5657 | _nbits = int.bit_length |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5658 | |
Mark Dickinson | 7ce0fa8 | 2011-06-04 18:14:23 +0100 | [diff] [blame] | 5659 | def _decimal_lshift_exact(n, e): |
| 5660 | """ Given integers n and e, return n * 10**e if it's an integer, else None. |
| 5661 | |
| 5662 | The computation is designed to avoid computing large powers of 10 |
| 5663 | unnecessarily. |
| 5664 | |
| 5665 | >>> _decimal_lshift_exact(3, 4) |
| 5666 | 30000 |
| 5667 | >>> _decimal_lshift_exact(300, -999999999) # returns None |
| 5668 | |
| 5669 | """ |
| 5670 | if n == 0: |
| 5671 | return 0 |
| 5672 | elif e >= 0: |
| 5673 | return n * 10**e |
| 5674 | else: |
| 5675 | # val_n = largest power of 10 dividing n. |
| 5676 | str_n = str(abs(n)) |
| 5677 | val_n = len(str_n) - len(str_n.rstrip('0')) |
| 5678 | return None if val_n < -e else n // 10**-e |
| 5679 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5680 | def _sqrt_nearest(n, a): |
| 5681 | """Closest integer to the square root of the positive integer n. a is |
| 5682 | an initial approximation to the square root. Any positive integer |
| 5683 | will do for a, but the closer a is to the square root of n the |
| 5684 | faster convergence will be. |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 5685 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5686 | """ |
| 5687 | if n <= 0 or a <= 0: |
| 5688 | raise ValueError("Both arguments to _sqrt_nearest should be positive.") |
| 5689 | |
| 5690 | b=0 |
| 5691 | while a != b: |
| 5692 | b, a = a, a--n//a>>1 |
| 5693 | return a |
| 5694 | |
| 5695 | def _rshift_nearest(x, shift): |
| 5696 | """Given an integer x and a nonnegative integer shift, return closest |
| 5697 | integer to x / 2**shift; use round-to-even in case of a tie. |
| 5698 | |
| 5699 | """ |
| 5700 | b, q = 1 << shift, x >> shift |
| 5701 | return q + (2*(x & (b-1)) + (q&1) > b) |
| 5702 | |
| 5703 | def _div_nearest(a, b): |
| 5704 | """Closest integer to a/b, a and b positive integers; rounds to even |
| 5705 | in the case of a tie. |
| 5706 | |
| 5707 | """ |
| 5708 | q, r = divmod(a, b) |
| 5709 | return q + (2*r + (q&1) > b) |
| 5710 | |
| 5711 | def _ilog(x, M, L = 8): |
| 5712 | """Integer approximation to M*log(x/M), with absolute error boundable |
| 5713 | in terms only of x/M. |
| 5714 | |
| 5715 | Given positive integers x and M, return an integer approximation to |
| 5716 | M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference |
| 5717 | between the approximation and the exact result is at most 22. For |
| 5718 | L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In |
| 5719 | both cases these are upper bounds on the error; it will usually be |
| 5720 | much smaller.""" |
| 5721 | |
| 5722 | # The basic algorithm is the following: let log1p be the function |
| 5723 | # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use |
| 5724 | # the reduction |
| 5725 | # |
| 5726 | # log1p(y) = 2*log1p(y/(1+sqrt(1+y))) |
| 5727 | # |
| 5728 | # repeatedly until the argument to log1p is small (< 2**-L in |
| 5729 | # absolute value). For small y we can use the Taylor series |
| 5730 | # expansion |
| 5731 | # |
| 5732 | # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T |
| 5733 | # |
| 5734 | # truncating at T such that y**T is small enough. The whole |
| 5735 | # computation is carried out in a form of fixed-point arithmetic, |
| 5736 | # with a real number z being represented by an integer |
| 5737 | # approximation to z*M. To avoid loss of precision, the y below |
| 5738 | # is actually an integer approximation to 2**R*y*M, where R is the |
| 5739 | # number of reductions performed so far. |
| 5740 | |
| 5741 | y = x-M |
| 5742 | # argument reduction; R = number of reductions performed |
| 5743 | R = 0 |
| 5744 | while (R <= L and abs(y) << L-R >= M or |
| 5745 | R > L and abs(y) >> R-L >= M): |
| 5746 | y = _div_nearest((M*y) << 1, |
| 5747 | M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M)) |
| 5748 | R += 1 |
| 5749 | |
| 5750 | # Taylor series with T terms |
| 5751 | T = -int(-10*len(str(M))//(3*L)) |
| 5752 | yshift = _rshift_nearest(y, R) |
| 5753 | w = _div_nearest(M, T) |
| 5754 | for k in range(T-1, 0, -1): |
| 5755 | w = _div_nearest(M, k) - _div_nearest(yshift*w, M) |
| 5756 | |
| 5757 | return _div_nearest(w*y, M) |
| 5758 | |
| 5759 | def _dlog10(c, e, p): |
| 5760 | """Given integers c, e and p with c > 0, p >= 0, compute an integer |
| 5761 | approximation to 10**p * log10(c*10**e), with an absolute error of |
| 5762 | at most 1. Assumes that c*10**e is not exactly 1.""" |
| 5763 | |
| 5764 | # increase precision by 2; compensate for this by dividing |
| 5765 | # final result by 100 |
| 5766 | p += 2 |
| 5767 | |
| 5768 | # write c*10**e as d*10**f with either: |
| 5769 | # f >= 0 and 1 <= d <= 10, or |
| 5770 | # f <= 0 and 0.1 <= d <= 1. |
| 5771 | # Thus for c*10**e close to 1, f = 0 |
| 5772 | l = len(str(c)) |
| 5773 | f = e+l - (e+l >= 1) |
| 5774 | |
| 5775 | if p > 0: |
| 5776 | M = 10**p |
| 5777 | k = e+p-f |
| 5778 | if k >= 0: |
| 5779 | c *= 10**k |
| 5780 | else: |
| 5781 | c = _div_nearest(c, 10**-k) |
| 5782 | |
| 5783 | log_d = _ilog(c, M) # error < 5 + 22 = 27 |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5784 | log_10 = _log10_digits(p) # error < 1 |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5785 | log_d = _div_nearest(log_d*M, log_10) |
| 5786 | log_tenpower = f*M # exact |
| 5787 | else: |
| 5788 | log_d = 0 # error < 2.31 |
Neal Norwitz | 2f99b24 | 2008-08-24 05:48:10 +0000 | [diff] [blame] | 5789 | log_tenpower = _div_nearest(f, 10**-p) # error < 0.5 |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5790 | |
| 5791 | return _div_nearest(log_tenpower+log_d, 100) |
| 5792 | |
| 5793 | def _dlog(c, e, p): |
| 5794 | """Given integers c, e and p with c > 0, compute an integer |
| 5795 | approximation to 10**p * log(c*10**e), with an absolute error of |
| 5796 | at most 1. Assumes that c*10**e is not exactly 1.""" |
| 5797 | |
| 5798 | # Increase precision by 2. The precision increase is compensated |
| 5799 | # for at the end with a division by 100. |
| 5800 | p += 2 |
| 5801 | |
| 5802 | # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10, |
| 5803 | # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e) |
| 5804 | # as 10**p * log(d) + 10**p*f * log(10). |
| 5805 | l = len(str(c)) |
| 5806 | f = e+l - (e+l >= 1) |
| 5807 | |
| 5808 | # compute approximation to 10**p*log(d), with error < 27 |
| 5809 | if p > 0: |
| 5810 | k = e+p-f |
| 5811 | if k >= 0: |
| 5812 | c *= 10**k |
| 5813 | else: |
| 5814 | c = _div_nearest(c, 10**-k) # error of <= 0.5 in c |
| 5815 | |
| 5816 | # _ilog magnifies existing error in c by a factor of at most 10 |
| 5817 | log_d = _ilog(c, 10**p) # error < 5 + 22 = 27 |
| 5818 | else: |
| 5819 | # p <= 0: just approximate the whole thing by 0; error < 2.31 |
| 5820 | log_d = 0 |
| 5821 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5822 | # compute approximation to f*10**p*log(10), with error < 11. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5823 | if f: |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5824 | extra = len(str(abs(f)))-1 |
| 5825 | if p + extra >= 0: |
| 5826 | # error in f * _log10_digits(p+extra) < |f| * 1 = |f| |
| 5827 | # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11 |
| 5828 | f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5829 | else: |
| 5830 | f_log_ten = 0 |
| 5831 | else: |
| 5832 | f_log_ten = 0 |
| 5833 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5834 | # 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] | 5835 | return _div_nearest(f_log_ten + log_d, 100) |
| 5836 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5837 | class _Log10Memoize(object): |
| 5838 | """Class to compute, store, and allow retrieval of, digits of the |
| 5839 | constant log(10) = 2.302585.... This constant is needed by |
| 5840 | Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__.""" |
| 5841 | def __init__(self): |
| 5842 | self.digits = "23025850929940456840179914546843642076011014886" |
| 5843 | |
| 5844 | def getdigits(self, p): |
| 5845 | """Given an integer p >= 0, return floor(10**p)*log(10). |
| 5846 | |
| 5847 | For example, self.getdigits(3) returns 2302. |
| 5848 | """ |
| 5849 | # digits are stored as a string, for quick conversion to |
| 5850 | # integer in the case that we've already computed enough |
| 5851 | # digits; the stored digits should always be correct |
| 5852 | # (truncated, not rounded to nearest). |
| 5853 | if p < 0: |
| 5854 | raise ValueError("p should be nonnegative") |
| 5855 | |
| 5856 | if p >= len(self.digits): |
| 5857 | # compute p+3, p+6, p+9, ... digits; continue until at |
| 5858 | # least one of the extra digits is nonzero |
| 5859 | extra = 3 |
| 5860 | while True: |
| 5861 | # compute p+extra digits, correct to within 1ulp |
| 5862 | M = 10**(p+extra+2) |
| 5863 | digits = str(_div_nearest(_ilog(10*M, M), 100)) |
| 5864 | if digits[-extra:] != '0'*extra: |
| 5865 | break |
| 5866 | extra += 3 |
| 5867 | # keep all reliable digits so far; remove trailing zeros |
| 5868 | # and next nonzero digit |
| 5869 | self.digits = digits.rstrip('0')[:-1] |
| 5870 | return int(self.digits[:p+1]) |
| 5871 | |
| 5872 | _log10_digits = _Log10Memoize().getdigits |
| 5873 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5874 | def _iexp(x, M, L=8): |
| 5875 | """Given integers x and M, M > 0, such that x/M is small in absolute |
| 5876 | value, compute an integer approximation to M*exp(x/M). For 0 <= |
| 5877 | x/M <= 2.4, the absolute error in the result is bounded by 60 (and |
| 5878 | is usually much smaller).""" |
| 5879 | |
| 5880 | # Algorithm: to compute exp(z) for a real number z, first divide z |
| 5881 | # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then |
| 5882 | # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor |
| 5883 | # series |
| 5884 | # |
| 5885 | # expm1(x) = x + x**2/2! + x**3/3! + ... |
| 5886 | # |
| 5887 | # Now use the identity |
| 5888 | # |
| 5889 | # expm1(2x) = expm1(x)*(expm1(x)+2) |
| 5890 | # |
| 5891 | # R times to compute the sequence expm1(z/2**R), |
| 5892 | # expm1(z/2**(R-1)), ... , exp(z/2), exp(z). |
| 5893 | |
| 5894 | # Find R such that x/2**R/M <= 2**-L |
| 5895 | R = _nbits((x<<L)//M) |
| 5896 | |
| 5897 | # Taylor series. (2**L)**T > M |
| 5898 | T = -int(-10*len(str(M))//(3*L)) |
| 5899 | y = _div_nearest(x, T) |
| 5900 | Mshift = M<<R |
| 5901 | for i in range(T-1, 0, -1): |
| 5902 | y = _div_nearest(x*(Mshift + y), Mshift * i) |
| 5903 | |
| 5904 | # Expansion |
| 5905 | for k in range(R-1, -1, -1): |
| 5906 | Mshift = M<<(k+2) |
| 5907 | y = _div_nearest(y*(y+Mshift), Mshift) |
| 5908 | |
| 5909 | return M+y |
| 5910 | |
| 5911 | def _dexp(c, e, p): |
| 5912 | """Compute an approximation to exp(c*10**e), with p decimal places of |
| 5913 | precision. |
| 5914 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5915 | Returns integers d, f such that: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5916 | |
| 5917 | 10**(p-1) <= d <= 10**p, and |
| 5918 | (d-1)*10**f < exp(c*10**e) < (d+1)*10**f |
| 5919 | |
| 5920 | In other words, d*10**f is an approximation to exp(c*10**e) with p |
| 5921 | digits of precision, and with an error in d of at most 1. This is |
| 5922 | almost, but not quite, the same as the error being < 1ulp: when d |
| 5923 | = 10**(p-1) the error could be up to 10 ulp.""" |
| 5924 | |
| 5925 | # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision |
| 5926 | p += 2 |
| 5927 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5928 | # compute log(10) with extra precision = adjusted exponent of c*10**e |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5929 | extra = max(0, e + len(str(c)) - 1) |
| 5930 | q = p + extra |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5931 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5932 | # 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] | 5933 | # rounding down |
| 5934 | shift = e+q |
| 5935 | if shift >= 0: |
| 5936 | cshift = c*10**shift |
| 5937 | else: |
| 5938 | cshift = c//10**-shift |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 5939 | quot, rem = divmod(cshift, _log10_digits(q)) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 5940 | |
| 5941 | # reduce remainder back to original precision |
| 5942 | rem = _div_nearest(rem, 10**extra) |
| 5943 | |
| 5944 | # error in result of _iexp < 120; error after division < 0.62 |
| 5945 | return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3 |
| 5946 | |
| 5947 | def _dpower(xc, xe, yc, ye, p): |
| 5948 | """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and |
| 5949 | y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that: |
| 5950 | |
| 5951 | 10**(p-1) <= c <= 10**p, and |
| 5952 | (c-1)*10**e < x**y < (c+1)*10**e |
| 5953 | |
| 5954 | in other words, c*10**e is an approximation to x**y with p digits |
| 5955 | of precision, and with an error in c of at most 1. (This is |
| 5956 | almost, but not quite, the same as the error being < 1ulp: when c |
| 5957 | == 10**(p-1) we can only guarantee error < 10ulp.) |
| 5958 | |
| 5959 | We assume that: x is positive and not equal to 1, and y is nonzero. |
| 5960 | """ |
| 5961 | |
| 5962 | # Find b such that 10**(b-1) <= |y| <= 10**b |
| 5963 | b = len(str(abs(yc))) + ye |
| 5964 | |
| 5965 | # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point |
| 5966 | lxc = _dlog(xc, xe, p+b+1) |
| 5967 | |
| 5968 | # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1) |
| 5969 | shift = ye-b |
| 5970 | if shift >= 0: |
| 5971 | pc = lxc*yc*10**shift |
| 5972 | else: |
| 5973 | pc = _div_nearest(lxc*yc, 10**-shift) |
| 5974 | |
| 5975 | if pc == 0: |
| 5976 | # we prefer a result that isn't exactly 1; this makes it |
| 5977 | # easier to compute a correctly rounded result in __pow__ |
| 5978 | if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1: |
| 5979 | coeff, exp = 10**(p-1)+1, 1-p |
| 5980 | else: |
| 5981 | coeff, exp = 10**p-1, -p |
| 5982 | else: |
| 5983 | coeff, exp = _dexp(pc, -(p+1), p+1) |
| 5984 | coeff = _div_nearest(coeff, 10) |
| 5985 | exp += 1 |
| 5986 | |
| 5987 | return coeff, exp |
| 5988 | |
| 5989 | def _log10_lb(c, correction = { |
| 5990 | '1': 100, '2': 70, '3': 53, '4': 40, '5': 31, |
| 5991 | '6': 23, '7': 16, '8': 10, '9': 5}): |
| 5992 | """Compute a lower bound for 100*log10(c) for a positive integer c.""" |
| 5993 | if c <= 0: |
| 5994 | raise ValueError("The argument to _log10_lb should be nonnegative.") |
| 5995 | str_c = str(c) |
| 5996 | return 100*len(str_c) - correction[str_c[0]] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5997 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 5998 | ##### Helper Functions #################################################### |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 5999 | |
Mark Dickinson | ac256ab | 2010-04-03 11:08:14 +0000 | [diff] [blame] | 6000 | def _convert_other(other, raiseit=False, allow_float=False): |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 6001 | """Convert other to Decimal. |
| 6002 | |
| 6003 | Verifies that it's ok to use in an implicit construction. |
Mark Dickinson | ac256ab | 2010-04-03 11:08:14 +0000 | [diff] [blame] | 6004 | If allow_float is true, allow conversion from float; this |
| 6005 | is used in the comparison methods (__eq__ and friends). |
| 6006 | |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 6007 | """ |
| 6008 | if isinstance(other, Decimal): |
| 6009 | return other |
Walter Dörwald | aa97f04 | 2007-05-03 21:05:51 +0000 | [diff] [blame] | 6010 | if isinstance(other, int): |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 6011 | return Decimal(other) |
Mark Dickinson | ac256ab | 2010-04-03 11:08:14 +0000 | [diff] [blame] | 6012 | if allow_float and isinstance(other, float): |
| 6013 | return Decimal.from_float(other) |
| 6014 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 6015 | if raiseit: |
| 6016 | raise TypeError("Unable to convert %s to Decimal" % other) |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 6017 | return NotImplemented |
Raymond Hettinger | 636a6b1 | 2004-09-19 01:54:09 +0000 | [diff] [blame] | 6018 | |
Mark Dickinson | 08ade6f | 2010-06-11 10:44:52 +0000 | [diff] [blame] | 6019 | def _convert_for_comparison(self, other, equality_op=False): |
| 6020 | """Given a Decimal instance self and a Python object other, return |
Mark Dickinson | 1c164a6 | 2010-06-11 16:49:20 +0000 | [diff] [blame] | 6021 | a pair (s, o) of Decimal instances such that "s op o" is |
Mark Dickinson | 08ade6f | 2010-06-11 10:44:52 +0000 | [diff] [blame] | 6022 | equivalent to "self op other" for any of the 6 comparison |
| 6023 | operators "op". |
| 6024 | |
| 6025 | """ |
| 6026 | if isinstance(other, Decimal): |
| 6027 | return self, other |
| 6028 | |
| 6029 | # Comparison with a Rational instance (also includes integers): |
| 6030 | # self op n/d <=> self*d op n (for n and d integers, d positive). |
| 6031 | # A NaN or infinity can be left unchanged without affecting the |
| 6032 | # comparison result. |
| 6033 | if isinstance(other, _numbers.Rational): |
| 6034 | if not self._is_special: |
| 6035 | self = _dec_from_triple(self._sign, |
| 6036 | str(int(self._int) * other.denominator), |
| 6037 | self._exp) |
| 6038 | return self, Decimal(other.numerator) |
| 6039 | |
| 6040 | # Comparisons with float and complex types. == and != comparisons |
| 6041 | # with complex numbers should succeed, returning either True or False |
| 6042 | # as appropriate. Other comparisons return NotImplemented. |
| 6043 | if equality_op and isinstance(other, _numbers.Complex) and other.imag == 0: |
| 6044 | other = other.real |
| 6045 | if isinstance(other, float): |
Stefan Krah | 1919b7e | 2012-03-21 18:25:23 +0100 | [diff] [blame] | 6046 | context = getcontext() |
| 6047 | if equality_op: |
| 6048 | context.flags[FloatOperation] = 1 |
| 6049 | else: |
| 6050 | context._raise_error(FloatOperation, |
| 6051 | "strict semantics for mixing floats and Decimals are enabled") |
Mark Dickinson | 08ade6f | 2010-06-11 10:44:52 +0000 | [diff] [blame] | 6052 | return self, Decimal.from_float(other) |
| 6053 | return NotImplemented, NotImplemented |
| 6054 | |
| 6055 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 6056 | ##### Setup Specific Contexts ############################################ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 6057 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 6058 | # The default context prototype used by Context() |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 6059 | # Is mutable, so that new contexts can have different default values |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 6060 | |
| 6061 | DefaultContext = Context( |
Raymond Hettinger | 6ea4845 | 2004-07-03 12:26:21 +0000 | [diff] [blame] | 6062 | prec=28, rounding=ROUND_HALF_EVEN, |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 6063 | traps=[DivisionByZero, Overflow, InvalidOperation], |
| 6064 | flags=[], |
Stefan Krah | 1919b7e | 2012-03-21 18:25:23 +0100 | [diff] [blame] | 6065 | Emax=999999, |
| 6066 | Emin=-999999, |
Mark Dickinson | b1d8e32 | 2010-05-22 18:35:36 +0000 | [diff] [blame] | 6067 | capitals=1, |
| 6068 | clamp=0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 6069 | ) |
| 6070 | |
| 6071 | # Pre-made alternate contexts offered by the specification |
| 6072 | # Don't change these; the user should be able to select these |
| 6073 | # contexts and be able to reproduce results from other implementations |
| 6074 | # of the spec. |
| 6075 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 6076 | BasicContext = Context( |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 6077 | prec=9, rounding=ROUND_HALF_UP, |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 6078 | traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow], |
| 6079 | flags=[], |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 6080 | ) |
| 6081 | |
Raymond Hettinger | 9ec3e3b | 2004-07-03 13:48:56 +0000 | [diff] [blame] | 6082 | ExtendedContext = Context( |
Raymond Hettinger | 6ea4845 | 2004-07-03 12:26:21 +0000 | [diff] [blame] | 6083 | prec=9, rounding=ROUND_HALF_EVEN, |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 6084 | traps=[], |
| 6085 | flags=[], |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 6086 | ) |
| 6087 | |
| 6088 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 6089 | ##### crud for parsing strings ############################################# |
Christian Heimes | 23daade0 | 2008-02-25 12:39:23 +0000 | [diff] [blame] | 6090 | # |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 6091 | # Regular expression used for parsing numeric strings. Additional |
| 6092 | # comments: |
| 6093 | # |
| 6094 | # 1. Uncomment the two '\s*' lines to allow leading and/or trailing |
| 6095 | # whitespace. But note that the specification disallows whitespace in |
| 6096 | # a numeric string. |
| 6097 | # |
| 6098 | # 2. For finite numbers (not infinities and NaNs) the body of the |
| 6099 | # number between the optional sign and the optional exponent must have |
| 6100 | # at least one decimal digit, possibly after the decimal point. The |
Mark Dickinson | 345adc4 | 2009-08-02 10:14:23 +0000 | [diff] [blame] | 6101 | # lookahead expression '(?=\d|\.\d)' checks this. |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 6102 | |
| 6103 | import re |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 6104 | _parser = re.compile(r""" # A numeric string consists of: |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 6105 | # \s* |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 6106 | (?P<sign>[-+])? # an optional sign, followed by either... |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 6107 | ( |
Mark Dickinson | 345adc4 | 2009-08-02 10:14:23 +0000 | [diff] [blame] | 6108 | (?=\d|\.\d) # ...a number (with at least one digit) |
| 6109 | (?P<int>\d*) # having a (possibly empty) integer part |
| 6110 | (\.(?P<frac>\d*))? # followed by an optional fractional part |
| 6111 | (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or... |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 6112 | | |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 6113 | Inf(inity)? # ...an infinity, or... |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 6114 | | |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 6115 | (?P<signal>s)? # ...an (optionally signaling) |
| 6116 | NaN # NaN |
Mark Dickinson | 345adc4 | 2009-08-02 10:14:23 +0000 | [diff] [blame] | 6117 | (?P<diag>\d*) # with (possibly empty) diagnostic info. |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 6118 | ) |
| 6119 | # \s* |
Christian Heimes | a62da1d | 2008-01-12 19:39:10 +0000 | [diff] [blame] | 6120 | \Z |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 6121 | """, re.VERBOSE | re.IGNORECASE).match |
| 6122 | |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 6123 | _all_zeros = re.compile('0*$').match |
| 6124 | _exact_half = re.compile('50*$').match |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6125 | |
| 6126 | ##### PEP3101 support functions ############################################## |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 6127 | # The functions in this section have little to do with the Decimal |
| 6128 | # class, and could potentially be reused or adapted for other pure |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6129 | # Python numeric classes that want to implement __format__ |
| 6130 | # |
| 6131 | # A format specifier for Decimal looks like: |
| 6132 | # |
Eric Smith | 984bb58 | 2010-11-25 16:08:06 +0000 | [diff] [blame] | 6133 | # [[fill]align][sign][#][0][minimumwidth][,][.precision][type] |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6134 | |
| 6135 | _parse_format_specifier_regex = re.compile(r"""\A |
| 6136 | (?: |
| 6137 | (?P<fill>.)? |
| 6138 | (?P<align>[<>=^]) |
| 6139 | )? |
| 6140 | (?P<sign>[-+ ])? |
Eric Smith | 984bb58 | 2010-11-25 16:08:06 +0000 | [diff] [blame] | 6141 | (?P<alt>\#)? |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6142 | (?P<zeropad>0)? |
| 6143 | (?P<minimumwidth>(?!0)\d+)? |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 6144 | (?P<thousands_sep>,)? |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6145 | (?:\.(?P<precision>0|(?!0)\d+))? |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 6146 | (?P<type>[eEfFgGn%])? |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6147 | \Z |
Stefan Krah | 6edda14 | 2013-05-29 15:45:38 +0200 | [diff] [blame] | 6148 | """, re.VERBOSE|re.DOTALL) |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6149 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 6150 | del re |
| 6151 | |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 6152 | # The locale module is only needed for the 'n' format specifier. The |
| 6153 | # rest of the PEP 3101 code functions quite happily without it, so we |
| 6154 | # don't care too much if locale isn't present. |
| 6155 | try: |
| 6156 | import locale as _locale |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 6157 | except ImportError: |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 6158 | pass |
| 6159 | |
| 6160 | def _parse_format_specifier(format_spec, _localeconv=None): |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6161 | """Parse and validate a format specifier. |
| 6162 | |
| 6163 | Turns a standard numeric format specifier into a dict, with the |
| 6164 | following entries: |
| 6165 | |
| 6166 | fill: fill character to pad field to minimum width |
| 6167 | align: alignment type, either '<', '>', '=' or '^' |
| 6168 | sign: either '+', '-' or ' ' |
| 6169 | minimumwidth: nonnegative integer giving minimum width |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 6170 | zeropad: boolean, indicating whether to pad with zeros |
| 6171 | thousands_sep: string to use as thousands separator, or '' |
| 6172 | grouping: grouping for thousands separators, in format |
| 6173 | used by localeconv |
| 6174 | decimal_point: string to use for decimal point |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6175 | precision: nonnegative integer giving precision, or None |
| 6176 | type: one of the characters 'eEfFgG%', or None |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6177 | |
| 6178 | """ |
| 6179 | m = _parse_format_specifier_regex.match(format_spec) |
| 6180 | if m is None: |
| 6181 | raise ValueError("Invalid format specifier: " + format_spec) |
| 6182 | |
| 6183 | # get the dictionary |
| 6184 | format_dict = m.groupdict() |
| 6185 | |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 6186 | # zeropad; defaults for fill and alignment. If zero padding |
| 6187 | # is requested, the fill and align fields should be absent. |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6188 | fill = format_dict['fill'] |
| 6189 | align = format_dict['align'] |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 6190 | format_dict['zeropad'] = (format_dict['zeropad'] is not None) |
| 6191 | if format_dict['zeropad']: |
| 6192 | if fill is not None: |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6193 | raise ValueError("Fill character conflicts with '0'" |
| 6194 | " in format specifier: " + format_spec) |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 6195 | if align is not None: |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6196 | raise ValueError("Alignment conflicts with '0' in " |
| 6197 | "format specifier: " + format_spec) |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6198 | format_dict['fill'] = fill or ' ' |
Mark Dickinson | 46ab5d0 | 2009-09-08 20:22:46 +0000 | [diff] [blame] | 6199 | # PEP 3101 originally specified that the default alignment should |
| 6200 | # be left; it was later agreed that right-aligned makes more sense |
| 6201 | # for numeric types. See http://bugs.python.org/issue6857. |
| 6202 | format_dict['align'] = align or '>' |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6203 | |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 6204 | # default sign handling: '-' for negative, '' for positive |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6205 | if format_dict['sign'] is None: |
| 6206 | format_dict['sign'] = '-' |
| 6207 | |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6208 | # minimumwidth defaults to 0; precision remains None if not given |
| 6209 | format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0') |
| 6210 | if format_dict['precision'] is not None: |
| 6211 | format_dict['precision'] = int(format_dict['precision']) |
| 6212 | |
| 6213 | # if format type is 'g' or 'G' then a precision of 0 makes little |
| 6214 | # sense; convert it to 1. Same if format type is unspecified. |
| 6215 | if format_dict['precision'] == 0: |
Stefan Krah | 1919b7e | 2012-03-21 18:25:23 +0100 | [diff] [blame] | 6216 | if format_dict['type'] is None or format_dict['type'] in 'gGn': |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6217 | format_dict['precision'] = 1 |
| 6218 | |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 6219 | # determine thousands separator, grouping, and decimal separator, and |
| 6220 | # add appropriate entries to format_dict |
| 6221 | if format_dict['type'] == 'n': |
| 6222 | # apart from separators, 'n' behaves just like 'g' |
| 6223 | format_dict['type'] = 'g' |
| 6224 | if _localeconv is None: |
| 6225 | _localeconv = _locale.localeconv() |
| 6226 | if format_dict['thousands_sep'] is not None: |
| 6227 | raise ValueError("Explicit thousands separator conflicts with " |
| 6228 | "'n' type in format specifier: " + format_spec) |
| 6229 | format_dict['thousands_sep'] = _localeconv['thousands_sep'] |
| 6230 | format_dict['grouping'] = _localeconv['grouping'] |
| 6231 | format_dict['decimal_point'] = _localeconv['decimal_point'] |
| 6232 | else: |
| 6233 | if format_dict['thousands_sep'] is None: |
| 6234 | format_dict['thousands_sep'] = '' |
| 6235 | format_dict['grouping'] = [3, 0] |
| 6236 | format_dict['decimal_point'] = '.' |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6237 | |
| 6238 | return format_dict |
| 6239 | |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 6240 | def _format_align(sign, body, spec): |
| 6241 | """Given an unpadded, non-aligned numeric string 'body' and sign |
Ezio Melotti | 42da663 | 2011-03-15 05:18:48 +0200 | [diff] [blame] | 6242 | string 'sign', add padding and alignment conforming to the given |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 6243 | format specifier dictionary 'spec' (as produced by |
| 6244 | parse_format_specifier). |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6245 | |
| 6246 | """ |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6247 | # how much extra space do we have to play with? |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 6248 | minimumwidth = spec['minimumwidth'] |
| 6249 | fill = spec['fill'] |
| 6250 | padding = fill*(minimumwidth - len(sign) - len(body)) |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6251 | |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 6252 | align = spec['align'] |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6253 | if align == '<': |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6254 | result = sign + body + padding |
Mark Dickinson | ad41634 | 2009-03-17 18:10:15 +0000 | [diff] [blame] | 6255 | elif align == '>': |
| 6256 | result = padding + sign + body |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6257 | elif align == '=': |
| 6258 | result = sign + padding + body |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 6259 | elif align == '^': |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6260 | half = len(padding)//2 |
| 6261 | result = padding[:half] + sign + body + padding[half:] |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 6262 | else: |
| 6263 | raise ValueError('Unrecognised alignment field') |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6264 | |
Christian Heimes | f16baeb | 2008-02-29 14:57:44 +0000 | [diff] [blame] | 6265 | return result |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 6266 | |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 6267 | def _group_lengths(grouping): |
| 6268 | """Convert a localeconv-style grouping into a (possibly infinite) |
| 6269 | iterable of integers representing group lengths. |
| 6270 | |
| 6271 | """ |
| 6272 | # The result from localeconv()['grouping'], and the input to this |
| 6273 | # function, should be a list of integers in one of the |
| 6274 | # following three forms: |
| 6275 | # |
| 6276 | # (1) an empty list, or |
| 6277 | # (2) nonempty list of positive integers + [0] |
| 6278 | # (3) list of positive integers + [locale.CHAR_MAX], or |
| 6279 | |
| 6280 | from itertools import chain, repeat |
| 6281 | if not grouping: |
| 6282 | return [] |
| 6283 | elif grouping[-1] == 0 and len(grouping) >= 2: |
| 6284 | return chain(grouping[:-1], repeat(grouping[-2])) |
| 6285 | elif grouping[-1] == _locale.CHAR_MAX: |
| 6286 | return grouping[:-1] |
| 6287 | else: |
| 6288 | raise ValueError('unrecognised format for grouping') |
| 6289 | |
| 6290 | def _insert_thousands_sep(digits, spec, min_width=1): |
| 6291 | """Insert thousands separators into a digit string. |
| 6292 | |
| 6293 | spec is a dictionary whose keys should include 'thousands_sep' and |
| 6294 | 'grouping'; typically it's the result of parsing the format |
| 6295 | specifier using _parse_format_specifier. |
| 6296 | |
| 6297 | The min_width keyword argument gives the minimum length of the |
| 6298 | result, which will be padded on the left with zeros if necessary. |
| 6299 | |
| 6300 | If necessary, the zero padding adds an extra '0' on the left to |
| 6301 | avoid a leading thousands separator. For example, inserting |
| 6302 | commas every three digits in '123456', with min_width=8, gives |
| 6303 | '0,123,456', even though that has length 9. |
| 6304 | |
| 6305 | """ |
| 6306 | |
| 6307 | sep = spec['thousands_sep'] |
| 6308 | grouping = spec['grouping'] |
| 6309 | |
| 6310 | groups = [] |
| 6311 | for l in _group_lengths(grouping): |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 6312 | if l <= 0: |
| 6313 | raise ValueError("group length should be positive") |
| 6314 | # max(..., 1) forces at least 1 digit to the left of a separator |
| 6315 | l = min(max(len(digits), min_width, 1), l) |
| 6316 | groups.append('0'*(l - len(digits)) + digits[-l:]) |
| 6317 | digits = digits[:-l] |
| 6318 | min_width -= l |
| 6319 | if not digits and min_width <= 0: |
| 6320 | break |
Mark Dickinson | 7303b59 | 2009-03-18 08:25:36 +0000 | [diff] [blame] | 6321 | min_width -= len(sep) |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 6322 | else: |
| 6323 | l = max(len(digits), min_width, 1) |
| 6324 | groups.append('0'*(l - len(digits)) + digits[-l:]) |
| 6325 | return sep.join(reversed(groups)) |
| 6326 | |
| 6327 | def _format_sign(is_negative, spec): |
| 6328 | """Determine sign character.""" |
| 6329 | |
| 6330 | if is_negative: |
| 6331 | return '-' |
| 6332 | elif spec['sign'] in ' +': |
| 6333 | return spec['sign'] |
| 6334 | else: |
| 6335 | return '' |
| 6336 | |
| 6337 | def _format_number(is_negative, intpart, fracpart, exp, spec): |
| 6338 | """Format a number, given the following data: |
| 6339 | |
| 6340 | is_negative: true if the number is negative, else false |
| 6341 | intpart: string of digits that must appear before the decimal point |
| 6342 | fracpart: string of digits that must come after the point |
| 6343 | exp: exponent, as an integer |
| 6344 | spec: dictionary resulting from parsing the format specifier |
| 6345 | |
| 6346 | This function uses the information in spec to: |
| 6347 | insert separators (decimal separator and thousands separators) |
| 6348 | format the sign |
| 6349 | format the exponent |
| 6350 | add trailing '%' for the '%' type |
| 6351 | zero-pad if necessary |
| 6352 | fill and align if necessary |
| 6353 | """ |
| 6354 | |
| 6355 | sign = _format_sign(is_negative, spec) |
| 6356 | |
Eric Smith | 984bb58 | 2010-11-25 16:08:06 +0000 | [diff] [blame] | 6357 | if fracpart or spec['alt']: |
Mark Dickinson | 79f5203 | 2009-03-17 23:12:51 +0000 | [diff] [blame] | 6358 | fracpart = spec['decimal_point'] + fracpart |
| 6359 | |
| 6360 | if exp != 0 or spec['type'] in 'eE': |
| 6361 | echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']] |
| 6362 | fracpart += "{0}{1:+}".format(echar, exp) |
| 6363 | if spec['type'] == '%': |
| 6364 | fracpart += '%' |
| 6365 | |
| 6366 | if spec['zeropad']: |
| 6367 | min_width = spec['minimumwidth'] - len(fracpart) - len(sign) |
| 6368 | else: |
| 6369 | min_width = 0 |
| 6370 | intpart = _insert_thousands_sep(intpart, spec, min_width) |
| 6371 | |
| 6372 | return _format_align(sign, intpart+fracpart, spec) |
| 6373 | |
| 6374 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 6375 | ##### Useful Constants (internal use only) ################################ |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 6376 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 6377 | # Reusable defaults |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 6378 | _Infinity = Decimal('Inf') |
| 6379 | _NegativeInfinity = Decimal('-Inf') |
Mark Dickinson | f923641 | 2009-01-02 23:23:21 +0000 | [diff] [blame] | 6380 | _NaN = Decimal('NaN') |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 6381 | _Zero = Decimal(0) |
| 6382 | _One = Decimal(1) |
| 6383 | _NegativeOne = Decimal(-1) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 6384 | |
Mark Dickinson | 627cf6a | 2009-01-03 12:11:47 +0000 | [diff] [blame] | 6385 | # _SignedInfinity[sign] is infinity w/ that sign |
| 6386 | _SignedInfinity = (_Infinity, _NegativeInfinity) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 6387 | |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 6388 | # Constants related to the hash implementation; hash(x) is based |
| 6389 | # on the reduction of x modulo _PyHASH_MODULUS |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 6390 | _PyHASH_MODULUS = sys.hash_info.modulus |
| 6391 | # hash values to use for positive and negative infinities, and nans |
| 6392 | _PyHASH_INF = sys.hash_info.inf |
| 6393 | _PyHASH_NAN = sys.hash_info.nan |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 6394 | |
| 6395 | # _PyHASH_10INV is the inverse of 10 modulo the prime _PyHASH_MODULUS |
| 6396 | _PyHASH_10INV = pow(10, _PyHASH_MODULUS - 2, _PyHASH_MODULUS) |
Stefan Krah | 1919b7e | 2012-03-21 18:25:23 +0100 | [diff] [blame] | 6397 | del sys |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 6398 | |
Stefan Krah | 1919b7e | 2012-03-21 18:25:23 +0100 | [diff] [blame] | 6399 | try: |
| 6400 | import _decimal |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 6401 | except ImportError: |
Stefan Krah | 1919b7e | 2012-03-21 18:25:23 +0100 | [diff] [blame] | 6402 | pass |
| 6403 | else: |
| 6404 | s1 = set(dir()) |
| 6405 | s2 = set(dir(_decimal)) |
| 6406 | for name in s1 - s2: |
| 6407 | del globals()[name] |
| 6408 | del s1, s2, name |
| 6409 | from _decimal import * |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 6410 | |
| 6411 | if __name__ == '__main__': |
Raymond Hettinger | 6d7e26e | 2011-02-01 23:54:43 +0000 | [diff] [blame] | 6412 | import doctest, decimal |
| 6413 | doctest.testmod(decimal) |