PageRenderTime 71ms CodeModel.GetById 1ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/decimal.py

https://bitbucket.org/evelyn559/pypy
Python | 6149 lines | 6117 code | 4 blank | 28 comment | 9 complexity | a9a71dfd7fcda25321ad62f70154f17a MD5 | raw file
  1. # Copyright (c) 2004 Python Software Foundation.
  2. # All rights reserved.
  3. # Written by Eric Price <eprice at tjhsst.edu>
  4. # and Facundo Batista <facundo at taniquetil.com.ar>
  5. # and Raymond Hettinger <python at rcn.com>
  6. # and Aahz <aahz at pobox.com>
  7. # and Tim Peters
  8. # This module is currently Py2.3 compatible and should be kept that way
  9. # unless a major compelling advantage arises. IOW, 2.3 compatibility is
  10. # strongly preferred, but not guaranteed.
  11. # Also, this module should be kept in sync with the latest updates of
  12. # the IBM specification as it evolves. Those updates will be treated
  13. # as bug fixes (deviation from the spec is a compatibility, usability
  14. # bug) and will be backported. At this point the spec is stabilizing
  15. # and the updates are becoming fewer, smaller, and less significant.
  16. """
  17. This is a Py2.3 implementation of decimal floating point arithmetic based on
  18. the General Decimal Arithmetic Specification:
  19. www2.hursley.ibm.com/decimal/decarith.html
  20. and IEEE standard 854-1987:
  21. www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
  22. Decimal floating point has finite precision with arbitrarily large bounds.
  23. The purpose of this module is to support arithmetic using familiar
  24. "schoolhouse" rules and to avoid some of the tricky representation
  25. issues associated with binary floating point. The package is especially
  26. useful for financial applications or for contexts where users have
  27. expectations that are at odds with binary floating point (for instance,
  28. in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
  29. of the expected Decimal('0.00') returned by decimal floating point).
  30. Here are some examples of using the decimal module:
  31. >>> from decimal import *
  32. >>> setcontext(ExtendedContext)
  33. >>> Decimal(0)
  34. Decimal('0')
  35. >>> Decimal('1')
  36. Decimal('1')
  37. >>> Decimal('-.0123')
  38. Decimal('-0.0123')
  39. >>> Decimal(123456)
  40. Decimal('123456')
  41. >>> Decimal('123.45e12345678901234567890')
  42. Decimal('1.2345E+12345678901234567892')
  43. >>> Decimal('1.33') + Decimal('1.27')
  44. Decimal('2.60')
  45. >>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41')
  46. Decimal('-2.20')
  47. >>> dig = Decimal(1)
  48. >>> print dig / Decimal(3)
  49. 0.333333333
  50. >>> getcontext().prec = 18
  51. >>> print dig / Decimal(3)
  52. 0.333333333333333333
  53. >>> print dig.sqrt()
  54. 1
  55. >>> print Decimal(3).sqrt()
  56. 1.73205080756887729
  57. >>> print Decimal(3) ** 123
  58. 4.85192780976896427E+58
  59. >>> inf = Decimal(1) / Decimal(0)
  60. >>> print inf
  61. Infinity
  62. >>> neginf = Decimal(-1) / Decimal(0)
  63. >>> print neginf
  64. -Infinity
  65. >>> print neginf + inf
  66. NaN
  67. >>> print neginf * inf
  68. -Infinity
  69. >>> print dig / 0
  70. Infinity
  71. >>> getcontext().traps[DivisionByZero] = 1
  72. >>> print dig / 0
  73. Traceback (most recent call last):
  74. ...
  75. ...
  76. ...
  77. DivisionByZero: x / 0
  78. >>> c = Context()
  79. >>> c.traps[InvalidOperation] = 0
  80. >>> print c.flags[InvalidOperation]
  81. 0
  82. >>> c.divide(Decimal(0), Decimal(0))
  83. Decimal('NaN')
  84. >>> c.traps[InvalidOperation] = 1
  85. >>> print c.flags[InvalidOperation]
  86. 1
  87. >>> c.flags[InvalidOperation] = 0
  88. >>> print c.flags[InvalidOperation]
  89. 0
  90. >>> print c.divide(Decimal(0), Decimal(0))
  91. Traceback (most recent call last):
  92. ...
  93. ...
  94. ...
  95. InvalidOperation: 0 / 0
  96. >>> print c.flags[InvalidOperation]
  97. 1
  98. >>> c.flags[InvalidOperation] = 0
  99. >>> c.traps[InvalidOperation] = 0
  100. >>> print c.divide(Decimal(0), Decimal(0))
  101. NaN
  102. >>> print c.flags[InvalidOperation]
  103. 1
  104. >>>
  105. """
  106. __all__ = [
  107. # Two major classes
  108. 'Decimal', 'Context',
  109. # Contexts
  110. 'DefaultContext', 'BasicContext', 'ExtendedContext',
  111. # Exceptions
  112. 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
  113. 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
  114. # Constants for use in setting up contexts
  115. 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
  116. 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
  117. # Functions for manipulating contexts
  118. 'setcontext', 'getcontext', 'localcontext'
  119. ]
  120. __version__ = '1.70' # Highest version of the spec this complies with
  121. import copy as _copy
  122. import math as _math
  123. import numbers as _numbers
  124. try:
  125. from collections import namedtuple as _namedtuple
  126. DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
  127. except ImportError:
  128. DecimalTuple = lambda *args: args
  129. # Rounding
  130. ROUND_DOWN = 'ROUND_DOWN'
  131. ROUND_HALF_UP = 'ROUND_HALF_UP'
  132. ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
  133. ROUND_CEILING = 'ROUND_CEILING'
  134. ROUND_FLOOR = 'ROUND_FLOOR'
  135. ROUND_UP = 'ROUND_UP'
  136. ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
  137. ROUND_05UP = 'ROUND_05UP'
  138. # Errors
  139. class DecimalException(ArithmeticError):
  140. """Base exception class.
  141. Used exceptions derive from this.
  142. If an exception derives from another exception besides this (such as
  143. Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
  144. called if the others are present. This isn't actually used for
  145. anything, though.
  146. handle -- Called when context._raise_error is called and the
  147. trap_enabler is not set. First argument is self, second is the
  148. context. More arguments can be given, those being after
  149. the explanation in _raise_error (For example,
  150. context._raise_error(NewError, '(-x)!', self._sign) would
  151. call NewError().handle(context, self._sign).)
  152. To define a new exception, it should be sufficient to have it derive
  153. from DecimalException.
  154. """
  155. def handle(self, context, *args):
  156. pass
  157. class Clamped(DecimalException):
  158. """Exponent of a 0 changed to fit bounds.
  159. This occurs and signals clamped if the exponent of a result has been
  160. altered in order to fit the constraints of a specific concrete
  161. representation. This may occur when the exponent of a zero result would
  162. be outside the bounds of a representation, or when a large normal
  163. number would have an encoded exponent that cannot be represented. In
  164. this latter case, the exponent is reduced to fit and the corresponding
  165. number of zero digits are appended to the coefficient ("fold-down").
  166. """
  167. class InvalidOperation(DecimalException):
  168. """An invalid operation was performed.
  169. Various bad things cause this:
  170. Something creates a signaling NaN
  171. -INF + INF
  172. 0 * (+-)INF
  173. (+-)INF / (+-)INF
  174. x % 0
  175. (+-)INF % x
  176. x._rescale( non-integer )
  177. sqrt(-x) , x > 0
  178. 0 ** 0
  179. x ** (non-integer)
  180. x ** (+-)INF
  181. An operand is invalid
  182. The result of the operation after these is a quiet positive NaN,
  183. except when the cause is a signaling NaN, in which case the result is
  184. also a quiet NaN, but with the original sign, and an optional
  185. diagnostic information.
  186. """
  187. def handle(self, context, *args):
  188. if args:
  189. ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
  190. return ans._fix_nan(context)
  191. return _NaN
  192. class ConversionSyntax(InvalidOperation):
  193. """Trying to convert badly formed string.
  194. This occurs and signals invalid-operation if an string is being
  195. converted to a number and it does not conform to the numeric string
  196. syntax. The result is [0,qNaN].
  197. """
  198. def handle(self, context, *args):
  199. return _NaN
  200. class DivisionByZero(DecimalException, ZeroDivisionError):
  201. """Division by 0.
  202. This occurs and signals division-by-zero if division of a finite number
  203. by zero was attempted (during a divide-integer or divide operation, or a
  204. power operation with negative right-hand operand), and the dividend was
  205. not zero.
  206. The result of the operation is [sign,inf], where sign is the exclusive
  207. or of the signs of the operands for divide, or is 1 for an odd power of
  208. -0, for power.
  209. """
  210. def handle(self, context, sign, *args):
  211. return _SignedInfinity[sign]
  212. class DivisionImpossible(InvalidOperation):
  213. """Cannot perform the division adequately.
  214. This occurs and signals invalid-operation if the integer result of a
  215. divide-integer or remainder operation had too many digits (would be
  216. longer than precision). The result is [0,qNaN].
  217. """
  218. def handle(self, context, *args):
  219. return _NaN
  220. class DivisionUndefined(InvalidOperation, ZeroDivisionError):
  221. """Undefined result of division.
  222. This occurs and signals invalid-operation if division by zero was
  223. attempted (during a divide-integer, divide, or remainder operation), and
  224. the dividend is also zero. The result is [0,qNaN].
  225. """
  226. def handle(self, context, *args):
  227. return _NaN
  228. class Inexact(DecimalException):
  229. """Had to round, losing information.
  230. This occurs and signals inexact whenever the result of an operation is
  231. not exact (that is, it needed to be rounded and any discarded digits
  232. were non-zero), or if an overflow or underflow condition occurs. The
  233. result in all cases is unchanged.
  234. The inexact signal may be tested (or trapped) to determine if a given
  235. operation (or sequence of operations) was inexact.
  236. """
  237. class InvalidContext(InvalidOperation):
  238. """Invalid context. Unknown rounding, for example.
  239. This occurs and signals invalid-operation if an invalid context was
  240. detected during an operation. This can occur if contexts are not checked
  241. on creation and either the precision exceeds the capability of the
  242. underlying concrete representation or an unknown or unsupported rounding
  243. was specified. These aspects of the context need only be checked when
  244. the values are required to be used. The result is [0,qNaN].
  245. """
  246. def handle(self, context, *args):
  247. return _NaN
  248. class Rounded(DecimalException):
  249. """Number got rounded (not necessarily changed during rounding).
  250. This occurs and signals rounded whenever the result of an operation is
  251. rounded (that is, some zero or non-zero digits were discarded from the
  252. coefficient), or if an overflow or underflow condition occurs. The
  253. result in all cases is unchanged.
  254. The rounded signal may be tested (or trapped) to determine if a given
  255. operation (or sequence of operations) caused a loss of precision.
  256. """
  257. class Subnormal(DecimalException):
  258. """Exponent < Emin before rounding.
  259. This occurs and signals subnormal whenever the result of a conversion or
  260. operation is subnormal (that is, its adjusted exponent is less than
  261. Emin, before any rounding). The result in all cases is unchanged.
  262. The subnormal signal may be tested (or trapped) to determine if a given
  263. or operation (or sequence of operations) yielded a subnormal result.
  264. """
  265. class Overflow(Inexact, Rounded):
  266. """Numerical overflow.
  267. This occurs and signals overflow if the adjusted exponent of a result
  268. (from a conversion or from an operation that is not an attempt to divide
  269. by zero), after rounding, would be greater than the largest value that
  270. can be handled by the implementation (the value Emax).
  271. The result depends on the rounding mode:
  272. For round-half-up and round-half-even (and for round-half-down and
  273. round-up, if implemented), the result of the operation is [sign,inf],
  274. where sign is the sign of the intermediate result. For round-down, the
  275. result is the largest finite number that can be represented in the
  276. current precision, with the sign of the intermediate result. For
  277. round-ceiling, the result is the same as for round-down if the sign of
  278. the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
  279. the result is the same as for round-down if the sign of the intermediate
  280. result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
  281. will also be raised.
  282. """
  283. def handle(self, context, sign, *args):
  284. if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
  285. ROUND_HALF_DOWN, ROUND_UP):
  286. return _SignedInfinity[sign]
  287. if sign == 0:
  288. if context.rounding == ROUND_CEILING:
  289. return _SignedInfinity[sign]
  290. return _dec_from_triple(sign, '9'*context.prec,
  291. context.Emax-context.prec+1)
  292. if sign == 1:
  293. if context.rounding == ROUND_FLOOR:
  294. return _SignedInfinity[sign]
  295. return _dec_from_triple(sign, '9'*context.prec,
  296. context.Emax-context.prec+1)
  297. class Underflow(Inexact, Rounded, Subnormal):
  298. """Numerical underflow with result rounded to 0.
  299. This occurs and signals underflow if a result is inexact and the
  300. adjusted exponent of the result would be smaller (more negative) than
  301. the smallest value that can be handled by the implementation (the value
  302. Emin). That is, the result is both inexact and subnormal.
  303. The result after an underflow will be a subnormal number rounded, if
  304. necessary, so that its exponent is not less than Etiny. This may result
  305. in 0 with the sign of the intermediate result and an exponent of Etiny.
  306. In all cases, Inexact, Rounded, and Subnormal will also be raised.
  307. """
  308. # List of public traps and flags
  309. _signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
  310. Underflow, InvalidOperation, Subnormal]
  311. # Map conditions (per the spec) to signals
  312. _condition_map = {ConversionSyntax:InvalidOperation,
  313. DivisionImpossible:InvalidOperation,
  314. DivisionUndefined:InvalidOperation,
  315. InvalidContext:InvalidOperation}
  316. ##### Context Functions ##################################################
  317. # The getcontext() and setcontext() function manage access to a thread-local
  318. # current context. Py2.4 offers direct support for thread locals. If that
  319. # is not available, use threading.currentThread() which is slower but will
  320. # work for older Pythons. If threads are not part of the build, create a
  321. # mock threading object with threading.local() returning the module namespace.
  322. try:
  323. import threading
  324. except ImportError:
  325. # Python was compiled without threads; create a mock object instead
  326. import sys
  327. class MockThreading(object):
  328. def local(self, sys=sys):
  329. return sys.modules[__name__]
  330. threading = MockThreading()
  331. del sys, MockThreading
  332. try:
  333. threading.local
  334. except AttributeError:
  335. # To fix reloading, force it to create a new context
  336. # Old contexts have different exceptions in their dicts, making problems.
  337. if hasattr(threading.currentThread(), '__decimal_context__'):
  338. del threading.currentThread().__decimal_context__
  339. def setcontext(context):
  340. """Set this thread's context to context."""
  341. if context in (DefaultContext, BasicContext, ExtendedContext):
  342. context = context.copy()
  343. context.clear_flags()
  344. threading.currentThread().__decimal_context__ = context
  345. def getcontext():
  346. """Returns this thread's context.
  347. If this thread does not yet have a context, returns
  348. a new context and sets this thread's context.
  349. New contexts are copies of DefaultContext.
  350. """
  351. try:
  352. return threading.currentThread().__decimal_context__
  353. except AttributeError:
  354. context = Context()
  355. threading.currentThread().__decimal_context__ = context
  356. return context
  357. else:
  358. local = threading.local()
  359. if hasattr(local, '__decimal_context__'):
  360. del local.__decimal_context__
  361. def getcontext(_local=local):
  362. """Returns this thread's context.
  363. If this thread does not yet have a context, returns
  364. a new context and sets this thread's context.
  365. New contexts are copies of DefaultContext.
  366. """
  367. try:
  368. return _local.__decimal_context__
  369. except AttributeError:
  370. context = Context()
  371. _local.__decimal_context__ = context
  372. return context
  373. def setcontext(context, _local=local):
  374. """Set this thread's context to context."""
  375. if context in (DefaultContext, BasicContext, ExtendedContext):
  376. context = context.copy()
  377. context.clear_flags()
  378. _local.__decimal_context__ = context
  379. del threading, local # Don't contaminate the namespace
  380. def localcontext(ctx=None):
  381. """Return a context manager for a copy of the supplied context
  382. Uses a copy of the current context if no context is specified
  383. The returned context manager creates a local decimal context
  384. in a with statement:
  385. def sin(x):
  386. with localcontext() as ctx:
  387. ctx.prec += 2
  388. # Rest of sin calculation algorithm
  389. # uses a precision 2 greater than normal
  390. return +s # Convert result to normal precision
  391. def sin(x):
  392. with localcontext(ExtendedContext):
  393. # Rest of sin calculation algorithm
  394. # uses the Extended Context from the
  395. # General Decimal Arithmetic Specification
  396. return +s # Convert result to normal context
  397. >>> setcontext(DefaultContext)
  398. >>> print getcontext().prec
  399. 28
  400. >>> with localcontext():
  401. ... ctx = getcontext()
  402. ... ctx.prec += 2
  403. ... print ctx.prec
  404. ...
  405. 30
  406. >>> with localcontext(ExtendedContext):
  407. ... print getcontext().prec
  408. ...
  409. 9
  410. >>> print getcontext().prec
  411. 28
  412. """
  413. if ctx is None: ctx = getcontext()
  414. return _ContextManager(ctx)
  415. ##### Decimal class #######################################################
  416. class Decimal(object):
  417. """Floating point class for decimal arithmetic."""
  418. __slots__ = ('_exp','_int','_sign', '_is_special')
  419. # Generally, the value of the Decimal instance is given by
  420. # (-1)**_sign * _int * 10**_exp
  421. # Special values are signified by _is_special == True
  422. # We're immutable, so use __new__ not __init__
  423. def __new__(cls, value="0", context=None):
  424. """Create a decimal point instance.
  425. >>> Decimal('3.14') # string input
  426. Decimal('3.14')
  427. >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
  428. Decimal('3.14')
  429. >>> Decimal(314) # int or long
  430. Decimal('314')
  431. >>> Decimal(Decimal(314)) # another decimal instance
  432. Decimal('314')
  433. >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
  434. Decimal('3.14')
  435. """
  436. # Note that the coefficient, self._int, is actually stored as
  437. # a string rather than as a tuple of digits. This speeds up
  438. # the "digits to integer" and "integer to digits" conversions
  439. # that are used in almost every arithmetic operation on
  440. # Decimals. This is an internal detail: the as_tuple function
  441. # and the Decimal constructor still deal with tuples of
  442. # digits.
  443. self = object.__new__(cls)
  444. # From a string
  445. # REs insist on real strings, so we can too.
  446. if isinstance(value, basestring):
  447. m = _parser(value.strip())
  448. if m is None:
  449. if context is None:
  450. context = getcontext()
  451. return context._raise_error(ConversionSyntax,
  452. "Invalid literal for Decimal: %r" % value)
  453. if m.group('sign') == "-":
  454. self._sign = 1
  455. else:
  456. self._sign = 0
  457. intpart = m.group('int')
  458. if intpart is not None:
  459. # finite number
  460. fracpart = m.group('frac') or ''
  461. exp = int(m.group('exp') or '0')
  462. self._int = str(int(intpart+fracpart))
  463. self._exp = exp - len(fracpart)
  464. self._is_special = False
  465. else:
  466. diag = m.group('diag')
  467. if diag is not None:
  468. # NaN
  469. self._int = str(int(diag or '0')).lstrip('0')
  470. if m.group('signal'):
  471. self._exp = 'N'
  472. else:
  473. self._exp = 'n'
  474. else:
  475. # infinity
  476. self._int = '0'
  477. self._exp = 'F'
  478. self._is_special = True
  479. return self
  480. # From an integer
  481. if isinstance(value, (int,long)):
  482. if value >= 0:
  483. self._sign = 0
  484. else:
  485. self._sign = 1
  486. self._exp = 0
  487. self._int = str(abs(value))
  488. self._is_special = False
  489. return self
  490. # From another decimal
  491. if isinstance(value, Decimal):
  492. self._exp = value._exp
  493. self._sign = value._sign
  494. self._int = value._int
  495. self._is_special = value._is_special
  496. return self
  497. # From an internal working value
  498. if isinstance(value, _WorkRep):
  499. self._sign = value.sign
  500. self._int = str(value.int)
  501. self._exp = int(value.exp)
  502. self._is_special = False
  503. return self
  504. # tuple/list conversion (possibly from as_tuple())
  505. if isinstance(value, (list,tuple)):
  506. if len(value) != 3:
  507. raise ValueError('Invalid tuple size in creation of Decimal '
  508. 'from list or tuple. The list or tuple '
  509. 'should have exactly three elements.')
  510. # process sign. The isinstance test rejects floats
  511. if not (isinstance(value[0], (int, long)) and value[0] in (0,1)):
  512. raise ValueError("Invalid sign. The first value in the tuple "
  513. "should be an integer; either 0 for a "
  514. "positive number or 1 for a negative number.")
  515. self._sign = value[0]
  516. if value[2] == 'F':
  517. # infinity: value[1] is ignored
  518. self._int = '0'
  519. self._exp = value[2]
  520. self._is_special = True
  521. else:
  522. # process and validate the digits in value[1]
  523. digits = []
  524. for digit in value[1]:
  525. if isinstance(digit, (int, long)) and 0 <= digit <= 9:
  526. # skip leading zeros
  527. if digits or digit != 0:
  528. digits.append(digit)
  529. else:
  530. raise ValueError("The second value in the tuple must "
  531. "be composed of integers in the range "
  532. "0 through 9.")
  533. if value[2] in ('n', 'N'):
  534. # NaN: digits form the diagnostic
  535. self._int = ''.join(map(str, digits))
  536. self._exp = value[2]
  537. self._is_special = True
  538. elif isinstance(value[2], (int, long)):
  539. # finite number: digits give the coefficient
  540. self._int = ''.join(map(str, digits or [0]))
  541. self._exp = value[2]
  542. self._is_special = False
  543. else:
  544. raise ValueError("The third value in the tuple must "
  545. "be an integer, or one of the "
  546. "strings 'F', 'n', 'N'.")
  547. return self
  548. if isinstance(value, float):
  549. value = Decimal.from_float(value)
  550. self._exp = value._exp
  551. self._sign = value._sign
  552. self._int = value._int
  553. self._is_special = value._is_special
  554. return self
  555. raise TypeError("Cannot convert %r to Decimal" % value)
  556. # @classmethod, but @decorator is not valid Python 2.3 syntax, so
  557. # don't use it (see notes on Py2.3 compatibility at top of file)
  558. def from_float(cls, f):
  559. """Converts a float to a decimal number, exactly.
  560. Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
  561. Since 0.1 is not exactly representable in binary floating point, the
  562. value is stored as the nearest representable value which is
  563. 0x1.999999999999ap-4. The exact equivalent of the value in decimal
  564. is 0.1000000000000000055511151231257827021181583404541015625.
  565. >>> Decimal.from_float(0.1)
  566. Decimal('0.1000000000000000055511151231257827021181583404541015625')
  567. >>> Decimal.from_float(float('nan'))
  568. Decimal('NaN')
  569. >>> Decimal.from_float(float('inf'))
  570. Decimal('Infinity')
  571. >>> Decimal.from_float(-float('inf'))
  572. Decimal('-Infinity')
  573. >>> Decimal.from_float(-0.0)
  574. Decimal('-0')
  575. """
  576. if isinstance(f, (int, long)): # handle integer inputs
  577. return cls(f)
  578. if _math.isinf(f) or _math.isnan(f): # raises TypeError if not a float
  579. return cls(repr(f))
  580. if _math.copysign(1.0, f) == 1.0:
  581. sign = 0
  582. else:
  583. sign = 1
  584. n, d = abs(f).as_integer_ratio()
  585. k = d.bit_length() - 1
  586. result = _dec_from_triple(sign, str(n*5**k), -k)
  587. if cls is Decimal:
  588. return result
  589. else:
  590. return cls(result)
  591. from_float = classmethod(from_float)
  592. def _isnan(self):
  593. """Returns whether the number is not actually one.
  594. 0 if a number
  595. 1 if NaN
  596. 2 if sNaN
  597. """
  598. if self._is_special:
  599. exp = self._exp
  600. if exp == 'n':
  601. return 1
  602. elif exp == 'N':
  603. return 2
  604. return 0
  605. def _isinfinity(self):
  606. """Returns whether the number is infinite
  607. 0 if finite or not a number
  608. 1 if +INF
  609. -1 if -INF
  610. """
  611. if self._exp == 'F':
  612. if self._sign:
  613. return -1
  614. return 1
  615. return 0
  616. def _check_nans(self, other=None, context=None):
  617. """Returns whether the number is not actually one.
  618. if self, other are sNaN, signal
  619. if self, other are NaN return nan
  620. return 0
  621. Done before operations.
  622. """
  623. self_is_nan = self._isnan()
  624. if other is None:
  625. other_is_nan = False
  626. else:
  627. other_is_nan = other._isnan()
  628. if self_is_nan or other_is_nan:
  629. if context is None:
  630. context = getcontext()
  631. if self_is_nan == 2:
  632. return context._raise_error(InvalidOperation, 'sNaN',
  633. self)
  634. if other_is_nan == 2:
  635. return context._raise_error(InvalidOperation, 'sNaN',
  636. other)
  637. if self_is_nan:
  638. return self._fix_nan(context)
  639. return other._fix_nan(context)
  640. return 0
  641. def _compare_check_nans(self, other, context):
  642. """Version of _check_nans used for the signaling comparisons
  643. compare_signal, __le__, __lt__, __ge__, __gt__.
  644. Signal InvalidOperation if either self or other is a (quiet
  645. or signaling) NaN. Signaling NaNs take precedence over quiet
  646. NaNs.
  647. Return 0 if neither operand is a NaN.
  648. """
  649. if context is None:
  650. context = getcontext()
  651. if self._is_special or other._is_special:
  652. if self.is_snan():
  653. return context._raise_error(InvalidOperation,
  654. 'comparison involving sNaN',
  655. self)
  656. elif other.is_snan():
  657. return context._raise_error(InvalidOperation,
  658. 'comparison involving sNaN',
  659. other)
  660. elif self.is_qnan():
  661. return context._raise_error(InvalidOperation,
  662. 'comparison involving NaN',
  663. self)
  664. elif other.is_qnan():
  665. return context._raise_error(InvalidOperation,
  666. 'comparison involving NaN',
  667. other)
  668. return 0
  669. def __nonzero__(self):
  670. """Return True if self is nonzero; otherwise return False.
  671. NaNs and infinities are considered nonzero.
  672. """
  673. return self._is_special or self._int != '0'
  674. def _cmp(self, other):
  675. """Compare the two non-NaN decimal instances self and other.
  676. Returns -1 if self < other, 0 if self == other and 1
  677. if self > other. This routine is for internal use only."""
  678. if self._is_special or other._is_special:
  679. self_inf = self._isinfinity()
  680. other_inf = other._isinfinity()
  681. if self_inf == other_inf:
  682. return 0
  683. elif self_inf < other_inf:
  684. return -1
  685. else:
  686. return 1
  687. # check for zeros; Decimal('0') == Decimal('-0')
  688. if not self:
  689. if not other:
  690. return 0
  691. else:
  692. return -((-1)**other._sign)
  693. if not other:
  694. return (-1)**self._sign
  695. # If different signs, neg one is less
  696. if other._sign < self._sign:
  697. return -1
  698. if self._sign < other._sign:
  699. return 1
  700. self_adjusted = self.adjusted()
  701. other_adjusted = other.adjusted()
  702. if self_adjusted == other_adjusted:
  703. self_padded = self._int + '0'*(self._exp - other._exp)
  704. other_padded = other._int + '0'*(other._exp - self._exp)
  705. if self_padded == other_padded:
  706. return 0
  707. elif self_padded < other_padded:
  708. return -(-1)**self._sign
  709. else:
  710. return (-1)**self._sign
  711. elif self_adjusted > other_adjusted:
  712. return (-1)**self._sign
  713. else: # self_adjusted < other_adjusted
  714. return -((-1)**self._sign)
  715. # Note: The Decimal standard doesn't cover rich comparisons for
  716. # Decimals. In particular, the specification is silent on the
  717. # subject of what should happen for a comparison involving a NaN.
  718. # We take the following approach:
  719. #
  720. # == comparisons involving a quiet NaN always return False
  721. # != comparisons involving a quiet NaN always return True
  722. # == or != comparisons involving a signaling NaN signal
  723. # InvalidOperation, and return False or True as above if the
  724. # InvalidOperation is not trapped.
  725. # <, >, <= and >= comparisons involving a (quiet or signaling)
  726. # NaN signal InvalidOperation, and return False if the
  727. # InvalidOperation is not trapped.
  728. #
  729. # This behavior is designed to conform as closely as possible to
  730. # that specified by IEEE 754.
  731. def __eq__(self, other, context=None):
  732. other = _convert_other(other, allow_float=True)
  733. if other is NotImplemented:
  734. return other
  735. if self._check_nans(other, context):
  736. return False
  737. return self._cmp(other) == 0
  738. def __ne__(self, other, context=None):
  739. other = _convert_other(other, allow_float=True)
  740. if other is NotImplemented:
  741. return other
  742. if self._check_nans(other, context):
  743. return True
  744. return self._cmp(other) != 0
  745. def __lt__(self, other, context=None):
  746. other = _convert_other(other, allow_float=True)
  747. if other is NotImplemented:
  748. return other
  749. ans = self._compare_check_nans(other, context)
  750. if ans:
  751. return False
  752. return self._cmp(other) < 0
  753. def __le__(self, other, context=None):
  754. other = _convert_other(other, allow_float=True)
  755. if other is NotImplemented:
  756. return other
  757. ans = self._compare_check_nans(other, context)
  758. if ans:
  759. return False
  760. return self._cmp(other) <= 0
  761. def __gt__(self, other, context=None):
  762. other = _convert_other(other, allow_float=True)
  763. if other is NotImplemented:
  764. return other
  765. ans = self._compare_check_nans(other, context)
  766. if ans:
  767. return False
  768. return self._cmp(other) > 0
  769. def __ge__(self, other, context=None):
  770. other = _convert_other(other, allow_float=True)
  771. if other is NotImplemented:
  772. return other
  773. ans = self._compare_check_nans(other, context)
  774. if ans:
  775. return False
  776. return self._cmp(other) >= 0
  777. def compare(self, other, context=None):
  778. """Compares one to another.
  779. -1 => a < b
  780. 0 => a = b
  781. 1 => a > b
  782. NaN => one is NaN
  783. Like __cmp__, but returns Decimal instances.
  784. """
  785. other = _convert_other(other, raiseit=True)
  786. # Compare(NaN, NaN) = NaN
  787. if (self._is_special or other and other._is_special):
  788. ans = self._check_nans(other, context)
  789. if ans:
  790. return ans
  791. return Decimal(self._cmp(other))
  792. def __hash__(self):
  793. """x.__hash__() <==> hash(x)"""
  794. # Decimal integers must hash the same as the ints
  795. #
  796. # The hash of a nonspecial noninteger Decimal must depend only
  797. # on the value of that Decimal, and not on its representation.
  798. # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
  799. # Equality comparisons involving signaling nans can raise an
  800. # exception; since equality checks are implicitly and
  801. # unpredictably used when checking set and dict membership, we
  802. # prevent signaling nans from being used as set elements or
  803. # dict keys by making __hash__ raise an exception.
  804. if self._is_special:
  805. if self.is_snan():
  806. raise TypeError('Cannot hash a signaling NaN value.')
  807. elif self.is_nan():
  808. # 0 to match hash(float('nan'))
  809. return 0
  810. else:
  811. # values chosen to match hash(float('inf')) and
  812. # hash(float('-inf')).
  813. if self._sign:
  814. return -271828
  815. else:
  816. return 314159
  817. # In Python 2.7, we're allowing comparisons (but not
  818. # arithmetic operations) between floats and Decimals; so if
  819. # a Decimal instance is exactly representable as a float then
  820. # its hash should match that of the float.
  821. self_as_float = float(self)
  822. if Decimal.from_float(self_as_float) == self:
  823. return hash(self_as_float)
  824. if self._isinteger():
  825. op = _WorkRep(self.to_integral_value())
  826. # to make computation feasible for Decimals with large
  827. # exponent, we use the fact that hash(n) == hash(m) for
  828. # any two nonzero integers n and m such that (i) n and m
  829. # have the same sign, and (ii) n is congruent to m modulo
  830. # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
  831. # hash((-1)**s*c*pow(10, e, 2**64-1).
  832. return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
  833. # The value of a nonzero nonspecial Decimal instance is
  834. # faithfully represented by the triple consisting of its sign,
  835. # its adjusted exponent, and its coefficient with trailing
  836. # zeros removed.
  837. return hash((self._sign,
  838. self._exp+len(self._int),
  839. self._int.rstrip('0')))
  840. def as_tuple(self):
  841. """Represents the number as a triple tuple.
  842. To show the internals exactly as they are.
  843. """
  844. return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
  845. def __repr__(self):
  846. """Represents the number as an instance of Decimal."""
  847. # Invariant: eval(repr(d)) == d
  848. return "Decimal('%s')" % str(self)
  849. def __str__(self, eng=False, context=None):
  850. """Return string representation of the number in scientific notation.
  851. Captures all of the information in the underlying representation.
  852. """
  853. sign = ['', '-'][self._sign]
  854. if self._is_special:
  855. if self._exp == 'F':
  856. return sign + 'Infinity'
  857. elif self._exp == 'n':
  858. return sign + 'NaN' + self._int
  859. else: # self._exp == 'N'
  860. return sign + 'sNaN' + self._int
  861. # number of digits of self._int to left of decimal point
  862. leftdigits = self._exp + len(self._int)
  863. # dotplace is number of digits of self._int to the left of the
  864. # decimal point in the mantissa of the output string (that is,
  865. # after adjusting the exponent)
  866. if self._exp <= 0 and leftdigits > -6:
  867. # no exponent required
  868. dotplace = leftdigits
  869. elif not eng:
  870. # usual scientific notation: 1 digit on left of the point
  871. dotplace = 1
  872. elif self._int == '0':
  873. # engineering notation, zero
  874. dotplace = (leftdigits + 1) % 3 - 1
  875. else:
  876. # engineering notation, nonzero
  877. dotplace = (leftdigits - 1) % 3 + 1
  878. if dotplace <= 0:
  879. intpart = '0'
  880. fracpart = '.' + '0'*(-dotplace) + self._int
  881. elif dotplace >= len(self._int):
  882. intpart = self._int+'0'*(dotplace-len(self._int))
  883. fracpart = ''
  884. else:
  885. intpart = self._int[:dotplace]
  886. fracpart = '.' + self._int[dotplace:]
  887. if leftdigits == dotplace:
  888. exp = ''
  889. else:
  890. if context is None:
  891. context = getcontext()
  892. exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
  893. return sign + intpart + fracpart + exp
  894. def to_eng_string(self, context=None):
  895. """Convert to engineering-type string.
  896. Engineering notation has an exponent which is a multiple of 3, so there
  897. are up to 3 digits left of the decimal place.
  898. Same rules for when in exponential and when as a value as in __str__.
  899. """
  900. return self.__str__(eng=True, context=context)
  901. def __neg__(self, context=None):
  902. """Returns a copy with the sign switched.
  903. Rounds, if it has reason.
  904. """
  905. if self._is_special:
  906. ans = self._check_nans(context=context)
  907. if ans:
  908. return ans
  909. if context is None:
  910. context = getcontext()
  911. if not self and context.rounding != ROUND_FLOOR:
  912. # -Decimal('0') is Decimal('0'), not Decimal('-0'), except
  913. # in ROUND_FLOOR rounding mode.
  914. ans = self.copy_abs()
  915. else:
  916. ans = self.copy_negate()
  917. return ans._fix(context)
  918. def __pos__(self, context=None):
  919. """Returns a copy, unless it is a sNaN.
  920. Rounds the number (if more then precision digits)
  921. """
  922. if self._is_special:
  923. ans = self._check_nans(context=context)
  924. if ans:
  925. return ans
  926. if context is None:
  927. context = getcontext()
  928. if not self and context.rounding != ROUND_FLOOR:
  929. # + (-0) = 0, except in ROUND_FLOOR rounding mode.
  930. ans = self.copy_abs()
  931. else:
  932. ans = Decimal(self)
  933. return ans._fix(context)
  934. def __abs__(self, round=True, context=None):
  935. """Returns the absolute value of self.
  936. If the keyword argument 'round' is false, do not round. The
  937. expression self.__abs__(round=False) is equivalent to
  938. self.copy_abs().
  939. """
  940. if not round:
  941. return self.copy_abs()
  942. if self._is_special:
  943. ans = self._check_nans(context=context)
  944. if ans:
  945. return ans
  946. if self._sign:
  947. ans = self.__neg__(context=context)
  948. else:
  949. ans = self.__pos__(context=context)
  950. return ans
  951. def __add__(self, other, context=None):
  952. """Returns self + other.
  953. -INF + INF (or the reverse) cause InvalidOperation errors.
  954. """
  955. other = _convert_other(other)
  956. if other is NotImplemented:
  957. return other
  958. if context is None:
  959. context = getcontext()
  960. if self._is_special or other._is_special:
  961. ans = self._check_nans(other, context)
  962. if ans:
  963. return ans
  964. if self._isinfinity():
  965. # If both INF, same sign => same as both, opposite => error.
  966. if self._sign != other._sign and other._isinfinity():
  967. return context._raise_error(InvalidOperation, '-INF + INF')
  968. return Decimal(self)
  969. if other._isinfinity():
  970. return Decimal(other) # Can't both be infinity here
  971. exp = min(self._exp, other._exp)
  972. negativezero = 0
  973. if context.rounding == ROUND_FLOOR and self._sign != other._sign:
  974. # If the answer is 0, the sign should be negative, in this case.
  975. negativezero = 1
  976. if not self and not other:
  977. sign = min(self._sign, other._sign)
  978. if negativezero:
  979. sign = 1
  980. ans = _dec_from_triple(sign, '0', exp)
  981. ans = ans._fix(context)
  982. return ans
  983. if not self:
  984. exp = max(exp, other._exp - context.prec-1)
  985. ans = other._rescale(exp, context.rounding)
  986. ans = ans._fix(context)
  987. return ans
  988. if not other:
  989. exp = max(exp, self._exp - context.prec-1)
  990. ans = self._rescale(exp, context.rounding)
  991. ans = ans._fix(context)
  992. return ans
  993. op1 = _WorkRep(self)
  994. op2 = _WorkRep(other)
  995. op1, op2 = _normalize(op1, op2, context.prec)
  996. result = _WorkRep()
  997. if op1.sign != op2.sign:
  998. # Equal and opposite
  999. if op1.int == op2.int:
  1000. ans = _dec_from_triple(negativezero, '0', exp)
  1001. ans = ans._fix(context)
  1002. return ans
  1003. if op1.int < op2.int:
  1004. op1, op2 = op2, op1
  1005. # OK, now abs(op1) > abs(op2)
  1006. if op1.sign == 1:
  1007. result.sign = 1
  1008. op1.sign, op2.sign = op2.sign, op1.sign
  1009. else:
  1010. result.sign = 0
  1011. # So we know the sign, and op1 > 0.
  1012. elif op1.sign == 1:
  1013. result.sign = 1
  1014. op1.sign, op2.sign = (0, 0)
  1015. else:
  1016. result.sign = 0
  1017. # Now, op1 > abs(op2) > 0
  1018. if op2.sign == 0:
  1019. result.int = op1.int + op2.int
  1020. else:
  1021. result.int = op1.int - op2.int
  1022. result.exp = op1.exp
  1023. ans = Decimal(result)
  1024. ans = ans._fix(context)
  1025. return ans
  1026. __radd__ = __add__
  1027. def __sub__(self, other, context=None):
  1028. """Return self - other"""
  1029. other = _convert_other(other)
  1030. if other is NotImplemented:
  1031. return other
  1032. if self._is_special or other._is_special:
  1033. ans = self._check_nans(other, context=context)
  1034. if ans:
  1035. return ans
  1036. # self - other is computed as self + other.copy_negate()
  1037. return self.__add__(other.copy_negate(), context=context)
  1038. def __rsub__(self, other, context=None):
  1039. """Return other - self"""
  1040. other = _convert_other(other)
  1041. if other is NotImplemented:
  1042. return other
  1043. return other.__sub__(self, context=context)
  1044. def __mul__(self, other, context=None):
  1045. """Return self * other.
  1046. (+-) INF * 0 (or its reverse) raise InvalidOperation.
  1047. """
  1048. other = _convert_other(other)
  1049. if other is NotImplemented:
  1050. return other
  1051. if context is None:
  1052. context = getcontext()
  1053. resultsign = self._sign ^ other._sign
  1054. if self._is_special or other._is_special:
  1055. ans = self._check_nans(other, context)
  1056. if ans:
  1057. return ans
  1058. if self._isinfinity():
  1059. if not other:
  1060. return context._raise_error(InvalidOperation, '(+-)INF * 0')
  1061. return _SignedInfinity[resultsign]
  1062. if other._isinfinity():
  1063. if not self:
  1064. return context._raise_error(InvalidOperation, '0 * (+-)INF')
  1065. return _SignedInfinity[resultsign]
  1066. resultexp = self._exp + other._exp
  1067. # Special case for multiplying by zero
  1068. if not self or not other:
  1069. ans = _dec_from_triple(resultsign, '0', resultexp)
  1070. # Fixing in case the exponent is out of bounds
  1071. ans = ans._fix(context)
  1072. return ans
  1073. # Special case for multiplying by power of 10
  1074. if self._int == '1':
  1075. ans = _dec_from_triple(resultsign, other._int, resultexp)
  1076. ans = ans._fix(context)
  1077. return ans
  1078. if other._int == '1':
  1079. ans = _dec_from_triple(resultsign, self._int, resultexp)
  1080. ans = ans._fix(context)
  1081. return ans
  1082. op1 = _WorkRep(self)
  1083. op2 = _WorkRep(other)
  1084. ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
  1085. ans = ans._fix(context)
  1086. return ans
  1087. __rmul__ = __mul__
  1088. def __truediv__(self, other, context=None):
  1089. """Return self / other."""
  1090. other = _convert_other(other)
  1091. if other is NotImplemented:
  1092. return NotImplemented
  1093. if context is None:
  1094. context = getcontext()
  1095. sign = self._sign ^ other._sign
  1096. if self._is_special or other._is_special:
  1097. ans = self._check_nans(other, context)
  1098. if ans:
  1099. return ans
  1100. if self._isinfinity() and other._isinfinity():
  1101. return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
  1102. if self._isinfinity():
  1103. return _SignedInfinity[sign]
  1104. if other._isinfinity():
  1105. context._raise_error(Clamped, 'Division by infinity')
  1106. return _dec_from_triple(sign, '0', context.Etiny())
  1107. # Special cases for zeroes
  1108. if not other:
  1109. if not self:
  1110. return context._raise_error(DivisionUndefined, '0 / 0')
  1111. return context._raise_error(DivisionByZero, 'x / 0', sign)
  1112. if not self:
  1113. exp = self._exp - other._exp
  1114. coeff = 0
  1115. else:
  1116. # OK, so neither = 0, INF or NaN
  1117. shift = len(other._int) - len(self._int) + context.prec + 1
  1118. exp = self._exp - other._exp - shift
  1119. op1 = _WorkRep(self)
  1120. op2 = _WorkRep(other)
  1121. if shift >= 0:
  1122. coeff, remainder = divmod(op1.int * 10**shift, op2.int)
  1123. else:
  1124. coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
  1125. if remainder:
  1126. # result is not exact; adjust to ensure correct rounding
  1127. if coeff % 5 == 0:
  1128. coeff += 1
  1129. else:
  1130. # result is exact; get as close to ideal exponent as possible
  1131. ideal_exp = self._exp - other._exp
  1132. while exp < ideal_exp and coeff % 10 == 0:
  1133. coeff //= 10
  1134. exp += 1
  1135. ans = _dec_from_triple(sign, str(coeff), exp)
  1136. return ans._fix(context)
  1137. def _divide(self, other, context):
  1138. """Return (self // other, self % other), to context.prec precision.
  1139. Assumes that neither self nor other is a NaN, that self is not
  1140. infinite and that other is nonzero.
  1141. """
  1142. sign = self._sign ^ other._sign
  1143. if other._isinfinity():
  1144. ideal_exp = self._exp
  1145. else:
  1146. ideal_exp = min(self._exp, other._exp)
  1147. expdiff = self.adjusted() - other.adjusted()
  1148. if not self or other._isinfinity() or expdiff <= -2:
  1149. return (_dec_from_triple(sign, '0', 0),
  1150. self._rescale(ideal_exp, context.rounding))
  1151. if expdiff <= context.prec:
  1152. op1 = _WorkRep(self)
  1153. op2 = _WorkRep(other)
  1154. if op1.exp >= op2.exp:
  1155. op1.int *= 10**(op1.exp - op2.exp)
  1156. else:
  1157. op2.int *= 10**(op2.exp - op1.exp)
  1158. q, r = divmod(op1.int, op2.int)
  1159. if q < 10**context.prec:
  1160. return (_dec_from_triple(sign, str(q), 0),
  1161. _dec_from_triple(self._sign, str(r), ideal_exp))
  1162. # Here the quotient is too large to be representable
  1163. ans = context._raise_error(DivisionImpossible,
  1164. 'quotient too large in //, % or divmod')
  1165. return ans, ans
  1166. def __rtruediv__(self, other, context=None):
  1167. """Swaps self/other and returns __truediv__."""
  1168. other = _convert_other(other)
  1169. if other is NotImplemented:
  1170. return other
  1171. return other.__truediv__(self, context=context)
  1172. __div__ = __truediv__
  1173. __rdiv__ = __rtruediv__
  1174. def __divmod__(self, other, context=None):
  1175. """
  1176. Return (self // other, self % other)
  1177. """
  1178. other = _convert_other(other)
  1179. if other is NotImplemented:
  1180. return other
  1181. if context is None:
  1182. context = getcontext()
  1183. ans = self._check_nans(other, context)
  1184. if ans:
  1185. return (ans, ans)
  1186. sign = self._sign ^ other._sign
  1187. if self._isinfinity():
  1188. if other._isinfinity():
  1189. ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
  1190. return ans, ans
  1191. else:
  1192. return (_SignedInfinity[sign],
  1193. context._raise_error(InvalidOperation, 'INF % x'))
  1194. if not other:
  1195. if not self:
  1196. ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
  1197. return ans, ans
  1198. else:
  1199. return (context._raise_error(DivisionByZero, 'x // 0', sign),
  1200. context._raise_error(InvalidOperation, 'x % 0'))
  1201. quotient, remainder = self._divide(other, context)
  1202. remainder = remainder._fix(context)
  1203. return quotient, remainder
  1204. def __rdivmod__(self, other, context=None):
  1205. """Swaps self/other and returns __divmod__."""
  1206. other = _convert_other(other)
  1207. if other is NotImplemented:
  1208. return other
  1209. return other.__divmod__(self, context=context)
  1210. def __mod__(self, other, context=None):
  1211. """
  1212. self % other
  1213. """
  1214. other = _convert_other(other)
  1215. if other is NotImplemented:
  1216. return other
  1217. if context is None:
  1218. context = getcontext()
  1219. ans = self._check_nans(other, context)
  1220. if ans:
  1221. return ans
  1222. if self._isinfinity():
  1223. return context._raise_error(InvalidOperation, 'INF % x')
  1224. elif not other:
  1225. if self:
  1226. return context._raise_error(InvalidOperation, 'x % 0')
  1227. else:
  1228. return context._raise_error(DivisionUndefined, '0 % 0')
  1229. remainder = self._divide(other, context)[1]
  1230. remainder = remainder._fix(context)
  1231. return remainder
  1232. def __rmod__(self, other, context=None):
  1233. """Swaps self/other and returns __mod__."""
  1234. other = _convert_other(other)
  1235. if other is NotImplemented:
  1236. return other
  1237. return other.__mod__(self, context=context)
  1238. def remainder_near(self, other, context=None):
  1239. """
  1240. Remainder nearest to 0- abs(remainder-near) <= other/2
  1241. """
  1242. if context is None:
  1243. context = getcontext()
  1244. other = _convert_other(other, raiseit=True)
  1245. ans = self._check_nans(other, context)
  1246. if ans:
  1247. return ans
  1248. # self == +/-infinity -> InvalidOperation
  1249. if self._isinfinity():
  1250. return context._raise_error(InvalidOperation,
  1251. 'remainder_near(infinity, x)')
  1252. # other == 0 -> either InvalidOperation or DivisionUndefined
  1253. if not other:
  1254. if self:
  1255. return context._raise_error(InvalidOperation,
  1256. 'remainder_near(x, 0)')
  1257. else:
  1258. return context._raise_error(DivisionUndefined,
  1259. 'remainder_near(0, 0)')
  1260. # other = +/-infinity -> remainder = self
  1261. if other._isinfinity():
  1262. ans = Decimal(self)
  1263. return ans._fix(context)
  1264. # self = 0 -> remainder = self, with ideal exponent
  1265. ideal_exponent = min(self._exp, other._exp)
  1266. if not self:
  1267. ans = _dec_from_triple(self._sign, '0', ideal_exponent)
  1268. return ans._fix(context)
  1269. # catch most cases of large or small quotient
  1270. expdiff = self.adjusted() - other.adjusted()
  1271. if expdiff >= context.prec + 1:
  1272. # expdiff >= prec+1 => abs(self/other) > 10**prec
  1273. return context._raise_error(DivisionImpossible)
  1274. if expdiff <= -2:
  1275. # expdiff <= -2 => abs(self/other) < 0.1
  1276. ans = self._rescale(ideal_exponent, context.rounding)
  1277. return ans._fix(context)
  1278. # adjust both arguments to have the same exponent, then divide
  1279. op1 = _WorkRep(self)
  1280. op2 = _WorkRep(other)
  1281. if op1.exp >= op2.exp:
  1282. op1.int *= 10**(op1.exp - op2.exp)
  1283. else:
  1284. op2.int *= 10**(op2.exp - op1.exp)
  1285. q, r = divmod(op1.int, op2.int)
  1286. # remainder is r*10**ideal_exponent; other is +/-op2.int *
  1287. # 10**ideal_exponent. Apply correction to ensure that
  1288. # abs(remainder) <= abs(other)/2
  1289. if 2*r + (q&1) > op2.int:
  1290. r -= op2.int
  1291. q += 1
  1292. if q >= 10**context.prec:
  1293. return context._raise_error(DivisionImpossible)
  1294. # result has same sign as self unless r is negative
  1295. sign = self._sign
  1296. if r < 0:
  1297. sign = 1-sign
  1298. r = -r
  1299. ans = _dec_from_triple(sign, str(r), ideal_exponent)
  1300. return ans._fix(context)
  1301. def __floordiv__(self, other, context=None):
  1302. """self // other"""
  1303. other = _convert_other(other)
  1304. if other is NotImplemented:
  1305. return other
  1306. if context is None:
  1307. context = getcontext()
  1308. ans = self._check_nans(other, context)
  1309. if ans:
  1310. return ans
  1311. if self._isinfinity():
  1312. if other._isinfinity():
  1313. return context._raise_error(InvalidOperation, 'INF // INF')
  1314. else:
  1315. return _SignedInfinity[self._sign ^ other._sign]
  1316. if not other:
  1317. if self:
  1318. return context._raise_error(DivisionByZero, 'x // 0',
  1319. self._sign ^ other._sign)
  1320. else:
  1321. return context._raise_error(DivisionUndefined, '0 // 0')
  1322. return self._divide(other, context)[0]
  1323. def __rfloordiv__(self, other, context=None):
  1324. """Swaps self/other and returns __floordiv__."""
  1325. other = _convert_other(other)
  1326. if other is NotImplemented:
  1327. return other
  1328. return other.__floordiv__(self, context=context)
  1329. def __float__(self):
  1330. """Float representation."""
  1331. return float(str(self))
  1332. def __int__(self):
  1333. """Converts self to an int, truncating if necessary."""
  1334. if self._is_special:
  1335. if self._isnan():
  1336. raise ValueError("Cannot convert NaN to integer")
  1337. elif self._isinfinity():
  1338. raise OverflowError("Cannot convert infinity to integer")
  1339. s = (-1)**self._sign
  1340. if self._exp >= 0:
  1341. return s*int(self._int)*10**self._exp
  1342. else:
  1343. return s*int(self._int[:self._exp] or '0')
  1344. __trunc__ = __int__
  1345. def real(self):
  1346. return self
  1347. real = property(real)
  1348. def imag(self):
  1349. return Decimal(0)
  1350. imag = property(imag)
  1351. def conjugate(self):
  1352. return self
  1353. def __complex__(self):
  1354. return complex(float(self))
  1355. def __long__(self):
  1356. """Converts to a long.
  1357. Equivalent to long(int(self))
  1358. """
  1359. return long(self.__int__())
  1360. def _fix_nan(self, context):
  1361. """Decapitate the payload of a NaN to fit the context"""
  1362. payload = self._int
  1363. # maximum length of payload is precision if _clamp=0,
  1364. # precision-1 if _clamp=1.
  1365. max_payload_len = context.prec - context._clamp
  1366. if len(payload) > max_payload_len:
  1367. payload = payload[len(payload)-max_payload_len:].lstrip('0')
  1368. return _dec_from_triple(self._sign, payload, self._exp, True)
  1369. return Decimal(self)
  1370. def _fix(self, context):
  1371. """Round if it is necessary to keep self within prec precision.
  1372. Rounds and fixes the exponent. Does not raise on a sNaN.
  1373. Arguments:
  1374. self - Decimal instance
  1375. context - context used.
  1376. """
  1377. if self._is_special:
  1378. if self._isnan():
  1379. # decapitate payload if necessary
  1380. return self._fix_nan(context)
  1381. else:
  1382. # self is +/-Infinity; return unaltered
  1383. return Decimal(self)
  1384. # if self is zero then exponent should be between Etiny and
  1385. # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
  1386. Etiny = context.Etiny()
  1387. Etop = context.Etop()
  1388. if not self:
  1389. exp_max = [context.Emax, Etop][context._clamp]
  1390. new_exp = min(max(self._exp, Etiny), exp_max)
  1391. if new_exp != self._exp:
  1392. context._raise_error(Clamped)
  1393. return _dec_from_triple(self._sign, '0', new_exp)
  1394. else:
  1395. return Decimal(self)
  1396. # exp_min is the smallest allowable exponent of the result,
  1397. # equal to max(self.adjusted()-context.prec+1, Etiny)
  1398. exp_min = len(self._int) + self._exp - context.prec
  1399. if exp_min > Etop:
  1400. # overflow: exp_min > Etop iff self.adjusted() > Emax
  1401. ans = context._raise_error(Overflow, 'above Emax', self._sign)
  1402. context._raise_error(Inexact)
  1403. context._raise_error(Rounded)
  1404. return ans
  1405. self_is_subnormal = exp_min < Etiny
  1406. if self_is_subnormal:
  1407. exp_min = Etiny
  1408. # round if self has too many digits
  1409. if self._exp < exp_min:
  1410. digits = len(self._int) + self._exp - exp_min
  1411. if digits < 0:
  1412. self = _dec_from_triple(self._sign, '1', exp_min-1)
  1413. digits = 0
  1414. rounding_method = self._pick_rounding_function[context.rounding]
  1415. changed = rounding_method(self, digits)
  1416. coeff = self._int[:digits] or '0'
  1417. if changed > 0:
  1418. coeff = str(int(coeff)+1)
  1419. if len(coeff) > context.prec:
  1420. coeff = coeff[:-1]
  1421. exp_min += 1
  1422. # check whether the rounding pushed the exponent out of range
  1423. if exp_min > Etop:
  1424. ans = context._raise_error(Overflow, 'above Emax', self._sign)
  1425. else:
  1426. ans = _dec_from_triple(self._sign, coeff, exp_min)
  1427. # raise the appropriate signals, taking care to respect
  1428. # the precedence described in the specification
  1429. if changed and self_is_subnormal:
  1430. context._raise_error(Underflow)
  1431. if self_is_subnormal:
  1432. context._raise_error(Subnormal)
  1433. if changed:
  1434. context._raise_error(Inexact)
  1435. context._raise_error(Rounded)
  1436. if not ans:
  1437. # raise Clamped on underflow to 0
  1438. context._raise_error(Clamped)
  1439. return ans
  1440. if self_is_subnormal:
  1441. context._raise_error(Subnormal)
  1442. # fold down if _clamp == 1 and self has too few digits
  1443. if context._clamp == 1 and self._exp > Etop:
  1444. context._raise_error(Clamped)
  1445. self_padded = self._int + '0'*(self._exp - Etop)
  1446. return _dec_from_triple(self._sign, self_padded, Etop)
  1447. # here self was representable to begin with; return unchanged
  1448. return Decimal(self)
  1449. # for each of the rounding functions below:
  1450. # self is a finite, nonzero Decimal
  1451. # prec is an integer satisfying 0 <= prec < len(self._int)
  1452. #
  1453. # each function returns either -1, 0, or 1, as follows:
  1454. # 1 indicates that self should be rounded up (away from zero)
  1455. # 0 indicates that self should be truncated, and that all the
  1456. # digits to be truncated are zeros (so the value is unchanged)
  1457. # -1 indicates that there are nonzero digits to be truncated
  1458. def _round_down(self, prec):
  1459. """Also known as round-towards-0, truncate."""
  1460. if _all_zeros(self._int, prec):
  1461. return 0
  1462. else:
  1463. return -1
  1464. def _round_up(self, prec):
  1465. """Rounds away from 0."""
  1466. return -self._round_down(prec)
  1467. def _round_half_up(self, prec):
  1468. """Rounds 5 up (away from 0)"""
  1469. if self._int[prec] in '56789':
  1470. return 1
  1471. elif _all_zeros(self._int, prec):
  1472. return 0
  1473. else:
  1474. return -1
  1475. def _round_half_down(self, prec):
  1476. """Round 5 down"""
  1477. if _exact_half(self._int, prec):
  1478. return -1
  1479. else:
  1480. return self._round_half_up(prec)
  1481. def _round_half_even(self, prec):
  1482. """Round 5 to even, rest to nearest."""
  1483. if _exact_half(self._int, prec) and \
  1484. (prec == 0 or self._int[prec-1] in '02468'):
  1485. return -1
  1486. else:
  1487. return self._round_half_up(prec)
  1488. def _round_ceiling(self, prec):
  1489. """Rounds up (not away from 0 if negative.)"""
  1490. if self._sign:
  1491. return self._round_down(prec)
  1492. else:
  1493. return -self._round_down(prec)
  1494. def _round_floor(self, prec):
  1495. """Rounds down (not towards 0 if negative)"""
  1496. if not self._sign:
  1497. return self._round_down(prec)
  1498. else:
  1499. return -self._round_down(prec)
  1500. def _round_05up(self, prec):
  1501. """Round down unless digit prec-1 is 0 or 5."""
  1502. if prec and self._int[prec-1] not in '05':
  1503. return self._round_down(prec)
  1504. else:
  1505. return -self._round_down(prec)
  1506. _pick_rounding_function = dict(
  1507. ROUND_DOWN = _round_down,
  1508. ROUND_UP = _round_up,
  1509. ROUND_HALF_UP = _round_half_up,
  1510. ROUND_HALF_DOWN = _round_half_down,
  1511. ROUND_HALF_EVEN = _round_half_even,
  1512. ROUND_CEILING = _round_ceiling,
  1513. ROUND_FLOOR = _round_floor,
  1514. ROUND_05UP = _round_05up,
  1515. )
  1516. def fma(self, other, third, context=None):
  1517. """Fused multiply-add.
  1518. Returns self*other+third with no rounding of the intermediate
  1519. product self*other.
  1520. self and other are multiplied together, with no rounding of
  1521. the result. The third operand is then added to the result,
  1522. and a single final rounding is performed.
  1523. """
  1524. other = _convert_other(other, raiseit=True)
  1525. # compute product; raise InvalidOperation if either operand is
  1526. # a signaling NaN or if the product is zero times infinity.
  1527. if self._is_special or other._is_special:
  1528. if context is None:
  1529. context = getcontext()
  1530. if self._exp == 'N':
  1531. return context._raise_error(InvalidOperation, 'sNaN', self)
  1532. if other._exp == 'N':
  1533. return context._raise_error(InvalidOperation, 'sNaN', other)
  1534. if self._exp == 'n':
  1535. product = self
  1536. elif other._exp == 'n':
  1537. product = other
  1538. elif self._exp == 'F':
  1539. if not other:
  1540. return context._raise_error(InvalidOperation,
  1541. 'INF * 0 in fma')
  1542. product = _SignedInfinity[self._sign ^ other._sign]
  1543. elif other._exp == 'F':
  1544. if not self:
  1545. return context._raise_error(InvalidOperation,
  1546. '0 * INF in fma')
  1547. product = _SignedInfinity[self._sign ^ other._sign]
  1548. else:
  1549. product = _dec_from_triple(self._sign ^ other._sign,
  1550. str(int(self._int) * int(other._int)),
  1551. self._exp + other._exp)
  1552. third = _convert_other(third, raiseit=True)
  1553. return product.__add__(third, context)
  1554. def _power_modulo(self, other, modulo, context=None):
  1555. """Three argument version of __pow__"""
  1556. # if can't convert other and modulo to Decimal, raise
  1557. # TypeError; there's no point returning NotImplemented (no
  1558. # equivalent of __rpow__ for three argument pow)
  1559. other = _convert_other(other, raiseit=True)
  1560. modulo = _convert_other(modulo, raiseit=True)
  1561. if context is None:
  1562. context = getcontext()
  1563. # deal with NaNs: if there are any sNaNs then first one wins,
  1564. # (i.e. behaviour for NaNs is identical to that of fma)
  1565. self_is_nan = self._isnan()
  1566. other_is_nan = other._isnan()
  1567. modulo_is_nan = modulo._isnan()
  1568. if self_is_nan or other_is_nan or modulo_is_nan:
  1569. if self_is_nan == 2:
  1570. return context._raise_error(InvalidOperation, 'sNaN',
  1571. self)
  1572. if other_is_nan == 2:
  1573. return context._raise_error(InvalidOperation, 'sNaN',
  1574. other)
  1575. if modulo_is_nan == 2:
  1576. return context._raise_error(InvalidOperation, 'sNaN',
  1577. modulo)
  1578. if self_is_nan:
  1579. return self._fix_nan(context)
  1580. if other_is_nan:
  1581. return other._fix_nan(context)
  1582. return modulo._fix_nan(context)
  1583. # check inputs: we apply same restrictions as Python's pow()
  1584. if not (self._isinteger() and
  1585. other._isinteger() and
  1586. modulo._isinteger()):
  1587. return context._raise_error(InvalidOperation,
  1588. 'pow() 3rd argument not allowed '
  1589. 'unless all arguments are integers')
  1590. if other < 0:
  1591. return context._raise_error(InvalidOperation,
  1592. 'pow() 2nd argument cannot be '
  1593. 'negative when 3rd argument specified')
  1594. if not modulo:
  1595. return context._raise_error(InvalidOperation,
  1596. 'pow() 3rd argument cannot be 0')
  1597. # additional restriction for decimal: the modulus must be less
  1598. # than 10**prec in absolute value
  1599. if modulo.adjusted() >= context.prec:
  1600. return context._raise_error(InvalidOperation,
  1601. 'insufficient precision: pow() 3rd '
  1602. 'argument must not have more than '
  1603. 'precision digits')
  1604. # define 0**0 == NaN, for consistency with two-argument pow
  1605. # (even though it hurts!)
  1606. if not other and not self:
  1607. return context._raise_error(InvalidOperation,
  1608. 'at least one of pow() 1st argument '
  1609. 'and 2nd argument must be nonzero ;'
  1610. '0**0 is not defined')
  1611. # compute sign of result
  1612. if other._iseven():
  1613. sign = 0
  1614. else:
  1615. sign = self._sign
  1616. # convert modulo to a Python integer, and self and other to
  1617. # Decimal integers (i.e. force their exponents to be >= 0)
  1618. modulo = abs(int(modulo))
  1619. base = _WorkRep(self.to_integral_value())
  1620. exponent = _WorkRep(other.to_integral_value())
  1621. # compute result using integer pow()
  1622. base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
  1623. for i in xrange(exponent.exp):
  1624. base = pow(base, 10, modulo)
  1625. base = pow(base, exponent.int, modulo)
  1626. return _dec_from_triple(sign, str(base), 0)
  1627. def _power_exact(self, other, p):
  1628. """Attempt to compute self**other exactly.
  1629. Given Decimals self and other and an integer p, attempt to
  1630. compute an exact result for the power self**other, with p
  1631. digits of precision. Return None if self**other is not
  1632. exactly representable in p digits.
  1633. Assumes that elimination of special cases has already been
  1634. performed: self and other must both be nonspecial; self must
  1635. be positive and not numerically equal to 1; other must be
  1636. nonzero. For efficiency, other._exp should not be too large,
  1637. so that 10**abs(other._exp) is a feasible calculation."""
  1638. # In the comments below, we write x for the value of self and
  1639. # y for the value of other. Write x = xc*10**xe and y =
  1640. # yc*10**ye.
  1641. # The main purpose of this method is to identify the *failure*
  1642. # of x**y to be exactly representable with as little effort as
  1643. # possible. So we look for cheap and easy tests that
  1644. # eliminate the possibility of x**y being exact. Only if all
  1645. # these tests are passed do we go on to actually compute x**y.
  1646. # Here's the main idea. First normalize both x and y. We
  1647. # express y as a rational m/n, with m and n relatively prime
  1648. # and n>0. Then for x**y to be exactly representable (at
  1649. # *any* precision), xc must be the nth power of a positive
  1650. # integer and xe must be divisible by n. If m is negative
  1651. # then additionally xc must be a power of either 2 or 5, hence
  1652. # a power of 2**n or 5**n.
  1653. #
  1654. # There's a limit to how small |y| can be: if y=m/n as above
  1655. # then:
  1656. #
  1657. # (1) if xc != 1 then for the result to be representable we
  1658. # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
  1659. # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
  1660. # 2**(1/|y|), hence xc**|y| < 2 and the result is not
  1661. # representable.
  1662. #
  1663. # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
  1664. # |y| < 1/|xe| then the result is not representable.
  1665. #
  1666. # Note that since x is not equal to 1, at least one of (1) and
  1667. # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
  1668. # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
  1669. #
  1670. # There's also a limit to how large y can be, at least if it's
  1671. # positive: the normalized result will have coefficient xc**y,
  1672. # so if it's representable then xc**y < 10**p, and y <
  1673. # p/log10(xc). Hence if y*log10(xc) >= p then the result is
  1674. # not exactly representable.
  1675. # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
  1676. # so |y| < 1/xe and the result is not representable.
  1677. # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
  1678. # < 1/nbits(xc).
  1679. x = _WorkRep(self)
  1680. xc, xe = x.int, x.exp
  1681. while xc % 10 == 0:
  1682. xc //= 10
  1683. xe += 1
  1684. y = _WorkRep(other)
  1685. yc, ye = y.int, y.exp
  1686. while yc % 10 == 0:
  1687. yc //= 10
  1688. ye += 1
  1689. # case where xc == 1: result is 10**(xe*y), with xe*y
  1690. # required to be an integer
  1691. if xc == 1:
  1692. xe *= yc
  1693. # result is now 10**(xe * 10**ye); xe * 10**ye must be integral
  1694. while xe % 10 == 0:
  1695. xe //= 10
  1696. ye += 1
  1697. if ye < 0:
  1698. return None
  1699. exponent = xe * 10**ye
  1700. if y.sign == 1:
  1701. exponent = -exponent
  1702. # if other is a nonnegative integer, use ideal exponent
  1703. if other._isinteger() and other._sign == 0:
  1704. ideal_exponent = self._exp*int(other)
  1705. zeros = min(exponent-ideal_exponent, p-1)
  1706. else:
  1707. zeros = 0
  1708. return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
  1709. # case where y is negative: xc must be either a power
  1710. # of 2 or a power of 5.
  1711. if y.sign == 1:
  1712. last_digit = xc % 10
  1713. if last_digit in (2,4,6,8):
  1714. # quick test for power of 2
  1715. if xc & -xc != xc:
  1716. return None
  1717. # now xc is a power of 2; e is its exponent
  1718. e = _nbits(xc)-1
  1719. # find e*y and xe*y; both must be integers
  1720. if ye >= 0:
  1721. y_as_int = yc*10**ye
  1722. e = e*y_as_int
  1723. xe = xe*y_as_int
  1724. else:
  1725. ten_pow = 10**-ye
  1726. e, remainder = divmod(e*yc, ten_pow)
  1727. if remainder:
  1728. return None
  1729. xe, remainder = divmod(xe*yc, ten_pow)
  1730. if remainder:
  1731. return None
  1732. if e*65 >= p*93: # 93/65 > log(10)/log(5)
  1733. return None
  1734. xc = 5**e
  1735. elif last_digit == 5:
  1736. # e >= log_5(xc) if xc is a power of 5; we have
  1737. # equality all the way up to xc=5**2658
  1738. e = _nbits(xc)*28//65
  1739. xc, remainder = divmod(5**e, xc)
  1740. if remainder:
  1741. return None
  1742. while xc % 5 == 0:
  1743. xc //= 5
  1744. e -= 1
  1745. if ye >= 0:
  1746. y_as_integer = yc*10**ye
  1747. e = e*y_as_integer
  1748. xe = xe*y_as_integer
  1749. else:
  1750. ten_pow = 10**-ye
  1751. e, remainder = divmod(e*yc, ten_pow)
  1752. if remainder:
  1753. return None
  1754. xe, remainder = divmod(xe*yc, ten_pow)
  1755. if remainder:
  1756. return None
  1757. if e*3 >= p*10: # 10/3 > log(10)/log(2)
  1758. return None
  1759. xc = 2**e
  1760. else:
  1761. return None
  1762. if xc >= 10**p:
  1763. return None
  1764. xe = -e-xe
  1765. return _dec_from_triple(0, str(xc), xe)
  1766. # now y is positive; find m and n such that y = m/n
  1767. if ye >= 0:
  1768. m, n = yc*10**ye, 1
  1769. else:
  1770. if xe != 0 and len(str(abs(yc*xe))) <= -ye:
  1771. return None
  1772. xc_bits = _nbits(xc)
  1773. if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
  1774. return None
  1775. m, n = yc, 10**(-ye)
  1776. while m % 2 == n % 2 == 0:
  1777. m //= 2
  1778. n //= 2
  1779. while m % 5 == n % 5 == 0:
  1780. m //= 5
  1781. n //= 5
  1782. # compute nth root of xc*10**xe
  1783. if n > 1:
  1784. # if 1 < xc < 2**n then xc isn't an nth power
  1785. if xc != 1 and xc_bits <= n:
  1786. return None
  1787. xe, rem = divmod(xe, n)
  1788. if rem != 0:
  1789. return None
  1790. # compute nth root of xc using Newton's method
  1791. a = 1L << -(-_nbits(xc)//n) # initial estimate
  1792. while True:
  1793. q, r = divmod(xc, a**(n-1))
  1794. if a <= q:
  1795. break
  1796. else:
  1797. a = (a*(n-1) + q)//n
  1798. if not (a == q and r == 0):
  1799. return None
  1800. xc = a
  1801. # now xc*10**xe is the nth root of the original xc*10**xe
  1802. # compute mth power of xc*10**xe
  1803. # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
  1804. # 10**p and the result is not representable.
  1805. if xc > 1 and m > p*100//_log10_lb(xc):
  1806. return None
  1807. xc = xc**m
  1808. xe *= m
  1809. if xc > 10**p:
  1810. return None
  1811. # by this point the result *is* exactly representable
  1812. # adjust the exponent to get as close as possible to the ideal
  1813. # exponent, if necessary
  1814. str_xc = str(xc)
  1815. if other._isinteger() and other._sign == 0:
  1816. ideal_exponent = self._exp*int(other)
  1817. zeros = min(xe-ideal_exponent, p-len(str_xc))
  1818. else:
  1819. zeros = 0
  1820. return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
  1821. def __pow__(self, other, modulo=None, context=None):
  1822. """Return self ** other [ % modulo].
  1823. With two arguments, compute self**other.
  1824. With three arguments, compute (self**other) % modulo. For the
  1825. three argument form, the following restrictions on the
  1826. arguments hold:
  1827. - all three arguments must be integral
  1828. - other must be nonnegative
  1829. - either self or other (or both) must be nonzero
  1830. - modulo must be nonzero and must have at most p digits,
  1831. where p is the context precision.
  1832. If any of these restrictions is violated the InvalidOperation
  1833. flag is raised.
  1834. The result of pow(self, other, modulo) is identical to the
  1835. result that would be obtained by computing (self**other) %
  1836. modulo with unbounded precision, but is computed more
  1837. efficiently. It is always exact.
  1838. """
  1839. if modulo is not None:
  1840. return self._power_modulo(other, modulo, context)
  1841. other = _convert_other(other)
  1842. if other is NotImplemented:
  1843. return other
  1844. if context is None:
  1845. context = getcontext()
  1846. # either argument is a NaN => result is NaN
  1847. ans = self._check_nans(other, context)
  1848. if ans:
  1849. return ans
  1850. # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
  1851. if not other:
  1852. if not self:
  1853. return context._raise_error(InvalidOperation, '0 ** 0')
  1854. else:
  1855. return _One
  1856. # result has sign 1 iff self._sign is 1 and other is an odd integer
  1857. result_sign = 0
  1858. if self._sign == 1:
  1859. if other._isinteger():
  1860. if not other._iseven():
  1861. result_sign = 1
  1862. else:
  1863. # -ve**noninteger = NaN
  1864. # (-0)**noninteger = 0**noninteger
  1865. if self:
  1866. return context._raise_error(InvalidOperation,
  1867. 'x ** y with x negative and y not an integer')
  1868. # negate self, without doing any unwanted rounding
  1869. self = self.copy_negate()
  1870. # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
  1871. if not self:
  1872. if other._sign == 0:
  1873. return _dec_from_triple(result_sign, '0', 0)
  1874. else:
  1875. return _SignedInfinity[result_sign]
  1876. # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
  1877. if self._isinfinity():
  1878. if other._sign == 0:
  1879. return _SignedInfinity[result_sign]
  1880. else:
  1881. return _dec_from_triple(result_sign, '0', 0)
  1882. # 1**other = 1, but the choice of exponent and the flags
  1883. # depend on the exponent of self, and on whether other is a
  1884. # positive integer, a negative integer, or neither
  1885. if self == _One:
  1886. if other._isinteger():
  1887. # exp = max(self._exp*max(int(other), 0),
  1888. # 1-context.prec) but evaluating int(other) directly
  1889. # is dangerous until we know other is small (other
  1890. # could be 1e999999999)
  1891. if other._sign == 1:
  1892. multiplier = 0
  1893. elif other > context.prec:
  1894. multiplier = context.prec
  1895. else:
  1896. multiplier = int(other)
  1897. exp = self._exp * multiplier
  1898. if exp < 1-context.prec:
  1899. exp = 1-context.prec
  1900. context._raise_error(Rounded)
  1901. else:
  1902. context._raise_error(Inexact)
  1903. context._raise_error(Rounded)
  1904. exp = 1-context.prec
  1905. return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
  1906. # compute adjusted exponent of self
  1907. self_adj = self.adjusted()
  1908. # self ** infinity is infinity if self > 1, 0 if self < 1
  1909. # self ** -infinity is infinity if self < 1, 0 if self > 1
  1910. if other._isinfinity():
  1911. if (other._sign == 0) == (self_adj < 0):
  1912. return _dec_from_triple(result_sign, '0', 0)
  1913. else:
  1914. return _SignedInfinity[result_sign]
  1915. # from here on, the result always goes through the call
  1916. # to _fix at the end of this function.
  1917. ans = None
  1918. exact = False
  1919. # crude test to catch cases of extreme overflow/underflow. If
  1920. # log10(self)*other >= 10**bound and bound >= len(str(Emax))
  1921. # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
  1922. # self**other >= 10**(Emax+1), so overflow occurs. The test
  1923. # for underflow is similar.
  1924. bound = self._log10_exp_bound() + other.adjusted()
  1925. if (self_adj >= 0) == (other._sign == 0):
  1926. # self > 1 and other +ve, or self < 1 and other -ve
  1927. # possibility of overflow
  1928. if bound >= len(str(context.Emax)):
  1929. ans = _dec_from_triple(result_sign, '1', context.Emax+1)
  1930. else:
  1931. # self > 1 and other -ve, or self < 1 and other +ve
  1932. # possibility of underflow to 0
  1933. Etiny = context.Etiny()
  1934. if bound >= len(str(-Etiny)):
  1935. ans = _dec_from_triple(result_sign, '1', Etiny-1)
  1936. # try for an exact result with precision +1
  1937. if ans is None:
  1938. ans = self._power_exact(other, context.prec + 1)
  1939. if ans is not None:
  1940. if result_sign == 1:
  1941. ans = _dec_from_triple(1, ans._int, ans._exp)
  1942. exact = True
  1943. # usual case: inexact result, x**y computed directly as exp(y*log(x))
  1944. if ans is None:
  1945. p = context.prec
  1946. x = _WorkRep(self)
  1947. xc, xe = x.int, x.exp
  1948. y = _WorkRep(other)
  1949. yc, ye = y.int, y.exp
  1950. if y.sign == 1:
  1951. yc = -yc
  1952. # compute correctly rounded result: start with precision +3,
  1953. # then increase precision until result is unambiguously roundable
  1954. extra = 3
  1955. while True:
  1956. coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
  1957. if coeff % (5*10**(len(str(coeff))-p-1)):
  1958. break
  1959. extra += 3
  1960. ans = _dec_from_triple(result_sign, str(coeff), exp)
  1961. # unlike exp, ln and log10, the power function respects the
  1962. # rounding mode; no need to switch to ROUND_HALF_EVEN here
  1963. # There's a difficulty here when 'other' is not an integer and
  1964. # the result is exact. In this case, the specification
  1965. # requires that the Inexact flag be raised (in spite of
  1966. # exactness), but since the result is exact _fix won't do this
  1967. # for us. (Correspondingly, the Underflow signal should also
  1968. # be raised for subnormal results.) We can't directly raise
  1969. # these signals either before or after calling _fix, since
  1970. # that would violate the precedence for signals. So we wrap
  1971. # the ._fix call in a temporary context, and reraise
  1972. # afterwards.
  1973. if exact and not other._isinteger():
  1974. # pad with zeros up to length context.prec+1 if necessary; this
  1975. # ensures that the Rounded signal will be raised.
  1976. if len(ans._int) <= context.prec:
  1977. expdiff = context.prec + 1 - len(ans._int)
  1978. ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
  1979. ans._exp-expdiff)
  1980. # create a copy of the current context, with cleared flags/traps
  1981. newcontext = context.copy()
  1982. newcontext.clear_flags()
  1983. for exception in _signals:
  1984. newcontext.traps[exception] = 0
  1985. # round in the new context
  1986. ans = ans._fix(newcontext)
  1987. # raise Inexact, and if necessary, Underflow
  1988. newcontext._raise_error(Inexact)
  1989. if newcontext.flags[Subnormal]:
  1990. newcontext._raise_error(Underflow)
  1991. # propagate signals to the original context; _fix could
  1992. # have raised any of Overflow, Underflow, Subnormal,
  1993. # Inexact, Rounded, Clamped. Overflow needs the correct
  1994. # arguments. Note that the order of the exceptions is
  1995. # important here.
  1996. if newcontext.flags[Overflow]:
  1997. context._raise_error(Overflow, 'above Emax', ans._sign)
  1998. for exception in Underflow, Subnormal, Inexact, Rounded, Clamped:
  1999. if newcontext.flags[exception]:
  2000. context._raise_error(exception)
  2001. else:
  2002. ans = ans._fix(context)
  2003. return ans
  2004. def __rpow__(self, other, context=None):
  2005. """Swaps self/other and returns __pow__."""
  2006. other = _convert_other(other)
  2007. if other is NotImplemented:
  2008. return other
  2009. return other.__pow__(self, context=context)
  2010. def normalize(self, context=None):
  2011. """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
  2012. if context is None:
  2013. context = getcontext()
  2014. if self._is_special:
  2015. ans = self._check_nans(context=context)
  2016. if ans:
  2017. return ans
  2018. dup = self._fix(context)
  2019. if dup._isinfinity():
  2020. return dup
  2021. if not dup:
  2022. return _dec_from_triple(dup._sign, '0', 0)
  2023. exp_max = [context.Emax, context.Etop()][context._clamp]
  2024. end = len(dup._int)
  2025. exp = dup._exp
  2026. while dup._int[end-1] == '0' and exp < exp_max:
  2027. exp += 1
  2028. end -= 1
  2029. return _dec_from_triple(dup._sign, dup._int[:end], exp)
  2030. def quantize(self, exp, rounding=None, context=None, watchexp=True):
  2031. """Quantize self so its exponent is the same as that of exp.
  2032. Similar to self._rescale(exp._exp) but with error checking.
  2033. """
  2034. exp = _convert_other(exp, raiseit=True)
  2035. if context is None:
  2036. context = getcontext()
  2037. if rounding is None:
  2038. rounding = context.rounding
  2039. if self._is_special or exp._is_special:
  2040. ans = self._check_nans(exp, context)
  2041. if ans:
  2042. return ans
  2043. if exp._isinfinity() or self._isinfinity():
  2044. if exp._isinfinity() and self._isinfinity():
  2045. return Decimal(self) # if both are inf, it is OK
  2046. return context._raise_error(InvalidOperation,
  2047. 'quantize with one INF')
  2048. # if we're not watching exponents, do a simple rescale
  2049. if not watchexp:
  2050. ans = self._rescale(exp._exp, rounding)
  2051. # raise Inexact and Rounded where appropriate
  2052. if ans._exp > self._exp:
  2053. context._raise_error(Rounded)
  2054. if ans != self:
  2055. context._raise_error(Inexact)
  2056. return ans
  2057. # exp._exp should be between Etiny and Emax
  2058. if not (context.Etiny() <= exp._exp <= context.Emax):
  2059. return context._raise_error(InvalidOperation,
  2060. 'target exponent out of bounds in quantize')
  2061. if not self:
  2062. ans = _dec_from_triple(self._sign, '0', exp._exp)
  2063. return ans._fix(context)
  2064. self_adjusted = self.adjusted()
  2065. if self_adjusted > context.Emax:
  2066. return context._raise_error(InvalidOperation,
  2067. 'exponent of quantize result too large for current context')
  2068. if self_adjusted - exp._exp + 1 > context.prec:
  2069. return context._raise_error(InvalidOperation,
  2070. 'quantize result has too many digits for current context')
  2071. ans = self._rescale(exp._exp, rounding)
  2072. if ans.adjusted() > context.Emax:
  2073. return context._raise_error(InvalidOperation,
  2074. 'exponent of quantize result too large for current context')
  2075. if len(ans._int) > context.prec:
  2076. return context._raise_error(InvalidOperation,
  2077. 'quantize result has too many digits for current context')
  2078. # raise appropriate flags
  2079. if ans and ans.adjusted() < context.Emin:
  2080. context._raise_error(Subnormal)
  2081. if ans._exp > self._exp:
  2082. if ans != self:
  2083. context._raise_error(Inexact)
  2084. context._raise_error(Rounded)
  2085. # call to fix takes care of any necessary folddown, and
  2086. # signals Clamped if necessary
  2087. ans = ans._fix(context)
  2088. return ans
  2089. def same_quantum(self, other):
  2090. """Return True if self and other have the same exponent; otherwise
  2091. return False.
  2092. If either operand is a special value, the following rules are used:
  2093. * return True if both operands are infinities
  2094. * return True if both operands are NaNs
  2095. * otherwise, return False.
  2096. """
  2097. other = _convert_other(other, raiseit=True)
  2098. if self._is_special or other._is_special:
  2099. return (self.is_nan() and other.is_nan() or
  2100. self.is_infinite() and other.is_infinite())
  2101. return self._exp == other._exp
  2102. def _rescale(self, exp, rounding):
  2103. """Rescale self so that the exponent is exp, either by padding with zeros
  2104. or by truncating digits, using the given rounding mode.
  2105. Specials are returned without change. This operation is
  2106. quiet: it raises no flags, and uses no information from the
  2107. context.
  2108. exp = exp to scale to (an integer)
  2109. rounding = rounding mode
  2110. """
  2111. if self._is_special:
  2112. return Decimal(self)
  2113. if not self:
  2114. return _dec_from_triple(self._sign, '0', exp)
  2115. if self._exp >= exp:
  2116. # pad answer with zeros if necessary
  2117. return _dec_from_triple(self._sign,
  2118. self._int + '0'*(self._exp - exp), exp)
  2119. # too many digits; round and lose data. If self.adjusted() <
  2120. # exp-1, replace self by 10**(exp-1) before rounding
  2121. digits = len(self._int) + self._exp - exp
  2122. if digits < 0:
  2123. self = _dec_from_triple(self._sign, '1', exp-1)
  2124. digits = 0
  2125. this_function = self._pick_rounding_function[rounding]
  2126. changed = this_function(self, digits)
  2127. coeff = self._int[:digits] or '0'
  2128. if changed == 1:
  2129. coeff = str(int(coeff)+1)
  2130. return _dec_from_triple(self._sign, coeff, exp)
  2131. def _round(self, places, rounding):
  2132. """Round a nonzero, nonspecial Decimal to a fixed number of
  2133. significant figures, using the given rounding mode.
  2134. Infinities, NaNs and zeros are returned unaltered.
  2135. This operation is quiet: it raises no flags, and uses no
  2136. information from the context.
  2137. """
  2138. if places <= 0:
  2139. raise ValueError("argument should be at least 1 in _round")
  2140. if self._is_special or not self:
  2141. return Decimal(self)
  2142. ans = self._rescale(self.adjusted()+1-places, rounding)
  2143. # it can happen that the rescale alters the adjusted exponent;
  2144. # for example when rounding 99.97 to 3 significant figures.
  2145. # When this happens we end up with an extra 0 at the end of
  2146. # the number; a second rescale fixes this.
  2147. if ans.adjusted() != self.adjusted():
  2148. ans = ans._rescale(ans.adjusted()+1-places, rounding)
  2149. return ans
  2150. def to_integral_exact(self, rounding=None, context=None):
  2151. """Rounds to a nearby integer.
  2152. If no rounding mode is specified, take the rounding mode from
  2153. the context. This method raises the Rounded and Inexact flags
  2154. when appropriate.
  2155. See also: to_integral_value, which does exactly the same as
  2156. this method except that it doesn't raise Inexact or Rounded.
  2157. """
  2158. if self._is_special:
  2159. ans = self._check_nans(context=context)
  2160. if ans:
  2161. return ans
  2162. return Decimal(self)
  2163. if self._exp >= 0:
  2164. return Decimal(self)
  2165. if not self:
  2166. return _dec_from_triple(self._sign, '0', 0)
  2167. if context is None:
  2168. context = getcontext()
  2169. if rounding is None:
  2170. rounding = context.rounding
  2171. ans = self._rescale(0, rounding)
  2172. if ans != self:
  2173. context._raise_error(Inexact)
  2174. context._raise_error(Rounded)
  2175. return ans
  2176. def to_integral_value(self, rounding=None, context=None):
  2177. """Rounds to the nearest integer, without raising inexact, rounded."""
  2178. if context is None:
  2179. context = getcontext()
  2180. if rounding is None:
  2181. rounding = context.rounding
  2182. if self._is_special:
  2183. ans = self._check_nans(context=context)
  2184. if ans:
  2185. return ans
  2186. return Decimal(self)
  2187. if self._exp >= 0:
  2188. return Decimal(self)
  2189. else:
  2190. return self._rescale(0, rounding)
  2191. # the method name changed, but we provide also the old one, for compatibility
  2192. to_integral = to_integral_value
  2193. def sqrt(self, context=None):
  2194. """Return the square root of self."""
  2195. if context is None:
  2196. context = getcontext()
  2197. if self._is_special:
  2198. ans = self._check_nans(context=context)
  2199. if ans:
  2200. return ans
  2201. if self._isinfinity() and self._sign == 0:
  2202. return Decimal(self)
  2203. if not self:
  2204. # exponent = self._exp // 2. sqrt(-0) = -0
  2205. ans = _dec_from_triple(self._sign, '0', self._exp // 2)
  2206. return ans._fix(context)
  2207. if self._sign == 1:
  2208. return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
  2209. # At this point self represents a positive number. Let p be
  2210. # the desired precision and express self in the form c*100**e
  2211. # with c a positive real number and e an integer, c and e
  2212. # being chosen so that 100**(p-1) <= c < 100**p. Then the
  2213. # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
  2214. # <= sqrt(c) < 10**p, so the closest representable Decimal at
  2215. # precision p is n*10**e where n = round_half_even(sqrt(c)),
  2216. # the closest integer to sqrt(c) with the even integer chosen
  2217. # in the case of a tie.
  2218. #
  2219. # To ensure correct rounding in all cases, we use the
  2220. # following trick: we compute the square root to an extra
  2221. # place (precision p+1 instead of precision p), rounding down.
  2222. # Then, if the result is inexact and its last digit is 0 or 5,
  2223. # we increase the last digit to 1 or 6 respectively; if it's
  2224. # exact we leave the last digit alone. Now the final round to
  2225. # p places (or fewer in the case of underflow) will round
  2226. # correctly and raise the appropriate flags.
  2227. # use an extra digit of precision
  2228. prec = context.prec+1
  2229. # write argument in the form c*100**e where e = self._exp//2
  2230. # is the 'ideal' exponent, to be used if the square root is
  2231. # exactly representable. l is the number of 'digits' of c in
  2232. # base 100, so that 100**(l-1) <= c < 100**l.
  2233. op = _WorkRep(self)
  2234. e = op.exp >> 1
  2235. if op.exp & 1:
  2236. c = op.int * 10
  2237. l = (len(self._int) >> 1) + 1
  2238. else:
  2239. c = op.int
  2240. l = len(self._int)+1 >> 1
  2241. # rescale so that c has exactly prec base 100 'digits'
  2242. shift = prec-l
  2243. if shift >= 0:
  2244. c *= 100**shift
  2245. exact = True
  2246. else:
  2247. c, remainder = divmod(c, 100**-shift)
  2248. exact = not remainder
  2249. e -= shift
  2250. # find n = floor(sqrt(c)) using Newton's method
  2251. n = 10**prec
  2252. while True:
  2253. q = c//n
  2254. if n <= q:
  2255. break
  2256. else:
  2257. n = n + q >> 1
  2258. exact = exact and n*n == c
  2259. if exact:
  2260. # result is exact; rescale to use ideal exponent e
  2261. if shift >= 0:
  2262. # assert n % 10**shift == 0
  2263. n //= 10**shift
  2264. else:
  2265. n *= 10**-shift
  2266. e += shift
  2267. else:
  2268. # result is not exact; fix last digit as described above
  2269. if n % 5 == 0:
  2270. n += 1
  2271. ans = _dec_from_triple(0, str(n), e)
  2272. # round, and fit to current context
  2273. context = context._shallow_copy()
  2274. rounding = context._set_rounding(ROUND_HALF_EVEN)
  2275. ans = ans._fix(context)
  2276. context.rounding = rounding
  2277. return ans
  2278. def max(self, other, context=None):
  2279. """Returns the larger value.
  2280. Like max(self, other) except if one is not a number, returns
  2281. NaN (and signals if one is sNaN). Also rounds.
  2282. """
  2283. other = _convert_other(other, raiseit=True)
  2284. if context is None:
  2285. context = getcontext()
  2286. if self._is_special or other._is_special:
  2287. # If one operand is a quiet NaN and the other is number, then the
  2288. # number is always returned
  2289. sn = self._isnan()
  2290. on = other._isnan()
  2291. if sn or on:
  2292. if on == 1 and sn == 0:
  2293. return self._fix(context)
  2294. if sn == 1 and on == 0:
  2295. return other._fix(context)
  2296. return self._check_nans(other, context)
  2297. c = self._cmp(other)
  2298. if c == 0:
  2299. # If both operands are finite and equal in numerical value
  2300. # then an ordering is applied:
  2301. #
  2302. # If the signs differ then max returns the operand with the
  2303. # positive sign and min returns the operand with the negative sign
  2304. #
  2305. # If the signs are the same then the exponent is used to select
  2306. # the result. This is exactly the ordering used in compare_total.
  2307. c = self.compare_total(other)
  2308. if c == -1:
  2309. ans = other
  2310. else:
  2311. ans = self
  2312. return ans._fix(context)
  2313. def min(self, other, context=None):
  2314. """Returns the smaller value.
  2315. Like min(self, other) except if one is not a number, returns
  2316. NaN (and signals if one is sNaN). Also rounds.
  2317. """
  2318. other = _convert_other(other, raiseit=True)
  2319. if context is None:
  2320. context = getcontext()
  2321. if self._is_special or other._is_special:
  2322. # If one operand is a quiet NaN and the other is number, then the
  2323. # number is always returned
  2324. sn = self._isnan()
  2325. on = other._isnan()
  2326. if sn or on:
  2327. if on == 1 and sn == 0:
  2328. return self._fix(context)
  2329. if sn == 1 and on == 0:
  2330. return other._fix(context)
  2331. return self._check_nans(other, context)
  2332. c = self._cmp(other)
  2333. if c == 0:
  2334. c = self.compare_total(other)
  2335. if c == -1:
  2336. ans = self
  2337. else:
  2338. ans = other
  2339. return ans._fix(context)
  2340. def _isinteger(self):
  2341. """Returns whether self is an integer"""
  2342. if self._is_special:
  2343. return False
  2344. if self._exp >= 0:
  2345. return True
  2346. rest = self._int[self._exp:]
  2347. return rest == '0'*len(rest)
  2348. def _iseven(self):
  2349. """Returns True if self is even. Assumes self is an integer."""
  2350. if not self or self._exp > 0:
  2351. return True
  2352. return self._int[-1+self._exp] in '02468'
  2353. def adjusted(self):
  2354. """Return the adjusted exponent of self"""
  2355. try:
  2356. return self._exp + len(self._int) - 1
  2357. # If NaN or Infinity, self._exp is string
  2358. except TypeError:
  2359. return 0
  2360. def canonical(self, context=None):
  2361. """Returns the same Decimal object.
  2362. As we do not have different encodings for the same number, the
  2363. received object already is in its canonical form.
  2364. """
  2365. return self
  2366. def compare_signal(self, other, context=None):
  2367. """Compares self to the other operand numerically.
  2368. It's pretty much like compare(), but all NaNs signal, with signaling
  2369. NaNs taking precedence over quiet NaNs.
  2370. """
  2371. other = _convert_other(other, raiseit = True)
  2372. ans = self._compare_check_nans(other, context)
  2373. if ans:
  2374. return ans
  2375. return self.compare(other, context=context)
  2376. def compare_total(self, other):
  2377. """Compares self to other using the abstract representations.
  2378. This is not like the standard compare, which use their numerical
  2379. value. Note that a total ordering is defined for all possible abstract
  2380. representations.
  2381. """
  2382. other = _convert_other(other, raiseit=True)
  2383. # if one is negative and the other is positive, it's easy
  2384. if self._sign and not other._sign:
  2385. return _NegativeOne
  2386. if not self._sign and other._sign:
  2387. return _One
  2388. sign = self._sign
  2389. # let's handle both NaN types
  2390. self_nan = self._isnan()
  2391. other_nan = other._isnan()
  2392. if self_nan or other_nan:
  2393. if self_nan == other_nan:
  2394. # compare payloads as though they're integers
  2395. self_key = len(self._int), self._int
  2396. other_key = len(other._int), other._int
  2397. if self_key < other_key:
  2398. if sign:
  2399. return _One
  2400. else:
  2401. return _NegativeOne
  2402. if self_key > other_key:
  2403. if sign:
  2404. return _NegativeOne
  2405. else:
  2406. return _One
  2407. return _Zero
  2408. if sign:
  2409. if self_nan == 1:
  2410. return _NegativeOne
  2411. if other_nan == 1:
  2412. return _One
  2413. if self_nan == 2:
  2414. return _NegativeOne
  2415. if other_nan == 2:
  2416. return _One
  2417. else:
  2418. if self_nan == 1:
  2419. return _One
  2420. if other_nan == 1:
  2421. return _NegativeOne
  2422. if self_nan == 2:
  2423. return _One
  2424. if other_nan == 2:
  2425. return _NegativeOne
  2426. if self < other:
  2427. return _NegativeOne
  2428. if self > other:
  2429. return _One
  2430. if self._exp < other._exp:
  2431. if sign:
  2432. return _One
  2433. else:
  2434. return _NegativeOne
  2435. if self._exp > other._exp:
  2436. if sign:
  2437. return _NegativeOne
  2438. else:
  2439. return _One
  2440. return _Zero
  2441. def compare_total_mag(self, other):
  2442. """Compares self to other using abstract repr., ignoring sign.
  2443. Like compare_total, but with operand's sign ignored and assumed to be 0.
  2444. """
  2445. other = _convert_other(other, raiseit=True)
  2446. s = self.copy_abs()
  2447. o = other.copy_abs()
  2448. return s.compare_total(o)
  2449. def copy_abs(self):
  2450. """Returns a copy with the sign set to 0. """
  2451. return _dec_from_triple(0, self._int, self._exp, self._is_special)
  2452. def copy_negate(self):
  2453. """Returns a copy with the sign inverted."""
  2454. if self._sign:
  2455. return _dec_from_triple(0, self._int, self._exp, self._is_special)
  2456. else:
  2457. return _dec_from_triple(1, self._int, self._exp, self._is_special)
  2458. def copy_sign(self, other):
  2459. """Returns self with the sign of other."""
  2460. other = _convert_other(other, raiseit=True)
  2461. return _dec_from_triple(other._sign, self._int,
  2462. self._exp, self._is_special)
  2463. def exp(self, context=None):
  2464. """Returns e ** self."""
  2465. if context is None:
  2466. context = getcontext()
  2467. # exp(NaN) = NaN
  2468. ans = self._check_nans(context=context)
  2469. if ans:
  2470. return ans
  2471. # exp(-Infinity) = 0
  2472. if self._isinfinity() == -1:
  2473. return _Zero
  2474. # exp(0) = 1
  2475. if not self:
  2476. return _One
  2477. # exp(Infinity) = Infinity
  2478. if self._isinfinity() == 1:
  2479. return Decimal(self)
  2480. # the result is now guaranteed to be inexact (the true
  2481. # mathematical result is transcendental). There's no need to
  2482. # raise Rounded and Inexact here---they'll always be raised as
  2483. # a result of the call to _fix.
  2484. p = context.prec
  2485. adj = self.adjusted()
  2486. # we only need to do any computation for quite a small range
  2487. # of adjusted exponents---for example, -29 <= adj <= 10 for
  2488. # the default context. For smaller exponent the result is
  2489. # indistinguishable from 1 at the given precision, while for
  2490. # larger exponent the result either overflows or underflows.
  2491. if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
  2492. # overflow
  2493. ans = _dec_from_triple(0, '1', context.Emax+1)
  2494. elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
  2495. # underflow to 0
  2496. ans = _dec_from_triple(0, '1', context.Etiny()-1)
  2497. elif self._sign == 0 and adj < -p:
  2498. # p+1 digits; final round will raise correct flags
  2499. ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
  2500. elif self._sign == 1 and adj < -p-1:
  2501. # p+1 digits; final round will raise correct flags
  2502. ans = _dec_from_triple(0, '9'*(p+1), -p-1)
  2503. # general case
  2504. else:
  2505. op = _WorkRep(self)
  2506. c, e = op.int, op.exp
  2507. if op.sign == 1:
  2508. c = -c
  2509. # compute correctly rounded result: increase precision by
  2510. # 3 digits at a time until we get an unambiguously
  2511. # roundable result
  2512. extra = 3
  2513. while True:
  2514. coeff, exp = _dexp(c, e, p+extra)
  2515. if coeff % (5*10**(len(str(coeff))-p-1)):
  2516. break
  2517. extra += 3
  2518. ans = _dec_from_triple(0, str(coeff), exp)
  2519. # at this stage, ans should round correctly with *any*
  2520. # rounding mode, not just with ROUND_HALF_EVEN
  2521. context = context._shallow_copy()
  2522. rounding = context._set_rounding(ROUND_HALF_EVEN)
  2523. ans = ans._fix(context)
  2524. context.rounding = rounding
  2525. return ans
  2526. def is_canonical(self):
  2527. """Return True if self is canonical; otherwise return False.
  2528. Currently, the encoding of a Decimal instance is always
  2529. canonical, so this method returns True for any Decimal.
  2530. """
  2531. return True
  2532. def is_finite(self):
  2533. """Return True if self is finite; otherwise return False.
  2534. A Decimal instance is considered finite if it is neither
  2535. infinite nor a NaN.
  2536. """
  2537. return not self._is_special
  2538. def is_infinite(self):
  2539. """Return True if self is infinite; otherwise return False."""
  2540. return self._exp == 'F'
  2541. def is_nan(self):
  2542. """Return True if self is a qNaN or sNaN; otherwise return False."""
  2543. return self._exp in ('n', 'N')
  2544. def is_normal(self, context=None):
  2545. """Return True if self is a normal number; otherwise return False."""
  2546. if self._is_special or not self:
  2547. return False
  2548. if context is None:
  2549. context = getcontext()
  2550. return context.Emin <= self.adjusted()
  2551. def is_qnan(self):
  2552. """Return True if self is a quiet NaN; otherwise return False."""
  2553. return self._exp == 'n'
  2554. def is_signed(self):
  2555. """Return True if self is negative; otherwise return False."""
  2556. return self._sign == 1
  2557. def is_snan(self):
  2558. """Return True if self is a signaling NaN; otherwise return False."""
  2559. return self._exp == 'N'
  2560. def is_subnormal(self, context=None):
  2561. """Return True if self is subnormal; otherwise return False."""
  2562. if self._is_special or not self:
  2563. return False
  2564. if context is None:
  2565. context = getcontext()
  2566. return self.adjusted() < context.Emin
  2567. def is_zero(self):
  2568. """Return True if self is a zero; otherwise return False."""
  2569. return not self._is_special and self._int == '0'
  2570. def _ln_exp_bound(self):
  2571. """Compute a lower bound for the adjusted exponent of self.ln().
  2572. In other words, compute r such that self.ln() >= 10**r. Assumes
  2573. that self is finite and positive and that self != 1.
  2574. """
  2575. # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
  2576. adj = self._exp + len(self._int) - 1
  2577. if adj >= 1:
  2578. # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
  2579. return len(str(adj*23//10)) - 1
  2580. if adj <= -2:
  2581. # argument <= 0.1
  2582. return len(str((-1-adj)*23//10)) - 1
  2583. op = _WorkRep(self)
  2584. c, e = op.int, op.exp
  2585. if adj == 0:
  2586. # 1 < self < 10
  2587. num = str(c-10**-e)
  2588. den = str(c)
  2589. return len(num) - len(den) - (num < den)
  2590. # adj == -1, 0.1 <= self < 1
  2591. return e + len(str(10**-e - c)) - 1
  2592. def ln(self, context=None):
  2593. """Returns the natural (base e) logarithm of self."""
  2594. if context is None:
  2595. context = getcontext()
  2596. # ln(NaN) = NaN
  2597. ans = self._check_nans(context=context)
  2598. if ans:
  2599. return ans
  2600. # ln(0.0) == -Infinity
  2601. if not self:
  2602. return _NegativeInfinity
  2603. # ln(Infinity) = Infinity
  2604. if self._isinfinity() == 1:
  2605. return _Infinity
  2606. # ln(1.0) == 0.0
  2607. if self == _One:
  2608. return _Zero
  2609. # ln(negative) raises InvalidOperation
  2610. if self._sign == 1:
  2611. return context._raise_error(InvalidOperation,
  2612. 'ln of a negative value')
  2613. # result is irrational, so necessarily inexact
  2614. op = _WorkRep(self)
  2615. c, e = op.int, op.exp
  2616. p = context.prec
  2617. # correctly rounded result: repeatedly increase precision by 3
  2618. # until we get an unambiguously roundable result
  2619. places = p - self._ln_exp_bound() + 2 # at least p+3 places
  2620. while True:
  2621. coeff = _dlog(c, e, places)
  2622. # assert len(str(abs(coeff)))-p >= 1
  2623. if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
  2624. break
  2625. places += 3
  2626. ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
  2627. context = context._shallow_copy()
  2628. rounding = context._set_rounding(ROUND_HALF_EVEN)
  2629. ans = ans._fix(context)
  2630. context.rounding = rounding
  2631. return ans
  2632. def _log10_exp_bound(self):
  2633. """Compute a lower bound for the adjusted exponent of self.log10().
  2634. In other words, find r such that self.log10() >= 10**r.
  2635. Assumes that self is finite and positive and that self != 1.
  2636. """
  2637. # For x >= 10 or x < 0.1 we only need a bound on the integer
  2638. # part of log10(self), and this comes directly from the
  2639. # exponent of x. For 0.1 <= x <= 10 we use the inequalities
  2640. # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
  2641. # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
  2642. adj = self._exp + len(self._int) - 1
  2643. if adj >= 1:
  2644. # self >= 10
  2645. return len(str(adj))-1
  2646. if adj <= -2:
  2647. # self < 0.1
  2648. return len(str(-1-adj))-1
  2649. op = _WorkRep(self)
  2650. c, e = op.int, op.exp
  2651. if adj == 0:
  2652. # 1 < self < 10
  2653. num = str(c-10**-e)
  2654. den = str(231*c)
  2655. return len(num) - len(den) - (num < den) + 2
  2656. # adj == -1, 0.1 <= self < 1
  2657. num = str(10**-e-c)
  2658. return len(num) + e - (num < "231") - 1
  2659. def log10(self, context=None):
  2660. """Returns the base 10 logarithm of self."""
  2661. if context is None:
  2662. context = getcontext()
  2663. # log10(NaN) = NaN
  2664. ans = self._check_nans(context=context)
  2665. if ans:
  2666. return ans
  2667. # log10(0.0) == -Infinity
  2668. if not self:
  2669. return _NegativeInfinity
  2670. # log10(Infinity) = Infinity
  2671. if self._isinfinity() == 1:
  2672. return _Infinity
  2673. # log10(negative or -Infinity) raises InvalidOperation
  2674. if self._sign == 1:
  2675. return context._raise_error(InvalidOperation,
  2676. 'log10 of a negative value')
  2677. # log10(10**n) = n
  2678. if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
  2679. # answer may need rounding
  2680. ans = Decimal(self._exp + len(self._int) - 1)
  2681. else:
  2682. # result is irrational, so necessarily inexact
  2683. op = _WorkRep(self)
  2684. c, e = op.int, op.exp
  2685. p = context.prec
  2686. # correctly rounded result: repeatedly increase precision
  2687. # until result is unambiguously roundable
  2688. places = p-self._log10_exp_bound()+2
  2689. while True:
  2690. coeff = _dlog10(c, e, places)
  2691. # assert len(str(abs(coeff)))-p >= 1
  2692. if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
  2693. break
  2694. places += 3
  2695. ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
  2696. context = context._shallow_copy()
  2697. rounding = context._set_rounding(ROUND_HALF_EVEN)
  2698. ans = ans._fix(context)
  2699. context.rounding = rounding
  2700. return ans
  2701. def logb(self, context=None):
  2702. """ Returns the exponent of the magnitude of self's MSD.
  2703. The result is the integer which is the exponent of the magnitude
  2704. of the most significant digit of self (as though it were truncated
  2705. to a single digit while maintaining the value of that digit and
  2706. without limiting the resulting exponent).
  2707. """
  2708. # logb(NaN) = NaN
  2709. ans = self._check_nans(context=context)
  2710. if ans:
  2711. return ans
  2712. if context is None:
  2713. context = getcontext()
  2714. # logb(+/-Inf) = +Inf
  2715. if self._isinfinity():
  2716. return _Infinity
  2717. # logb(0) = -Inf, DivisionByZero
  2718. if not self:
  2719. return context._raise_error(DivisionByZero, 'logb(0)', 1)
  2720. # otherwise, simply return the adjusted exponent of self, as a
  2721. # Decimal. Note that no attempt is made to fit the result
  2722. # into the current context.
  2723. ans = Decimal(self.adjusted())
  2724. return ans._fix(context)
  2725. def _islogical(self):
  2726. """Return True if self is a logical operand.
  2727. For being logical, it must be a finite number with a sign of 0,
  2728. an exponent of 0, and a coefficient whose digits must all be
  2729. either 0 or 1.
  2730. """
  2731. if self._sign != 0 or self._exp != 0:
  2732. return False
  2733. for dig in self._int:
  2734. if dig not in '01':
  2735. return False
  2736. return True
  2737. def _fill_logical(self, context, opa, opb):
  2738. dif = context.prec - len(opa)
  2739. if dif > 0:
  2740. opa = '0'*dif + opa
  2741. elif dif < 0:
  2742. opa = opa[-context.prec:]
  2743. dif = context.prec - len(opb)
  2744. if dif > 0:
  2745. opb = '0'*dif + opb
  2746. elif dif < 0:
  2747. opb = opb[-context.prec:]
  2748. return opa, opb
  2749. def logical_and(self, other, context=None):
  2750. """Applies an 'and' operation between self and other's digits."""
  2751. if context is None:
  2752. context = getcontext()
  2753. other = _convert_other(other, raiseit=True)
  2754. if not self._islogical() or not other._islogical():
  2755. return context._raise_error(InvalidOperation)
  2756. # fill to context.prec
  2757. (opa, opb) = self._fill_logical(context, self._int, other._int)
  2758. # make the operation, and clean starting zeroes
  2759. result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
  2760. return _dec_from_triple(0, result.lstrip('0') or '0', 0)
  2761. def logical_invert(self, context=None):
  2762. """Invert all its digits."""
  2763. if context is None:
  2764. context = getcontext()
  2765. return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
  2766. context)
  2767. def logical_or(self, other, context=None):
  2768. """Applies an 'or' operation between self and other's digits."""
  2769. if context is None:
  2770. context = getcontext()
  2771. other = _convert_other(other, raiseit=True)
  2772. if not self._islogical() or not other._islogical():
  2773. return context._raise_error(InvalidOperation)
  2774. # fill to context.prec
  2775. (opa, opb) = self._fill_logical(context, self._int, other._int)
  2776. # make the operation, and clean starting zeroes
  2777. result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
  2778. return _dec_from_triple(0, result.lstrip('0') or '0', 0)
  2779. def logical_xor(self, other, context=None):
  2780. """Applies an 'xor' operation between self and other's digits."""
  2781. if context is None:
  2782. context = getcontext()
  2783. other = _convert_other(other, raiseit=True)
  2784. if not self._islogical() or not other._islogical():
  2785. return context._raise_error(InvalidOperation)
  2786. # fill to context.prec
  2787. (opa, opb) = self._fill_logical(context, self._int, other._int)
  2788. # make the operation, and clean starting zeroes
  2789. result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
  2790. return _dec_from_triple(0, result.lstrip('0') or '0', 0)
  2791. def max_mag(self, other, context=None):
  2792. """Compares the values numerically with their sign ignored."""
  2793. other = _convert_other(other, raiseit=True)
  2794. if context is None:
  2795. context = getcontext()
  2796. if self._is_special or other._is_special:
  2797. # If one operand is a quiet NaN and the other is number, then the
  2798. # number is always returned
  2799. sn = self._isnan()
  2800. on = other._isnan()
  2801. if sn or on:
  2802. if on == 1 and sn == 0:
  2803. return self._fix(context)
  2804. if sn == 1 and on == 0:
  2805. return other._fix(context)
  2806. return self._check_nans(other, context)
  2807. c = self.copy_abs()._cmp(other.copy_abs())
  2808. if c == 0:
  2809. c = self.compare_total(other)
  2810. if c == -1:
  2811. ans = other
  2812. else:
  2813. ans = self
  2814. return ans._fix(context)
  2815. def min_mag(self, other, context=None):
  2816. """Compares the values numerically with their sign ignored."""
  2817. other = _convert_other(other, raiseit=True)
  2818. if context is None:
  2819. context = getcontext()
  2820. if self._is_special or other._is_special:
  2821. # If one operand is a quiet NaN and the other is number, then the
  2822. # number is always returned
  2823. sn = self._isnan()
  2824. on = other._isnan()
  2825. if sn or on:
  2826. if on == 1 and sn == 0:
  2827. return self._fix(context)
  2828. if sn == 1 and on == 0:
  2829. return other._fix(context)
  2830. return self._check_nans(other, context)
  2831. c = self.copy_abs()._cmp(other.copy_abs())
  2832. if c == 0:
  2833. c = self.compare_total(other)
  2834. if c == -1:
  2835. ans = self
  2836. else:
  2837. ans = other
  2838. return ans._fix(context)
  2839. def next_minus(self, context=None):
  2840. """Returns the largest representable number smaller than itself."""
  2841. if context is None:
  2842. context = getcontext()
  2843. ans = self._check_nans(context=context)
  2844. if ans:
  2845. return ans
  2846. if self._isinfinity() == -1:
  2847. return _NegativeInfinity
  2848. if self._isinfinity() == 1:
  2849. return _dec_from_triple(0, '9'*context.prec, context.Etop())
  2850. context = context.copy()
  2851. context._set_rounding(ROUND_FLOOR)
  2852. context._ignore_all_flags()
  2853. new_self = self._fix(context)
  2854. if new_self != self:
  2855. return new_self
  2856. return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
  2857. context)
  2858. def next_plus(self, context=None):
  2859. """Returns the smallest representable number larger than itself."""
  2860. if context is None:
  2861. context = getcontext()
  2862. ans = self._check_nans(context=context)
  2863. if ans:
  2864. return ans
  2865. if self._isinfinity() == 1:
  2866. return _Infinity
  2867. if self._isinfinity() == -1:
  2868. return _dec_from_triple(1, '9'*context.prec, context.Etop())
  2869. context = context.copy()
  2870. context._set_rounding(ROUND_CEILING)
  2871. context._ignore_all_flags()
  2872. new_self = self._fix(context)
  2873. if new_self != self:
  2874. return new_self
  2875. return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
  2876. context)
  2877. def next_toward(self, other, context=None):
  2878. """Returns the number closest to self, in the direction towards other.
  2879. The result is the closest representable number to self
  2880. (excluding self) that is in the direction towards other,
  2881. unless both have the same value. If the two operands are
  2882. numerically equal, then the result is a copy of self with the
  2883. sign set to be the same as the sign of other.
  2884. """
  2885. other = _convert_other(other, raiseit=True)
  2886. if context is None:
  2887. context = getcontext()
  2888. ans = self._check_nans(other, context)
  2889. if ans:
  2890. return ans
  2891. comparison = self._cmp(other)
  2892. if comparison == 0:
  2893. return self.copy_sign(other)
  2894. if comparison == -1:
  2895. ans = self.next_plus(context)
  2896. else: # comparison == 1
  2897. ans = self.next_minus(context)
  2898. # decide which flags to raise using value of ans
  2899. if ans._isinfinity():
  2900. context._raise_error(Overflow,
  2901. 'Infinite result from next_toward',
  2902. ans._sign)
  2903. context._raise_error(Inexact)
  2904. context._raise_error(Rounded)
  2905. elif ans.adjusted() < context.Emin:
  2906. context._raise_error(Underflow)
  2907. context._raise_error(Subnormal)
  2908. context._raise_error(Inexact)
  2909. context._raise_error(Rounded)
  2910. # if precision == 1 then we don't raise Clamped for a
  2911. # result 0E-Etiny.
  2912. if not ans:
  2913. context._raise_error(Clamped)
  2914. return ans
  2915. def number_class(self, context=None):
  2916. """Returns an indication of the class of self.
  2917. The class is one of the following strings:
  2918. sNaN
  2919. NaN
  2920. -Infinity
  2921. -Normal
  2922. -Subnormal
  2923. -Zero
  2924. +Zero
  2925. +Subnormal
  2926. +Normal
  2927. +Infinity
  2928. """
  2929. if self.is_snan():
  2930. return "sNaN"
  2931. if self.is_qnan():
  2932. return "NaN"
  2933. inf = self._isinfinity()
  2934. if inf == 1:
  2935. return "+Infinity"
  2936. if inf == -1:
  2937. return "-Infinity"
  2938. if self.is_zero():
  2939. if self._sign:
  2940. return "-Zero"
  2941. else:
  2942. return "+Zero"
  2943. if context is None:
  2944. context = getcontext()
  2945. if self.is_subnormal(context=context):
  2946. if self._sign:
  2947. return "-Subnormal"
  2948. else:
  2949. return "+Subnormal"
  2950. # just a normal, regular, boring number, :)
  2951. if self._sign:
  2952. return "-Normal"
  2953. else:
  2954. return "+Normal"
  2955. def radix(self):
  2956. """Just returns 10, as this is Decimal, :)"""
  2957. return Decimal(10)
  2958. def rotate(self, other, context=None):
  2959. """Returns a rotated copy of self, value-of-other times."""
  2960. if context is None:
  2961. context = getcontext()
  2962. other = _convert_other(other, raiseit=True)
  2963. ans = self._check_nans(other, context)
  2964. if ans:
  2965. return ans
  2966. if other._exp != 0:
  2967. return context._raise_error(InvalidOperation)
  2968. if not (-context.prec <= int(other) <= context.prec):
  2969. return context._raise_error(InvalidOperation)
  2970. if self._isinfinity():
  2971. return Decimal(self)
  2972. # get values, pad if necessary
  2973. torot = int(other)
  2974. rotdig = self._int
  2975. topad = context.prec - len(rotdig)
  2976. if topad > 0:
  2977. rotdig = '0'*topad + rotdig
  2978. elif topad < 0:
  2979. rotdig = rotdig[-topad:]
  2980. # let's rotate!
  2981. rotated = rotdig[torot:] + rotdig[:torot]
  2982. return _dec_from_triple(self._sign,
  2983. rotated.lstrip('0') or '0', self._exp)
  2984. def scaleb(self, other, context=None):
  2985. """Returns self operand after adding the second value to its exp."""
  2986. if context is None:
  2987. context = getcontext()
  2988. other = _convert_other(other, raiseit=True)
  2989. ans = self._check_nans(other, context)
  2990. if ans:
  2991. return ans
  2992. if other._exp != 0:
  2993. return context._raise_error(InvalidOperation)
  2994. liminf = -2 * (context.Emax + context.prec)
  2995. limsup = 2 * (context.Emax + context.prec)
  2996. if not (liminf <= int(other) <= limsup):
  2997. return context._raise_error(InvalidOperation)
  2998. if self._isinfinity():
  2999. return Decimal(self)
  3000. d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
  3001. d = d._fix(context)
  3002. return d
  3003. def shift(self, other, context=None):
  3004. """Returns a shifted copy of self, value-of-other times."""
  3005. if context is None:
  3006. context = getcontext()
  3007. other = _convert_other(other, raiseit=True)
  3008. ans = self._check_nans(other, context)
  3009. if ans:
  3010. return ans
  3011. if other._exp != 0:
  3012. return context._raise_error(InvalidOperation)
  3013. if not (-context.prec <= int(other) <= context.prec):
  3014. return context._raise_error(InvalidOperation)
  3015. if self._isinfinity():
  3016. return Decimal(self)
  3017. # get values, pad if necessary
  3018. torot = int(other)
  3019. rotdig = self._int
  3020. topad = context.prec - len(rotdig)
  3021. if topad > 0:
  3022. rotdig = '0'*topad + rotdig
  3023. elif topad < 0:
  3024. rotdig = rotdig[-topad:]
  3025. # let's shift!
  3026. if torot < 0:
  3027. shifted = rotdig[:torot]
  3028. else:
  3029. shifted = rotdig + '0'*torot
  3030. shifted = shifted[-context.prec:]
  3031. return _dec_from_triple(self._sign,
  3032. shifted.lstrip('0') or '0', self._exp)
  3033. # Support for pickling, copy, and deepcopy
  3034. def __reduce__(self):
  3035. return (self.__class__, (str(self),))
  3036. def __copy__(self):
  3037. if type(self) is Decimal:
  3038. return self # I'm immutable; therefore I am my own clone
  3039. return self.__class__(str(self))
  3040. def __deepcopy__(self, memo):
  3041. if type(self) is Decimal:
  3042. return self # My components are also immutable
  3043. return self.__class__(str(self))
  3044. # PEP 3101 support. the _localeconv keyword argument should be
  3045. # considered private: it's provided for ease of testing only.
  3046. def __format__(self, specifier, context=None, _localeconv=None):
  3047. """Format a Decimal instance according to the given specifier.
  3048. The specifier should be a standard format specifier, with the
  3049. form described in PEP 3101. Formatting types 'e', 'E', 'f',
  3050. 'F', 'g', 'G', 'n' and '%' are supported. If the formatting
  3051. type is omitted it defaults to 'g' or 'G', depending on the
  3052. value of context.capitals.
  3053. """
  3054. # Note: PEP 3101 says that if the type is not present then
  3055. # there should be at least one digit after the decimal point.
  3056. # We take the liberty of ignoring this requirement for
  3057. # Decimal---it's presumably there to make sure that
  3058. # format(float, '') behaves similarly to str(float).
  3059. if context is None:
  3060. context = getcontext()
  3061. spec = _parse_format_specifier(specifier, _localeconv=_localeconv)
  3062. # special values don't care about the type or precision
  3063. if self._is_special:
  3064. sign = _format_sign(self._sign, spec)
  3065. body = str(self.copy_abs())
  3066. return _format_align(sign, body, spec)
  3067. # a type of None defaults to 'g' or 'G', depending on context
  3068. if spec['type'] is None:
  3069. spec['type'] = ['g', 'G'][context.capitals]
  3070. # if type is '%', adjust exponent of self accordingly
  3071. if spec['type'] == '%':
  3072. self = _dec_from_triple(self._sign, self._int, self._exp+2)
  3073. # round if necessary, taking rounding mode from the context
  3074. rounding = context.rounding
  3075. precision = spec['precision']
  3076. if precision is not None:
  3077. if spec['type'] in 'eE':
  3078. self = self._round(precision+1, rounding)
  3079. elif spec['type'] in 'fF%':
  3080. self = self._rescale(-precision, rounding)
  3081. elif spec['type'] in 'gG' and len(self._int) > precision:
  3082. self = self._round(precision, rounding)
  3083. # special case: zeros with a positive exponent can't be
  3084. # represented in fixed point; rescale them to 0e0.
  3085. if not self and self._exp > 0 and spec['type'] in 'fF%':
  3086. self = self._rescale(0, rounding)
  3087. # figure out placement of the decimal point
  3088. leftdigits = self._exp + len(self._int)
  3089. if spec['type'] in 'eE':
  3090. if not self and precision is not None:
  3091. dotplace = 1 - precision
  3092. else:
  3093. dotplace = 1
  3094. elif spec['type'] in 'fF%':
  3095. dotplace = leftdigits
  3096. elif spec['type'] in 'gG':
  3097. if self._exp <= 0 and leftdigits > -6:
  3098. dotplace = leftdigits
  3099. else:
  3100. dotplace = 1
  3101. # find digits before and after decimal point, and get exponent
  3102. if dotplace < 0:
  3103. intpart = '0'
  3104. fracpart = '0'*(-dotplace) + self._int
  3105. elif dotplace > len(self._int):
  3106. intpart = self._int + '0'*(dotplace-len(self._int))
  3107. fracpart = ''
  3108. else:
  3109. intpart = self._int[:dotplace] or '0'
  3110. fracpart = self._int[dotplace:]
  3111. exp = leftdigits-dotplace
  3112. # done with the decimal-specific stuff; hand over the rest
  3113. # of the formatting to the _format_number function
  3114. return _format_number(self._sign, intpart, fracpart, exp, spec)
  3115. def _dec_from_triple(sign, coefficient, exponent, special=False):
  3116. """Create a decimal instance directly, without any validation,
  3117. normalization (e.g. removal of leading zeros) or argument
  3118. conversion.
  3119. This function is for *internal use only*.
  3120. """
  3121. self = object.__new__(Decimal)
  3122. self._sign = sign
  3123. self._int = coefficient
  3124. self._exp = exponent
  3125. self._is_special = special
  3126. return self
  3127. # Register Decimal as a kind of Number (an abstract base class).
  3128. # However, do not register it as Real (because Decimals are not
  3129. # interoperable with floats).
  3130. _numbers.Number.register(Decimal)
  3131. ##### Context class #######################################################
  3132. class _ContextManager(object):
  3133. """Context manager class to support localcontext().
  3134. Sets a copy of the supplied context in __enter__() and restores
  3135. the previous decimal context in __exit__()
  3136. """
  3137. def __init__(self, new_context):
  3138. self.new_context = new_context.copy()
  3139. def __enter__(self):
  3140. self.saved_context = getcontext()
  3141. setcontext(self.new_context)
  3142. return self.new_context
  3143. def __exit__(self, t, v, tb):
  3144. setcontext(self.saved_context)
  3145. class Context(object):
  3146. """Contains the context for a Decimal instance.
  3147. Contains:
  3148. prec - precision (for use in rounding, division, square roots..)
  3149. rounding - rounding type (how you round)
  3150. traps - If traps[exception] = 1, then the exception is
  3151. raised when it is caused. Otherwise, a value is
  3152. substituted in.
  3153. flags - When an exception is caused, flags[exception] is set.
  3154. (Whether or not the trap_enabler is set)
  3155. Should be reset by user of Decimal instance.
  3156. Emin - Minimum exponent
  3157. Emax - Maximum exponent
  3158. capitals - If 1, 1*10^1 is printed as 1E+1.
  3159. If 0, printed as 1e1
  3160. _clamp - If 1, change exponents if too high (Default 0)
  3161. """
  3162. def __init__(self, prec=None, rounding=None,
  3163. traps=None, flags=None,
  3164. Emin=None, Emax=None,
  3165. capitals=None, _clamp=0,
  3166. _ignored_flags=None):
  3167. # Set defaults; for everything except flags and _ignored_flags,
  3168. # inherit from DefaultContext.
  3169. try:
  3170. dc = DefaultContext
  3171. except NameError:
  3172. pass
  3173. self.prec = prec if prec is not None else dc.prec
  3174. self.rounding = rounding if rounding is not None else dc.rounding
  3175. self.Emin = Emin if Emin is not None else dc.Emin
  3176. self.Emax = Emax if Emax is not None else dc.Emax
  3177. self.capitals = capitals if capitals is not None else dc.capitals
  3178. self._clamp = _clamp if _clamp is not None else dc._clamp
  3179. if _ignored_flags is None:
  3180. self._ignored_flags = []
  3181. else:
  3182. self._ignored_flags = _ignored_flags
  3183. if traps is None:
  3184. self.traps = dc.traps.copy()
  3185. elif not isinstance(traps, dict):
  3186. self.traps = dict((s, int(s in traps)) for s in _signals)
  3187. else:
  3188. self.traps = traps
  3189. if flags is None:
  3190. self.flags = dict.fromkeys(_signals, 0)
  3191. elif not isinstance(flags, dict):
  3192. self.flags = dict((s, int(s in flags)) for s in _signals)
  3193. else:
  3194. self.flags = flags
  3195. def __repr__(self):
  3196. """Show the current context."""
  3197. s = []
  3198. s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
  3199. 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
  3200. % vars(self))
  3201. names = [f.__name__ for f, v in self.flags.items() if v]
  3202. s.append('flags=[' + ', '.join(names) + ']')
  3203. names = [t.__name__ for t, v in self.traps.items() if v]
  3204. s.append('traps=[' + ', '.join(names) + ']')
  3205. return ', '.join(s) + ')'
  3206. def clear_flags(self):
  3207. """Reset all flags to zero"""
  3208. for flag in self.flags:
  3209. self.flags[flag] = 0
  3210. def _shallow_copy(self):
  3211. """Returns a shallow copy from self."""
  3212. nc = Context(self.prec, self.rounding, self.traps,
  3213. self.flags, self.Emin, self.Emax,
  3214. self.capitals, self._clamp, self._ignored_flags)
  3215. return nc
  3216. def copy(self):
  3217. """Returns a deep copy from self."""
  3218. nc = Context(self.prec, self.rounding, self.traps.copy(),
  3219. self.flags.copy(), self.Emin, self.Emax,
  3220. self.capitals, self._clamp, self._ignored_flags)
  3221. return nc
  3222. __copy__ = copy
  3223. def _raise_error(self, condition, explanation = None, *args):
  3224. """Handles an error
  3225. If the flag is in _ignored_flags, returns the default response.
  3226. Otherwise, it sets the flag, then, if the corresponding
  3227. trap_enabler is set, it reraises the exception. Otherwise, it returns
  3228. the default value after setting the flag.
  3229. """
  3230. error = _condition_map.get(condition, condition)
  3231. if error in self._ignored_flags:
  3232. # Don't touch the flag
  3233. return error().handle(self, *args)
  3234. self.flags[error] = 1
  3235. if not self.traps[error]:
  3236. # The errors define how to handle themselves.
  3237. return condition().handle(self, *args)
  3238. # Errors should only be risked on copies of the context
  3239. # self._ignored_flags = []
  3240. raise error(explanation)
  3241. def _ignore_all_flags(self):
  3242. """Ignore all flags, if they are raised"""
  3243. return self._ignore_flags(*_signals)
  3244. def _ignore_flags(self, *flags):
  3245. """Ignore the flags, if they are raised"""
  3246. # Do not mutate-- This way, copies of a context leave the original
  3247. # alone.
  3248. self._ignored_flags = (self._ignored_flags + list(flags))
  3249. return list(flags)
  3250. def _regard_flags(self, *flags):
  3251. """Stop ignoring the flags, if they are raised"""
  3252. if flags and isinstance(flags[0], (tuple,list)):
  3253. flags = flags[0]
  3254. for flag in flags:
  3255. self._ignored_flags.remove(flag)
  3256. # We inherit object.__hash__, so we must deny this explicitly
  3257. __hash__ = None
  3258. def Etiny(self):
  3259. """Returns Etiny (= Emin - prec + 1)"""
  3260. return int(self.Emin - self.prec + 1)
  3261. def Etop(self):
  3262. """Returns maximum exponent (= Emax - prec + 1)"""
  3263. return int(self.Emax - self.prec + 1)
  3264. def _set_rounding(self, type):
  3265. """Sets the rounding type.
  3266. Sets the rounding type, and returns the current (previous)
  3267. rounding type. Often used like:
  3268. context = context.copy()
  3269. # so you don't change the calling context
  3270. # if an error occurs in the middle.
  3271. rounding = context._set_rounding(ROUND_UP)
  3272. val = self.__sub__(other, context=context)
  3273. context._set_rounding(rounding)
  3274. This will make it round up for that operation.
  3275. """
  3276. rounding = self.rounding
  3277. self.rounding= type
  3278. return rounding
  3279. def create_decimal(self, num='0'):
  3280. """Creates a new Decimal instance but using self as context.
  3281. This method implements the to-number operation of the
  3282. IBM Decimal specification."""
  3283. if isinstance(num, basestring) and num != num.strip():
  3284. return self._raise_error(ConversionSyntax,
  3285. "no trailing or leading whitespace is "
  3286. "permitted.")
  3287. d = Decimal(num, context=self)
  3288. if d._isnan() and len(d._int) > self.prec - self._clamp:
  3289. return self._raise_error(ConversionSyntax,
  3290. "diagnostic info too long in NaN")
  3291. return d._fix(self)
  3292. def create_decimal_from_float(self, f):
  3293. """Creates a new Decimal instance from a float but rounding using self
  3294. as the context.
  3295. >>> context = Context(prec=5, rounding=ROUND_DOWN)
  3296. >>> context.create_decimal_from_float(3.1415926535897932)
  3297. Decimal('3.1415')
  3298. >>> context = Context(prec=5, traps=[Inexact])
  3299. >>> context.create_decimal_from_float(3.1415926535897932)
  3300. Traceback (most recent call last):
  3301. ...
  3302. Inexact: None
  3303. """
  3304. d = Decimal.from_float(f) # An exact conversion
  3305. return d._fix(self) # Apply the context rounding
  3306. # Methods
  3307. def abs(self, a):
  3308. """Returns the absolute value of the operand.
  3309. If the operand is negative, the result is the same as using the minus
  3310. operation on the operand. Otherwise, the result is the same as using
  3311. the plus operation on the operand.
  3312. >>> ExtendedContext.abs(Decimal('2.1'))
  3313. Decimal('2.1')
  3314. >>> ExtendedContext.abs(Decimal('-100'))
  3315. Decimal('100')
  3316. >>> ExtendedContext.abs(Decimal('101.5'))
  3317. Decimal('101.5')
  3318. >>> ExtendedContext.abs(Decimal('-101.5'))
  3319. Decimal('101.5')
  3320. >>> ExtendedContext.abs(-1)
  3321. Decimal('1')
  3322. """
  3323. a = _convert_other(a, raiseit=True)
  3324. return a.__abs__(context=self)
  3325. def add(self, a, b):
  3326. """Return the sum of the two operands.
  3327. >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
  3328. Decimal('19.00')
  3329. >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
  3330. Decimal('1.02E+4')
  3331. >>> ExtendedContext.add(1, Decimal(2))
  3332. Decimal('3')
  3333. >>> ExtendedContext.add(Decimal(8), 5)
  3334. Decimal('13')
  3335. >>> ExtendedContext.add(5, 5)
  3336. Decimal('10')
  3337. """
  3338. a = _convert_other(a, raiseit=True)
  3339. r = a.__add__(b, context=self)
  3340. if r is NotImplemented:
  3341. raise TypeError("Unable to convert %s to Decimal" % b)
  3342. else:
  3343. return r
  3344. def _apply(self, a):
  3345. return str(a._fix(self))
  3346. def canonical(self, a):
  3347. """Returns the same Decimal object.
  3348. As we do not have different encodings for the same number, the
  3349. received object already is in its canonical form.
  3350. >>> ExtendedContext.canonical(Decimal('2.50'))
  3351. Decimal('2.50')
  3352. """
  3353. return a.canonical(context=self)
  3354. def compare(self, a, b):
  3355. """Compares values numerically.
  3356. If the signs of the operands differ, a value representing each operand
  3357. ('-1' if the operand is less than zero, '0' if the operand is zero or
  3358. negative zero, or '1' if the operand is greater than zero) is used in
  3359. place of that operand for the comparison instead of the actual
  3360. operand.
  3361. The comparison is then effected by subtracting the second operand from
  3362. the first and then returning a value according to the result of the
  3363. subtraction: '-1' if the result is less than zero, '0' if the result is
  3364. zero or negative zero, or '1' if the result is greater than zero.
  3365. >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
  3366. Decimal('-1')
  3367. >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
  3368. Decimal('0')
  3369. >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
  3370. Decimal('0')
  3371. >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
  3372. Decimal('1')
  3373. >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
  3374. Decimal('1')
  3375. >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
  3376. Decimal('-1')
  3377. >>> ExtendedContext.compare(1, 2)
  3378. Decimal('-1')
  3379. >>> ExtendedContext.compare(Decimal(1), 2)
  3380. Decimal('-1')
  3381. >>> ExtendedContext.compare(1, Decimal(2))
  3382. Decimal('-1')
  3383. """
  3384. a = _convert_other(a, raiseit=True)
  3385. return a.compare(b, context=self)
  3386. def compare_signal(self, a, b):
  3387. """Compares the values of the two operands numerically.
  3388. It's pretty much like compare(), but all NaNs signal, with signaling
  3389. NaNs taking precedence over quiet NaNs.
  3390. >>> c = ExtendedContext
  3391. >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
  3392. Decimal('-1')
  3393. >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
  3394. Decimal('0')
  3395. >>> c.flags[InvalidOperation] = 0
  3396. >>> print c.flags[InvalidOperation]
  3397. 0
  3398. >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
  3399. Decimal('NaN')
  3400. >>> print c.flags[InvalidOperation]
  3401. 1
  3402. >>> c.flags[InvalidOperation] = 0
  3403. >>> print c.flags[InvalidOperation]
  3404. 0
  3405. >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
  3406. Decimal('NaN')
  3407. >>> print c.flags[InvalidOperation]
  3408. 1
  3409. >>> c.compare_signal(-1, 2)
  3410. Decimal('-1')
  3411. >>> c.compare_signal(Decimal(-1), 2)
  3412. Decimal('-1')
  3413. >>> c.compare_signal(-1, Decimal(2))
  3414. Decimal('-1')
  3415. """
  3416. a = _convert_other(a, raiseit=True)
  3417. return a.compare_signal(b, context=self)
  3418. def compare_total(self, a, b):
  3419. """Compares two operands using their abstract representation.
  3420. This is not like the standard compare, which use their numerical
  3421. value. Note that a total ordering is defined for all possible abstract
  3422. representations.
  3423. >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
  3424. Decimal('-1')
  3425. >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
  3426. Decimal('-1')
  3427. >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
  3428. Decimal('-1')
  3429. >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
  3430. Decimal('0')
  3431. >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
  3432. Decimal('1')
  3433. >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
  3434. Decimal('-1')
  3435. >>> ExtendedContext.compare_total(1, 2)
  3436. Decimal('-1')
  3437. >>> ExtendedContext.compare_total(Decimal(1), 2)
  3438. Decimal('-1')
  3439. >>> ExtendedContext.compare_total(1, Decimal(2))
  3440. Decimal('-1')
  3441. """
  3442. a = _convert_other(a, raiseit=True)
  3443. return a.compare_total(b)
  3444. def compare_total_mag(self, a, b):
  3445. """Compares two operands using their abstract representation ignoring sign.
  3446. Like compare_total, but with operand's sign ignored and assumed to be 0.
  3447. """
  3448. a = _convert_other(a, raiseit=True)
  3449. return a.compare_total_mag(b)
  3450. def copy_abs(self, a):
  3451. """Returns a copy of the operand with the sign set to 0.
  3452. >>> ExtendedContext.copy_abs(Decimal('2.1'))
  3453. Decimal('2.1')
  3454. >>> ExtendedContext.copy_abs(Decimal('-100'))
  3455. Decimal('100')
  3456. >>> ExtendedContext.copy_abs(-1)
  3457. Decimal('1')
  3458. """
  3459. a = _convert_other(a, raiseit=True)
  3460. return a.copy_abs()
  3461. def copy_decimal(self, a):
  3462. """Returns a copy of the decimal object.
  3463. >>> ExtendedContext.copy_decimal(Decimal('2.1'))
  3464. Decimal('2.1')
  3465. >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
  3466. Decimal('-1.00')
  3467. >>> ExtendedContext.copy_decimal(1)
  3468. Decimal('1')
  3469. """
  3470. a = _convert_other(a, raiseit=True)
  3471. return Decimal(a)
  3472. def copy_negate(self, a):
  3473. """Returns a copy of the operand with the sign inverted.
  3474. >>> ExtendedContext.copy_negate(Decimal('101.5'))
  3475. Decimal('-101.5')
  3476. >>> ExtendedContext.copy_negate(Decimal('-101.5'))
  3477. Decimal('101.5')
  3478. >>> ExtendedContext.copy_negate(1)
  3479. Decimal('-1')
  3480. """
  3481. a = _convert_other(a, raiseit=True)
  3482. return a.copy_negate()
  3483. def copy_sign(self, a, b):
  3484. """Copies the second operand's sign to the first one.
  3485. In detail, it returns a copy of the first operand with the sign
  3486. equal to the sign of the second operand.
  3487. >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
  3488. Decimal('1.50')
  3489. >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
  3490. Decimal('1.50')
  3491. >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
  3492. Decimal('-1.50')
  3493. >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
  3494. Decimal('-1.50')
  3495. >>> ExtendedContext.copy_sign(1, -2)
  3496. Decimal('-1')
  3497. >>> ExtendedContext.copy_sign(Decimal(1), -2)
  3498. Decimal('-1')
  3499. >>> ExtendedContext.copy_sign(1, Decimal(-2))
  3500. Decimal('-1')
  3501. """
  3502. a = _convert_other(a, raiseit=True)
  3503. return a.copy_sign(b)
  3504. def divide(self, a, b):
  3505. """Decimal division in a specified context.
  3506. >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
  3507. Decimal('0.333333333')
  3508. >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
  3509. Decimal('0.666666667')
  3510. >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
  3511. Decimal('2.5')
  3512. >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
  3513. Decimal('0.1')
  3514. >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
  3515. Decimal('1')
  3516. >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
  3517. Decimal('4.00')
  3518. >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
  3519. Decimal('1.20')
  3520. >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
  3521. Decimal('10')
  3522. >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
  3523. Decimal('1000')
  3524. >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
  3525. Decimal('1.20E+6')
  3526. >>> ExtendedContext.divide(5, 5)
  3527. Decimal('1')
  3528. >>> ExtendedContext.divide(Decimal(5), 5)
  3529. Decimal('1')
  3530. >>> ExtendedContext.divide(5, Decimal(5))
  3531. Decimal('1')
  3532. """
  3533. a = _convert_other(a, raiseit=True)
  3534. r = a.__div__(b, context=self)
  3535. if r is NotImplemented:
  3536. raise TypeError("Unable to convert %s to Decimal" % b)
  3537. else:
  3538. return r
  3539. def divide_int(self, a, b):
  3540. """Divides two numbers and returns the integer part of the result.
  3541. >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
  3542. Decimal('0')
  3543. >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
  3544. Decimal('3')
  3545. >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
  3546. Decimal('3')
  3547. >>> ExtendedContext.divide_int(10, 3)
  3548. Decimal('3')
  3549. >>> ExtendedContext.divide_int(Decimal(10), 3)
  3550. Decimal('3')
  3551. >>> ExtendedContext.divide_int(10, Decimal(3))
  3552. Decimal('3')
  3553. """
  3554. a = _convert_other(a, raiseit=True)
  3555. r = a.__floordiv__(b, context=self)
  3556. if r is NotImplemented:
  3557. raise TypeError("Unable to convert %s to Decimal" % b)
  3558. else:
  3559. return r
  3560. def divmod(self, a, b):
  3561. """Return (a // b, a % b).
  3562. >>> ExtendedContext.divmod(Decimal(8), Decimal(3))
  3563. (Decimal('2'), Decimal('2'))
  3564. >>> ExtendedContext.divmod(Decimal(8), Decimal(4))
  3565. (Decimal('2'), Decimal('0'))
  3566. >>> ExtendedContext.divmod(8, 4)
  3567. (Decimal('2'), Decimal('0'))
  3568. >>> ExtendedContext.divmod(Decimal(8), 4)
  3569. (Decimal('2'), Decimal('0'))
  3570. >>> ExtendedContext.divmod(8, Decimal(4))
  3571. (Decimal('2'), Decimal('0'))
  3572. """
  3573. a = _convert_other(a, raiseit=True)
  3574. r = a.__divmod__(b, context=self)
  3575. if r is NotImplemented:
  3576. raise TypeError("Unable to convert %s to Decimal" % b)
  3577. else:
  3578. return r
  3579. def exp(self, a):
  3580. """Returns e ** a.
  3581. >>> c = ExtendedContext.copy()
  3582. >>> c.Emin = -999
  3583. >>> c.Emax = 999
  3584. >>> c.exp(Decimal('-Infinity'))
  3585. Decimal('0')
  3586. >>> c.exp(Decimal('-1'))
  3587. Decimal('0.367879441')
  3588. >>> c.exp(Decimal('0'))
  3589. Decimal('1')
  3590. >>> c.exp(Decimal('1'))
  3591. Decimal('2.71828183')
  3592. >>> c.exp(Decimal('0.693147181'))
  3593. Decimal('2.00000000')
  3594. >>> c.exp(Decimal('+Infinity'))
  3595. Decimal('Infinity')
  3596. >>> c.exp(10)
  3597. Decimal('22026.4658')
  3598. """
  3599. a =_convert_other(a, raiseit=True)
  3600. return a.exp(context=self)
  3601. def fma(self, a, b, c):
  3602. """Returns a multiplied by b, plus c.
  3603. The first two operands are multiplied together, using multiply,
  3604. the third operand is then added to the result of that
  3605. multiplication, using add, all with only one final rounding.
  3606. >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
  3607. Decimal('22')
  3608. >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
  3609. Decimal('-8')
  3610. >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
  3611. Decimal('1.38435736E+12')
  3612. >>> ExtendedContext.fma(1, 3, 4)
  3613. Decimal('7')
  3614. >>> ExtendedContext.fma(1, Decimal(3), 4)
  3615. Decimal('7')
  3616. >>> ExtendedContext.fma(1, 3, Decimal(4))
  3617. Decimal('7')
  3618. """
  3619. a = _convert_other(a, raiseit=True)
  3620. return a.fma(b, c, context=self)
  3621. def is_canonical(self, a):
  3622. """Return True if the operand is canonical; otherwise return False.
  3623. Currently, the encoding of a Decimal instance is always
  3624. canonical, so this method returns True for any Decimal.
  3625. >>> ExtendedContext.is_canonical(Decimal('2.50'))
  3626. True
  3627. """
  3628. return a.is_canonical()
  3629. def is_finite(self, a):
  3630. """Return True if the operand is finite; otherwise return False.
  3631. A Decimal instance is considered finite if it is neither
  3632. infinite nor a NaN.
  3633. >>> ExtendedContext.is_finite(Decimal('2.50'))
  3634. True
  3635. >>> ExtendedContext.is_finite(Decimal('-0.3'))
  3636. True
  3637. >>> ExtendedContext.is_finite(Decimal('0'))
  3638. True
  3639. >>> ExtendedContext.is_finite(Decimal('Inf'))
  3640. False
  3641. >>> ExtendedContext.is_finite(Decimal('NaN'))
  3642. False
  3643. >>> ExtendedContext.is_finite(1)
  3644. True
  3645. """
  3646. a = _convert_other(a, raiseit=True)
  3647. return a.is_finite()
  3648. def is_infinite(self, a):
  3649. """Return True if the operand is infinite; otherwise return False.
  3650. >>> ExtendedContext.is_infinite(Decimal('2.50'))
  3651. False
  3652. >>> ExtendedContext.is_infinite(Decimal('-Inf'))
  3653. True
  3654. >>> ExtendedContext.is_infinite(Decimal('NaN'))
  3655. False
  3656. >>> ExtendedContext.is_infinite(1)
  3657. False
  3658. """
  3659. a = _convert_other(a, raiseit=True)
  3660. return a.is_infinite()
  3661. def is_nan(self, a):
  3662. """Return True if the operand is a qNaN or sNaN;
  3663. otherwise return False.
  3664. >>> ExtendedContext.is_nan(Decimal('2.50'))
  3665. False
  3666. >>> ExtendedContext.is_nan(Decimal('NaN'))
  3667. True
  3668. >>> ExtendedContext.is_nan(Decimal('-sNaN'))
  3669. True
  3670. >>> ExtendedContext.is_nan(1)
  3671. False
  3672. """
  3673. a = _convert_other(a, raiseit=True)
  3674. return a.is_nan()
  3675. def is_normal(self, a):
  3676. """Return True if the operand is a normal number;
  3677. otherwise return False.
  3678. >>> c = ExtendedContext.copy()
  3679. >>> c.Emin = -999
  3680. >>> c.Emax = 999
  3681. >>> c.is_normal(Decimal('2.50'))
  3682. True
  3683. >>> c.is_normal(Decimal('0.1E-999'))
  3684. False
  3685. >>> c.is_normal(Decimal('0.00'))
  3686. False
  3687. >>> c.is_normal(Decimal('-Inf'))
  3688. False
  3689. >>> c.is_normal(Decimal('NaN'))
  3690. False
  3691. >>> c.is_normal(1)
  3692. True
  3693. """
  3694. a = _convert_other(a, raiseit=True)
  3695. return a.is_normal(context=self)
  3696. def is_qnan(self, a):
  3697. """Return True if the operand is a quiet NaN; otherwise return False.
  3698. >>> ExtendedContext.is_qnan(Decimal('2.50'))
  3699. False
  3700. >>> ExtendedContext.is_qnan(Decimal('NaN'))
  3701. True
  3702. >>> ExtendedContext.is_qnan(Decimal('sNaN'))
  3703. False
  3704. >>> ExtendedContext.is_qnan(1)
  3705. False
  3706. """
  3707. a = _convert_other(a, raiseit=True)
  3708. return a.is_qnan()
  3709. def is_signed(self, a):
  3710. """Return True if the operand is negative; otherwise return False.
  3711. >>> ExtendedContext.is_signed(Decimal('2.50'))
  3712. False
  3713. >>> ExtendedContext.is_signed(Decimal('-12'))
  3714. True
  3715. >>> ExtendedContext.is_signed(Decimal('-0'))
  3716. True
  3717. >>> ExtendedContext.is_signed(8)
  3718. False
  3719. >>> ExtendedContext.is_signed(-8)
  3720. True
  3721. """
  3722. a = _convert_other(a, raiseit=True)
  3723. return a.is_signed()
  3724. def is_snan(self, a):
  3725. """Return True if the operand is a signaling NaN;
  3726. otherwise return False.
  3727. >>> ExtendedContext.is_snan(Decimal('2.50'))
  3728. False
  3729. >>> ExtendedContext.is_snan(Decimal('NaN'))
  3730. False
  3731. >>> ExtendedContext.is_snan(Decimal('sNaN'))
  3732. True
  3733. >>> ExtendedContext.is_snan(1)
  3734. False
  3735. """
  3736. a = _convert_other(a, raiseit=True)
  3737. return a.is_snan()
  3738. def is_subnormal(self, a):
  3739. """Return True if the operand is subnormal; otherwise return False.
  3740. >>> c = ExtendedContext.copy()
  3741. >>> c.Emin = -999
  3742. >>> c.Emax = 999
  3743. >>> c.is_subnormal(Decimal('2.50'))
  3744. False
  3745. >>> c.is_subnormal(Decimal('0.1E-999'))
  3746. True
  3747. >>> c.is_subnormal(Decimal('0.00'))
  3748. False
  3749. >>> c.is_subnormal(Decimal('-Inf'))
  3750. False
  3751. >>> c.is_subnormal(Decimal('NaN'))
  3752. False
  3753. >>> c.is_subnormal(1)
  3754. False
  3755. """
  3756. a = _convert_other(a, raiseit=True)
  3757. return a.is_subnormal(context=self)
  3758. def is_zero(self, a):
  3759. """Return True if the operand is a zero; otherwise return False.
  3760. >>> ExtendedContext.is_zero(Decimal('0'))
  3761. True
  3762. >>> ExtendedContext.is_zero(Decimal('2.50'))
  3763. False
  3764. >>> ExtendedContext.is_zero(Decimal('-0E+2'))
  3765. True
  3766. >>> ExtendedContext.is_zero(1)
  3767. False
  3768. >>> ExtendedContext.is_zero(0)
  3769. True
  3770. """
  3771. a = _convert_other(a, raiseit=True)
  3772. return a.is_zero()
  3773. def ln(self, a):
  3774. """Returns the natural (base e) logarithm of the operand.
  3775. >>> c = ExtendedContext.copy()
  3776. >>> c.Emin = -999
  3777. >>> c.Emax = 999
  3778. >>> c.ln(Decimal('0'))
  3779. Decimal('-Infinity')
  3780. >>> c.ln(Decimal('1.000'))
  3781. Decimal('0')
  3782. >>> c.ln(Decimal('2.71828183'))
  3783. Decimal('1.00000000')
  3784. >>> c.ln(Decimal('10'))
  3785. Decimal('2.30258509')
  3786. >>> c.ln(Decimal('+Infinity'))
  3787. Decimal('Infinity')
  3788. >>> c.ln(1)
  3789. Decimal('0')
  3790. """
  3791. a = _convert_other(a, raiseit=True)
  3792. return a.ln(context=self)
  3793. def log10(self, a):
  3794. """Returns the base 10 logarithm of the operand.
  3795. >>> c = ExtendedContext.copy()
  3796. >>> c.Emin = -999
  3797. >>> c.Emax = 999
  3798. >>> c.log10(Decimal('0'))
  3799. Decimal('-Infinity')
  3800. >>> c.log10(Decimal('0.001'))
  3801. Decimal('-3')
  3802. >>> c.log10(Decimal('1.000'))
  3803. Decimal('0')
  3804. >>> c.log10(Decimal('2'))
  3805. Decimal('0.301029996')
  3806. >>> c.log10(Decimal('10'))
  3807. Decimal('1')
  3808. >>> c.log10(Decimal('70'))
  3809. Decimal('1.84509804')
  3810. >>> c.log10(Decimal('+Infinity'))
  3811. Decimal('Infinity')
  3812. >>> c.log10(0)
  3813. Decimal('-Infinity')
  3814. >>> c.log10(1)
  3815. Decimal('0')
  3816. """
  3817. a = _convert_other(a, raiseit=True)
  3818. return a.log10(context=self)
  3819. def logb(self, a):
  3820. """ Returns the exponent of the magnitude of the operand's MSD.
  3821. The result is the integer which is the exponent of the magnitude
  3822. of the most significant digit of the operand (as though the
  3823. operand were truncated to a single digit while maintaining the
  3824. value of that digit and without limiting the resulting exponent).
  3825. >>> ExtendedContext.logb(Decimal('250'))
  3826. Decimal('2')
  3827. >>> ExtendedContext.logb(Decimal('2.50'))
  3828. Decimal('0')
  3829. >>> ExtendedContext.logb(Decimal('0.03'))
  3830. Decimal('-2')
  3831. >>> ExtendedContext.logb(Decimal('0'))
  3832. Decimal('-Infinity')
  3833. >>> ExtendedContext.logb(1)
  3834. Decimal('0')
  3835. >>> ExtendedContext.logb(10)
  3836. Decimal('1')
  3837. >>> ExtendedContext.logb(100)
  3838. Decimal('2')
  3839. """
  3840. a = _convert_other(a, raiseit=True)
  3841. return a.logb(context=self)
  3842. def logical_and(self, a, b):
  3843. """Applies the logical operation 'and' between each operand's digits.
  3844. The operands must be both logical numbers.
  3845. >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
  3846. Decimal('0')
  3847. >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
  3848. Decimal('0')
  3849. >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
  3850. Decimal('0')
  3851. >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
  3852. Decimal('1')
  3853. >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
  3854. Decimal('1000')
  3855. >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
  3856. Decimal('10')
  3857. >>> ExtendedContext.logical_and(110, 1101)
  3858. Decimal('100')
  3859. >>> ExtendedContext.logical_and(Decimal(110), 1101)
  3860. Decimal('100')
  3861. >>> ExtendedContext.logical_and(110, Decimal(1101))
  3862. Decimal('100')
  3863. """
  3864. a = _convert_other(a, raiseit=True)
  3865. return a.logical_and(b, context=self)
  3866. def logical_invert(self, a):
  3867. """Invert all the digits in the operand.
  3868. The operand must be a logical number.
  3869. >>> ExtendedContext.logical_invert(Decimal('0'))
  3870. Decimal('111111111')
  3871. >>> ExtendedContext.logical_invert(Decimal('1'))
  3872. Decimal('111111110')
  3873. >>> ExtendedContext.logical_invert(Decimal('111111111'))
  3874. Decimal('0')
  3875. >>> ExtendedContext.logical_invert(Decimal('101010101'))
  3876. Decimal('10101010')
  3877. >>> ExtendedContext.logical_invert(1101)
  3878. Decimal('111110010')
  3879. """
  3880. a = _convert_other(a, raiseit=True)
  3881. return a.logical_invert(context=self)
  3882. def logical_or(self, a, b):
  3883. """Applies the logical operation 'or' between each operand's digits.
  3884. The operands must be both logical numbers.
  3885. >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
  3886. Decimal('0')
  3887. >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
  3888. Decimal('1')
  3889. >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
  3890. Decimal('1')
  3891. >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
  3892. Decimal('1')
  3893. >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
  3894. Decimal('1110')
  3895. >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
  3896. Decimal('1110')
  3897. >>> ExtendedContext.logical_or(110, 1101)
  3898. Decimal('1111')
  3899. >>> ExtendedContext.logical_or(Decimal(110), 1101)
  3900. Decimal('1111')
  3901. >>> ExtendedContext.logical_or(110, Decimal(1101))
  3902. Decimal('1111')
  3903. """
  3904. a = _convert_other(a, raiseit=True)
  3905. return a.logical_or(b, context=self)
  3906. def logical_xor(self, a, b):
  3907. """Applies the logical operation 'xor' between each operand's digits.
  3908. The operands must be both logical numbers.
  3909. >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
  3910. Decimal('0')
  3911. >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
  3912. Decimal('1')
  3913. >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
  3914. Decimal('1')
  3915. >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
  3916. Decimal('0')
  3917. >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
  3918. Decimal('110')
  3919. >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
  3920. Decimal('1101')
  3921. >>> ExtendedContext.logical_xor(110, 1101)
  3922. Decimal('1011')
  3923. >>> ExtendedContext.logical_xor(Decimal(110), 1101)
  3924. Decimal('1011')
  3925. >>> ExtendedContext.logical_xor(110, Decimal(1101))
  3926. Decimal('1011')
  3927. """
  3928. a = _convert_other(a, raiseit=True)
  3929. return a.logical_xor(b, context=self)
  3930. def max(self, a, b):
  3931. """max compares two values numerically and returns the maximum.
  3932. If either operand is a NaN then the general rules apply.
  3933. Otherwise, the operands are compared as though by the compare
  3934. operation. If they are numerically equal then the left-hand operand
  3935. is chosen as the result. Otherwise the maximum (closer to positive
  3936. infinity) of the two operands is chosen as the result.
  3937. >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
  3938. Decimal('3')
  3939. >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
  3940. Decimal('3')
  3941. >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
  3942. Decimal('1')
  3943. >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
  3944. Decimal('7')
  3945. >>> ExtendedContext.max(1, 2)
  3946. Decimal('2')
  3947. >>> ExtendedContext.max(Decimal(1), 2)
  3948. Decimal('2')
  3949. >>> ExtendedContext.max(1, Decimal(2))
  3950. Decimal('2')
  3951. """
  3952. a = _convert_other(a, raiseit=True)
  3953. return a.max(b, context=self)
  3954. def max_mag(self, a, b):
  3955. """Compares the values numerically with their sign ignored.
  3956. >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN'))
  3957. Decimal('7')
  3958. >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10'))
  3959. Decimal('-10')
  3960. >>> ExtendedContext.max_mag(1, -2)
  3961. Decimal('-2')
  3962. >>> ExtendedContext.max_mag(Decimal(1), -2)
  3963. Decimal('-2')
  3964. >>> ExtendedContext.max_mag(1, Decimal(-2))
  3965. Decimal('-2')
  3966. """
  3967. a = _convert_other(a, raiseit=True)
  3968. return a.max_mag(b, context=self)
  3969. def min(self, a, b):
  3970. """min compares two values numerically and returns the minimum.
  3971. If either operand is a NaN then the general rules apply.
  3972. Otherwise, the operands are compared as though by the compare
  3973. operation. If they are numerically equal then the left-hand operand
  3974. is chosen as the result. Otherwise the minimum (closer to negative
  3975. infinity) of the two operands is chosen as the result.
  3976. >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
  3977. Decimal('2')
  3978. >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
  3979. Decimal('-10')
  3980. >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
  3981. Decimal('1.0')
  3982. >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
  3983. Decimal('7')
  3984. >>> ExtendedContext.min(1, 2)
  3985. Decimal('1')
  3986. >>> ExtendedContext.min(Decimal(1), 2)
  3987. Decimal('1')
  3988. >>> ExtendedContext.min(1, Decimal(29))
  3989. Decimal('1')
  3990. """
  3991. a = _convert_other(a, raiseit=True)
  3992. return a.min(b, context=self)
  3993. def min_mag(self, a, b):
  3994. """Compares the values numerically with their sign ignored.
  3995. >>> ExtendedContext.min_mag(Decimal('3'), Decimal('-2'))
  3996. Decimal('-2')
  3997. >>> ExtendedContext.min_mag(Decimal('-3'), Decimal('NaN'))
  3998. Decimal('-3')
  3999. >>> ExtendedContext.min_mag(1, -2)
  4000. Decimal('1')
  4001. >>> ExtendedContext.min_mag(Decimal(1), -2)
  4002. Decimal('1')
  4003. >>> ExtendedContext.min_mag(1, Decimal(-2))
  4004. Decimal('1')
  4005. """
  4006. a = _convert_other(a, raiseit=True)
  4007. return a.min_mag(b, context=self)
  4008. def minus(self, a):
  4009. """Minus corresponds to unary prefix minus in Python.
  4010. The operation is evaluated using the same rules as subtract; the
  4011. operation minus(a) is calculated as subtract('0', a) where the '0'
  4012. has the same exponent as the operand.
  4013. >>> ExtendedContext.minus(Decimal('1.3'))
  4014. Decimal('-1.3')
  4015. >>> ExtendedContext.minus(Decimal('-1.3'))
  4016. Decimal('1.3')
  4017. >>> ExtendedContext.minus(1)
  4018. Decimal('-1')
  4019. """
  4020. a = _convert_other(a, raiseit=True)
  4021. return a.__neg__(context=self)
  4022. def multiply(self, a, b):
  4023. """multiply multiplies two operands.
  4024. If either operand is a special value then the general rules apply.
  4025. Otherwise, the operands are multiplied together
  4026. ('long multiplication'), resulting in a number which may be as long as
  4027. the sum of the lengths of the two operands.
  4028. >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
  4029. Decimal('3.60')
  4030. >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
  4031. Decimal('21')
  4032. >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
  4033. Decimal('0.72')
  4034. >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
  4035. Decimal('-0.0')
  4036. >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
  4037. Decimal('4.28135971E+11')
  4038. >>> ExtendedContext.multiply(7, 7)
  4039. Decimal('49')
  4040. >>> ExtendedContext.multiply(Decimal(7), 7)
  4041. Decimal('49')
  4042. >>> ExtendedContext.multiply(7, Decimal(7))
  4043. Decimal('49')
  4044. """
  4045. a = _convert_other(a, raiseit=True)
  4046. r = a.__mul__(b, context=self)
  4047. if r is NotImplemented:
  4048. raise TypeError("Unable to convert %s to Decimal" % b)
  4049. else:
  4050. return r
  4051. def next_minus(self, a):
  4052. """Returns the largest representable number smaller than a.
  4053. >>> c = ExtendedContext.copy()
  4054. >>> c.Emin = -999
  4055. >>> c.Emax = 999
  4056. >>> ExtendedContext.next_minus(Decimal('1'))
  4057. Decimal('0.999999999')
  4058. >>> c.next_minus(Decimal('1E-1007'))
  4059. Decimal('0E-1007')
  4060. >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
  4061. Decimal('-1.00000004')
  4062. >>> c.next_minus(Decimal('Infinity'))
  4063. Decimal('9.99999999E+999')
  4064. >>> c.next_minus(1)
  4065. Decimal('0.999999999')
  4066. """
  4067. a = _convert_other(a, raiseit=True)
  4068. return a.next_minus(context=self)
  4069. def next_plus(self, a):
  4070. """Returns the smallest representable number larger than a.
  4071. >>> c = ExtendedContext.copy()
  4072. >>> c.Emin = -999
  4073. >>> c.Emax = 999
  4074. >>> ExtendedContext.next_plus(Decimal('1'))
  4075. Decimal('1.00000001')
  4076. >>> c.next_plus(Decimal('-1E-1007'))
  4077. Decimal('-0E-1007')
  4078. >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
  4079. Decimal('-1.00000002')
  4080. >>> c.next_plus(Decimal('-Infinity'))
  4081. Decimal('-9.99999999E+999')
  4082. >>> c.next_plus(1)
  4083. Decimal('1.00000001')
  4084. """
  4085. a = _convert_other(a, raiseit=True)
  4086. return a.next_plus(context=self)
  4087. def next_toward(self, a, b):
  4088. """Returns the number closest to a, in direction towards b.
  4089. The result is the closest representable number from the first
  4090. operand (but not the first operand) that is in the direction
  4091. towards the second operand, unless the operands have the same
  4092. value.
  4093. >>> c = ExtendedContext.copy()
  4094. >>> c.Emin = -999
  4095. >>> c.Emax = 999
  4096. >>> c.next_toward(Decimal('1'), Decimal('2'))
  4097. Decimal('1.00000001')
  4098. >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
  4099. Decimal('-0E-1007')
  4100. >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
  4101. Decimal('-1.00000002')
  4102. >>> c.next_toward(Decimal('1'), Decimal('0'))
  4103. Decimal('0.999999999')
  4104. >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
  4105. Decimal('0E-1007')
  4106. >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
  4107. Decimal('-1.00000004')
  4108. >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
  4109. Decimal('-0.00')
  4110. >>> c.next_toward(0, 1)
  4111. Decimal('1E-1007')
  4112. >>> c.next_toward(Decimal(0), 1)
  4113. Decimal('1E-1007')
  4114. >>> c.next_toward(0, Decimal(1))
  4115. Decimal('1E-1007')
  4116. """
  4117. a = _convert_other(a, raiseit=True)
  4118. return a.next_toward(b, context=self)
  4119. def normalize(self, a):
  4120. """normalize reduces an operand to its simplest form.
  4121. Essentially a plus operation with all trailing zeros removed from the
  4122. result.
  4123. >>> ExtendedContext.normalize(Decimal('2.1'))
  4124. Decimal('2.1')
  4125. >>> ExtendedContext.normalize(Decimal('-2.0'))
  4126. Decimal('-2')
  4127. >>> ExtendedContext.normalize(Decimal('1.200'))
  4128. Decimal('1.2')
  4129. >>> ExtendedContext.normalize(Decimal('-120'))
  4130. Decimal('-1.2E+2')
  4131. >>> ExtendedContext.normalize(Decimal('120.00'))
  4132. Decimal('1.2E+2')
  4133. >>> ExtendedContext.normalize(Decimal('0.00'))
  4134. Decimal('0')
  4135. >>> ExtendedContext.normalize(6)
  4136. Decimal('6')
  4137. """
  4138. a = _convert_other(a, raiseit=True)
  4139. return a.normalize(context=self)
  4140. def number_class(self, a):
  4141. """Returns an indication of the class of the operand.
  4142. The class is one of the following strings:
  4143. -sNaN
  4144. -NaN
  4145. -Infinity
  4146. -Normal
  4147. -Subnormal
  4148. -Zero
  4149. +Zero
  4150. +Subnormal
  4151. +Normal
  4152. +Infinity
  4153. >>> c = Context(ExtendedContext)
  4154. >>> c.Emin = -999
  4155. >>> c.Emax = 999
  4156. >>> c.number_class(Decimal('Infinity'))
  4157. '+Infinity'
  4158. >>> c.number_class(Decimal('1E-10'))
  4159. '+Normal'
  4160. >>> c.number_class(Decimal('2.50'))
  4161. '+Normal'
  4162. >>> c.number_class(Decimal('0.1E-999'))
  4163. '+Subnormal'
  4164. >>> c.number_class(Decimal('0'))
  4165. '+Zero'
  4166. >>> c.number_class(Decimal('-0'))
  4167. '-Zero'
  4168. >>> c.number_class(Decimal('-0.1E-999'))
  4169. '-Subnormal'
  4170. >>> c.number_class(Decimal('-1E-10'))
  4171. '-Normal'
  4172. >>> c.number_class(Decimal('-2.50'))
  4173. '-Normal'
  4174. >>> c.number_class(Decimal('-Infinity'))
  4175. '-Infinity'
  4176. >>> c.number_class(Decimal('NaN'))
  4177. 'NaN'
  4178. >>> c.number_class(Decimal('-NaN'))
  4179. 'NaN'
  4180. >>> c.number_class(Decimal('sNaN'))
  4181. 'sNaN'
  4182. >>> c.number_class(123)
  4183. '+Normal'
  4184. """
  4185. a = _convert_other(a, raiseit=True)
  4186. return a.number_class(context=self)
  4187. def plus(self, a):
  4188. """Plus corresponds to unary prefix plus in Python.
  4189. The operation is evaluated using the same rules as add; the
  4190. operation plus(a) is calculated as add('0', a) where the '0'
  4191. has the same exponent as the operand.
  4192. >>> ExtendedContext.plus(Decimal('1.3'))
  4193. Decimal('1.3')
  4194. >>> ExtendedContext.plus(Decimal('-1.3'))
  4195. Decimal('-1.3')
  4196. >>> ExtendedContext.plus(-1)
  4197. Decimal('-1')
  4198. """
  4199. a = _convert_other(a, raiseit=True)
  4200. return a.__pos__(context=self)
  4201. def power(self, a, b, modulo=None):
  4202. """Raises a to the power of b, to modulo if given.
  4203. With two arguments, compute a**b. If a is negative then b
  4204. must be integral. The result will be inexact unless b is
  4205. integral and the result is finite and can be expressed exactly
  4206. in 'precision' digits.
  4207. With three arguments, compute (a**b) % modulo. For the
  4208. three argument form, the following restrictions on the
  4209. arguments hold:
  4210. - all three arguments must be integral
  4211. - b must be nonnegative
  4212. - at least one of a or b must be nonzero
  4213. - modulo must be nonzero and have at most 'precision' digits
  4214. The result of pow(a, b, modulo) is identical to the result
  4215. that would be obtained by computing (a**b) % modulo with
  4216. unbounded precision, but is computed more efficiently. It is
  4217. always exact.
  4218. >>> c = ExtendedContext.copy()
  4219. >>> c.Emin = -999
  4220. >>> c.Emax = 999
  4221. >>> c.power(Decimal('2'), Decimal('3'))
  4222. Decimal('8')
  4223. >>> c.power(Decimal('-2'), Decimal('3'))
  4224. Decimal('-8')
  4225. >>> c.power(Decimal('2'), Decimal('-3'))
  4226. Decimal('0.125')
  4227. >>> c.power(Decimal('1.7'), Decimal('8'))
  4228. Decimal('69.7575744')
  4229. >>> c.power(Decimal('10'), Decimal('0.301029996'))
  4230. Decimal('2.00000000')
  4231. >>> c.power(Decimal('Infinity'), Decimal('-1'))
  4232. Decimal('0')
  4233. >>> c.power(Decimal('Infinity'), Decimal('0'))
  4234. Decimal('1')
  4235. >>> c.power(Decimal('Infinity'), Decimal('1'))
  4236. Decimal('Infinity')
  4237. >>> c.power(Decimal('-Infinity'), Decimal('-1'))
  4238. Decimal('-0')
  4239. >>> c.power(Decimal('-Infinity'), Decimal('0'))
  4240. Decimal('1')
  4241. >>> c.power(Decimal('-Infinity'), Decimal('1'))
  4242. Decimal('-Infinity')
  4243. >>> c.power(Decimal('-Infinity'), Decimal('2'))
  4244. Decimal('Infinity')
  4245. >>> c.power(Decimal('0'), Decimal('0'))
  4246. Decimal('NaN')
  4247. >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
  4248. Decimal('11')
  4249. >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
  4250. Decimal('-11')
  4251. >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
  4252. Decimal('1')
  4253. >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
  4254. Decimal('11')
  4255. >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
  4256. Decimal('11729830')
  4257. >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
  4258. Decimal('-0')
  4259. >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
  4260. Decimal('1')
  4261. >>> ExtendedContext.power(7, 7)
  4262. Decimal('823543')
  4263. >>> ExtendedContext.power(Decimal(7), 7)
  4264. Decimal('823543')
  4265. >>> ExtendedContext.power(7, Decimal(7), 2)
  4266. Decimal('1')
  4267. """
  4268. a = _convert_other(a, raiseit=True)
  4269. r = a.__pow__(b, modulo, context=self)
  4270. if r is NotImplemented:
  4271. raise TypeError("Unable to convert %s to Decimal" % b)
  4272. else:
  4273. return r
  4274. def quantize(self, a, b):
  4275. """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
  4276. The coefficient of the result is derived from that of the left-hand
  4277. operand. It may be rounded using the current rounding setting (if the
  4278. exponent is being increased), multiplied by a positive power of ten (if
  4279. the exponent is being decreased), or is unchanged (if the exponent is
  4280. already equal to that of the right-hand operand).
  4281. Unlike other operations, if the length of the coefficient after the
  4282. quantize operation would be greater than precision then an Invalid
  4283. operation condition is raised. This guarantees that, unless there is
  4284. an error condition, the exponent of the result of a quantize is always
  4285. equal to that of the right-hand operand.
  4286. Also unlike other operations, quantize will never raise Underflow, even
  4287. if the result is subnormal and inexact.
  4288. >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
  4289. Decimal('2.170')
  4290. >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
  4291. Decimal('2.17')
  4292. >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
  4293. Decimal('2.2')
  4294. >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
  4295. Decimal('2')
  4296. >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
  4297. Decimal('0E+1')
  4298. >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
  4299. Decimal('-Infinity')
  4300. >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
  4301. Decimal('NaN')
  4302. >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
  4303. Decimal('-0')
  4304. >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
  4305. Decimal('-0E+5')
  4306. >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
  4307. Decimal('NaN')
  4308. >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
  4309. Decimal('NaN')
  4310. >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
  4311. Decimal('217.0')
  4312. >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
  4313. Decimal('217')
  4314. >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
  4315. Decimal('2.2E+2')
  4316. >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
  4317. Decimal('2E+2')
  4318. >>> ExtendedContext.quantize(1, 2)
  4319. Decimal('1')
  4320. >>> ExtendedContext.quantize(Decimal(1), 2)
  4321. Decimal('1')
  4322. >>> ExtendedContext.quantize(1, Decimal(2))
  4323. Decimal('1')
  4324. """
  4325. a = _convert_other(a, raiseit=True)
  4326. return a.quantize(b, context=self)
  4327. def radix(self):
  4328. """Just returns 10, as this is Decimal, :)
  4329. >>> ExtendedContext.radix()
  4330. Decimal('10')
  4331. """
  4332. return Decimal(10)
  4333. def remainder(self, a, b):
  4334. """Returns the remainder from integer division.
  4335. The result is the residue of the dividend after the operation of
  4336. calculating integer division as described for divide-integer, rounded
  4337. to precision digits if necessary. The sign of the result, if
  4338. non-zero, is the same as that of the original dividend.
  4339. This operation will fail under the same conditions as integer division
  4340. (that is, if integer division on the same two operands would fail, the
  4341. remainder cannot be calculated).
  4342. >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
  4343. Decimal('2.1')
  4344. >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
  4345. Decimal('1')
  4346. >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
  4347. Decimal('-1')
  4348. >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
  4349. Decimal('0.2')
  4350. >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
  4351. Decimal('0.1')
  4352. >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
  4353. Decimal('1.0')
  4354. >>> ExtendedContext.remainder(22, 6)
  4355. Decimal('4')
  4356. >>> ExtendedContext.remainder(Decimal(22), 6)
  4357. Decimal('4')
  4358. >>> ExtendedContext.remainder(22, Decimal(6))
  4359. Decimal('4')
  4360. """
  4361. a = _convert_other(a, raiseit=True)
  4362. r = a.__mod__(b, context=self)
  4363. if r is NotImplemented:
  4364. raise TypeError("Unable to convert %s to Decimal" % b)
  4365. else:
  4366. return r
  4367. def remainder_near(self, a, b):
  4368. """Returns to be "a - b * n", where n is the integer nearest the exact
  4369. value of "x / b" (if two integers are equally near then the even one
  4370. is chosen). If the result is equal to 0 then its sign will be the
  4371. sign of a.
  4372. This operation will fail under the same conditions as integer division
  4373. (that is, if integer division on the same two operands would fail, the
  4374. remainder cannot be calculated).
  4375. >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
  4376. Decimal('-0.9')
  4377. >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
  4378. Decimal('-2')
  4379. >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
  4380. Decimal('1')
  4381. >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
  4382. Decimal('-1')
  4383. >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
  4384. Decimal('0.2')
  4385. >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
  4386. Decimal('0.1')
  4387. >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
  4388. Decimal('-0.3')
  4389. >>> ExtendedContext.remainder_near(3, 11)
  4390. Decimal('3')
  4391. >>> ExtendedContext.remainder_near(Decimal(3), 11)
  4392. Decimal('3')
  4393. >>> ExtendedContext.remainder_near(3, Decimal(11))
  4394. Decimal('3')
  4395. """
  4396. a = _convert_other(a, raiseit=True)
  4397. return a.remainder_near(b, context=self)
  4398. def rotate(self, a, b):
  4399. """Returns a rotated copy of a, b times.
  4400. The coefficient of the result is a rotated copy of the digits in
  4401. the coefficient of the first operand. The number of places of
  4402. rotation is taken from the absolute value of the second operand,
  4403. with the rotation being to the left if the second operand is
  4404. positive or to the right otherwise.
  4405. >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
  4406. Decimal('400000003')
  4407. >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
  4408. Decimal('12')
  4409. >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
  4410. Decimal('891234567')
  4411. >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
  4412. Decimal('123456789')
  4413. >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
  4414. Decimal('345678912')
  4415. >>> ExtendedContext.rotate(1333333, 1)
  4416. Decimal('13333330')
  4417. >>> ExtendedContext.rotate(Decimal(1333333), 1)
  4418. Decimal('13333330')
  4419. >>> ExtendedContext.rotate(1333333, Decimal(1))
  4420. Decimal('13333330')
  4421. """
  4422. a = _convert_other(a, raiseit=True)
  4423. return a.rotate(b, context=self)
  4424. def same_quantum(self, a, b):
  4425. """Returns True if the two operands have the same exponent.
  4426. The result is never affected by either the sign or the coefficient of
  4427. either operand.
  4428. >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
  4429. False
  4430. >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
  4431. True
  4432. >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
  4433. False
  4434. >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
  4435. True
  4436. >>> ExtendedContext.same_quantum(10000, -1)
  4437. True
  4438. >>> ExtendedContext.same_quantum(Decimal(10000), -1)
  4439. True
  4440. >>> ExtendedContext.same_quantum(10000, Decimal(-1))
  4441. True
  4442. """
  4443. a = _convert_other(a, raiseit=True)
  4444. return a.same_quantum(b)
  4445. def scaleb (self, a, b):
  4446. """Returns the first operand after adding the second value its exp.
  4447. >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
  4448. Decimal('0.0750')
  4449. >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
  4450. Decimal('7.50')
  4451. >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
  4452. Decimal('7.50E+3')
  4453. >>> ExtendedContext.scaleb(1, 4)
  4454. Decimal('1E+4')
  4455. >>> ExtendedContext.scaleb(Decimal(1), 4)
  4456. Decimal('1E+4')
  4457. >>> ExtendedContext.scaleb(1, Decimal(4))
  4458. Decimal('1E+4')
  4459. """
  4460. a = _convert_other(a, raiseit=True)
  4461. return a.scaleb(b, context=self)
  4462. def shift(self, a, b):
  4463. """Returns a shifted copy of a, b times.
  4464. The coefficient of the result is a shifted copy of the digits
  4465. in the coefficient of the first operand. The number of places
  4466. to shift is taken from the absolute value of the second operand,
  4467. with the shift being to the left if the second operand is
  4468. positive or to the right otherwise. Digits shifted into the
  4469. coefficient are zeros.
  4470. >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
  4471. Decimal('400000000')
  4472. >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
  4473. Decimal('0')
  4474. >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
  4475. Decimal('1234567')
  4476. >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
  4477. Decimal('123456789')
  4478. >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
  4479. Decimal('345678900')
  4480. >>> ExtendedContext.shift(88888888, 2)
  4481. Decimal('888888800')
  4482. >>> ExtendedContext.shift(Decimal(88888888), 2)
  4483. Decimal('888888800')
  4484. >>> ExtendedContext.shift(88888888, Decimal(2))
  4485. Decimal('888888800')
  4486. """
  4487. a = _convert_other(a, raiseit=True)
  4488. return a.shift(b, context=self)
  4489. def sqrt(self, a):
  4490. """Square root of a non-negative number to context precision.
  4491. If the result must be inexact, it is rounded using the round-half-even
  4492. algorithm.
  4493. >>> ExtendedContext.sqrt(Decimal('0'))
  4494. Decimal('0')
  4495. >>> ExtendedContext.sqrt(Decimal('-0'))
  4496. Decimal('-0')
  4497. >>> ExtendedContext.sqrt(Decimal('0.39'))
  4498. Decimal('0.624499800')
  4499. >>> ExtendedContext.sqrt(Decimal('100'))
  4500. Decimal('10')
  4501. >>> ExtendedContext.sqrt(Decimal('1'))
  4502. Decimal('1')
  4503. >>> ExtendedContext.sqrt(Decimal('1.0'))
  4504. Decimal('1.0')
  4505. >>> ExtendedContext.sqrt(Decimal('1.00'))
  4506. Decimal('1.0')
  4507. >>> ExtendedContext.sqrt(Decimal('7'))
  4508. Decimal('2.64575131')
  4509. >>> ExtendedContext.sqrt(Decimal('10'))
  4510. Decimal('3.16227766')
  4511. >>> ExtendedContext.sqrt(2)
  4512. Decimal('1.41421356')
  4513. >>> ExtendedContext.prec
  4514. 9
  4515. """
  4516. a = _convert_other(a, raiseit=True)
  4517. return a.sqrt(context=self)
  4518. def subtract(self, a, b):
  4519. """Return the difference between the two operands.
  4520. >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
  4521. Decimal('0.23')
  4522. >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
  4523. Decimal('0.00')
  4524. >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
  4525. Decimal('-0.77')
  4526. >>> ExtendedContext.subtract(8, 5)
  4527. Decimal('3')
  4528. >>> ExtendedContext.subtract(Decimal(8), 5)
  4529. Decimal('3')
  4530. >>> ExtendedContext.subtract(8, Decimal(5))
  4531. Decimal('3')
  4532. """
  4533. a = _convert_other(a, raiseit=True)
  4534. r = a.__sub__(b, context=self)
  4535. if r is NotImplemented:
  4536. raise TypeError("Unable to convert %s to Decimal" % b)
  4537. else:
  4538. return r
  4539. def to_eng_string(self, a):
  4540. """Converts a number to a string, using scientific notation.
  4541. The operation is not affected by the context.
  4542. """
  4543. a = _convert_other(a, raiseit=True)
  4544. return a.to_eng_string(context=self)
  4545. def to_sci_string(self, a):
  4546. """Converts a number to a string, using scientific notation.
  4547. The operation is not affected by the context.
  4548. """
  4549. a = _convert_other(a, raiseit=True)
  4550. return a.__str__(context=self)
  4551. def to_integral_exact(self, a):
  4552. """Rounds to an integer.
  4553. When the operand has a negative exponent, the result is the same
  4554. as using the quantize() operation using the given operand as the
  4555. left-hand-operand, 1E+0 as the right-hand-operand, and the precision
  4556. of the operand as the precision setting; Inexact and Rounded flags
  4557. are allowed in this operation. The rounding mode is taken from the
  4558. context.
  4559. >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
  4560. Decimal('2')
  4561. >>> ExtendedContext.to_integral_exact(Decimal('100'))
  4562. Decimal('100')
  4563. >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
  4564. Decimal('100')
  4565. >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
  4566. Decimal('102')
  4567. >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
  4568. Decimal('-102')
  4569. >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
  4570. Decimal('1.0E+6')
  4571. >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
  4572. Decimal('7.89E+77')
  4573. >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
  4574. Decimal('-Infinity')
  4575. """
  4576. a = _convert_other(a, raiseit=True)
  4577. return a.to_integral_exact(context=self)
  4578. def to_integral_value(self, a):
  4579. """Rounds to an integer.
  4580. When the operand has a negative exponent, the result is the same
  4581. as using the quantize() operation using the given operand as the
  4582. left-hand-operand, 1E+0 as the right-hand-operand, and the precision
  4583. of the operand as the precision setting, except that no flags will
  4584. be set. The rounding mode is taken from the context.
  4585. >>> ExtendedContext.to_integral_value(Decimal('2.1'))
  4586. Decimal('2')
  4587. >>> ExtendedContext.to_integral_value(Decimal('100'))
  4588. Decimal('100')
  4589. >>> ExtendedContext.to_integral_value(Decimal('100.0'))
  4590. Decimal('100')
  4591. >>> ExtendedContext.to_integral_value(Decimal('101.5'))
  4592. Decimal('102')
  4593. >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
  4594. Decimal('-102')
  4595. >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
  4596. Decimal('1.0E+6')
  4597. >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
  4598. Decimal('7.89E+77')
  4599. >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
  4600. Decimal('-Infinity')
  4601. """
  4602. a = _convert_other(a, raiseit=True)
  4603. return a.to_integral_value(context=self)
  4604. # the method name changed, but we provide also the old one, for compatibility
  4605. to_integral = to_integral_value
  4606. class _WorkRep(object):
  4607. __slots__ = ('sign','int','exp')
  4608. # sign: 0 or 1
  4609. # int: int or long
  4610. # exp: None, int, or string
  4611. def __init__(self, value=None):
  4612. if value is None:
  4613. self.sign = None
  4614. self.int = 0
  4615. self.exp = None
  4616. elif isinstance(value, Decimal):
  4617. self.sign = value._sign
  4618. self.int = int(value._int)
  4619. self.exp = value._exp
  4620. else:
  4621. # assert isinstance(value, tuple)
  4622. self.sign = value[0]
  4623. self.int = value[1]
  4624. self.exp = value[2]
  4625. def __repr__(self):
  4626. return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
  4627. __str__ = __repr__
  4628. def _normalize(op1, op2, prec = 0):
  4629. """Normalizes op1, op2 to have the same exp and length of coefficient.
  4630. Done during addition.
  4631. """
  4632. if op1.exp < op2.exp:
  4633. tmp = op2
  4634. other = op1
  4635. else:
  4636. tmp = op1
  4637. other = op2
  4638. # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
  4639. # Then adding 10**exp to tmp has the same effect (after rounding)
  4640. # as adding any positive quantity smaller than 10**exp; similarly
  4641. # for subtraction. So if other is smaller than 10**exp we replace
  4642. # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
  4643. tmp_len = len(str(tmp.int))
  4644. other_len = len(str(other.int))
  4645. exp = tmp.exp + min(-1, tmp_len - prec - 2)
  4646. if other_len + other.exp - 1 < exp:
  4647. other.int = 1
  4648. other.exp = exp
  4649. tmp.int *= 10 ** (tmp.exp - other.exp)
  4650. tmp.exp = other.exp
  4651. return op1, op2
  4652. ##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
  4653. # This function from Tim Peters was taken from here:
  4654. # http://mail.python.org/pipermail/python-list/1999-July/007758.html
  4655. # The correction being in the function definition is for speed, and
  4656. # the whole function is not resolved with math.log because of avoiding
  4657. # the use of floats.
  4658. def _nbits(n, correction = {
  4659. '0': 4, '1': 3, '2': 2, '3': 2,
  4660. '4': 1, '5': 1, '6': 1, '7': 1,
  4661. '8': 0, '9': 0, 'a': 0, 'b': 0,
  4662. 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
  4663. """Number of bits in binary representation of the positive integer n,
  4664. or 0 if n == 0.
  4665. """
  4666. if n < 0:
  4667. raise ValueError("The argument to _nbits should be nonnegative.")
  4668. hex_n = "%x" % n
  4669. return 4*len(hex_n) - correction[hex_n[0]]
  4670. def _sqrt_nearest(n, a):
  4671. """Closest integer to the square root of the positive integer n. a is
  4672. an initial approximation to the square root. Any positive integer
  4673. will do for a, but the closer a is to the square root of n the
  4674. faster convergence will be.
  4675. """
  4676. if n <= 0 or a <= 0:
  4677. raise ValueError("Both arguments to _sqrt_nearest should be positive.")
  4678. b=0
  4679. while a != b:
  4680. b, a = a, a--n//a>>1
  4681. return a
  4682. def _rshift_nearest(x, shift):
  4683. """Given an integer x and a nonnegative integer shift, return closest
  4684. integer to x / 2**shift; use round-to-even in case of a tie.
  4685. """
  4686. b, q = 1L << shift, x >> shift
  4687. return q + (2*(x & (b-1)) + (q&1) > b)
  4688. def _div_nearest(a, b):
  4689. """Closest integer to a/b, a and b positive integers; rounds to even
  4690. in the case of a tie.
  4691. """
  4692. q, r = divmod(a, b)
  4693. return q + (2*r + (q&1) > b)
  4694. def _ilog(x, M, L = 8):
  4695. """Integer approximation to M*log(x/M), with absolute error boundable
  4696. in terms only of x/M.
  4697. Given positive integers x and M, return an integer approximation to
  4698. M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
  4699. between the approximation and the exact result is at most 22. For
  4700. L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
  4701. both cases these are upper bounds on the error; it will usually be
  4702. much smaller."""
  4703. # The basic algorithm is the following: let log1p be the function
  4704. # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
  4705. # the reduction
  4706. #
  4707. # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
  4708. #
  4709. # repeatedly until the argument to log1p is small (< 2**-L in
  4710. # absolute value). For small y we can use the Taylor series
  4711. # expansion
  4712. #
  4713. # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
  4714. #
  4715. # truncating at T such that y**T is small enough. The whole
  4716. # computation is carried out in a form of fixed-point arithmetic,
  4717. # with a real number z being represented by an integer
  4718. # approximation to z*M. To avoid loss of precision, the y below
  4719. # is actually an integer approximation to 2**R*y*M, where R is the
  4720. # number of reductions performed so far.
  4721. y = x-M
  4722. # argument reduction; R = number of reductions performed
  4723. R = 0
  4724. while (R <= L and long(abs(y)) << L-R >= M or
  4725. R > L and abs(y) >> R-L >= M):
  4726. y = _div_nearest(long(M*y) << 1,
  4727. M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
  4728. R += 1
  4729. # Taylor series with T terms
  4730. T = -int(-10*len(str(M))//(3*L))
  4731. yshift = _rshift_nearest(y, R)
  4732. w = _div_nearest(M, T)
  4733. for k in xrange(T-1, 0, -1):
  4734. w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
  4735. return _div_nearest(w*y, M)
  4736. def _dlog10(c, e, p):
  4737. """Given integers c, e and p with c > 0, p >= 0, compute an integer
  4738. approximation to 10**p * log10(c*10**e), with an absolute error of
  4739. at most 1. Assumes that c*10**e is not exactly 1."""
  4740. # increase precision by 2; compensate for this by dividing
  4741. # final result by 100
  4742. p += 2
  4743. # write c*10**e as d*10**f with either:
  4744. # f >= 0 and 1 <= d <= 10, or
  4745. # f <= 0 and 0.1 <= d <= 1.
  4746. # Thus for c*10**e close to 1, f = 0
  4747. l = len(str(c))
  4748. f = e+l - (e+l >= 1)
  4749. if p > 0:
  4750. M = 10**p
  4751. k = e+p-f
  4752. if k >= 0:
  4753. c *= 10**k
  4754. else:
  4755. c = _div_nearest(c, 10**-k)
  4756. log_d = _ilog(c, M) # error < 5 + 22 = 27
  4757. log_10 = _log10_digits(p) # error < 1
  4758. log_d = _div_nearest(log_d*M, log_10)
  4759. log_tenpower = f*M # exact
  4760. else:
  4761. log_d = 0 # error < 2.31
  4762. log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
  4763. return _div_nearest(log_tenpower+log_d, 100)
  4764. def _dlog(c, e, p):
  4765. """Given integers c, e and p with c > 0, compute an integer
  4766. approximation to 10**p * log(c*10**e), with an absolute error of
  4767. at most 1. Assumes that c*10**e is not exactly 1."""
  4768. # Increase precision by 2. The precision increase is compensated
  4769. # for at the end with a division by 100.
  4770. p += 2
  4771. # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
  4772. # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
  4773. # as 10**p * log(d) + 10**p*f * log(10).
  4774. l = len(str(c))
  4775. f = e+l - (e+l >= 1)
  4776. # compute approximation to 10**p*log(d), with error < 27
  4777. if p > 0:
  4778. k = e+p-f
  4779. if k >= 0:
  4780. c *= 10**k
  4781. else:
  4782. c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
  4783. # _ilog magnifies existing error in c by a factor of at most 10
  4784. log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
  4785. else:
  4786. # p <= 0: just approximate the whole thing by 0; error < 2.31
  4787. log_d = 0
  4788. # compute approximation to f*10**p*log(10), with error < 11.
  4789. if f:
  4790. extra = len(str(abs(f)))-1
  4791. if p + extra >= 0:
  4792. # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
  4793. # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
  4794. f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
  4795. else:
  4796. f_log_ten = 0
  4797. else:
  4798. f_log_ten = 0
  4799. # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
  4800. return _div_nearest(f_log_ten + log_d, 100)
  4801. class _Log10Memoize(object):
  4802. """Class to compute, store, and allow retrieval of, digits of the
  4803. constant log(10) = 2.302585.... This constant is needed by
  4804. Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
  4805. def __init__(self):
  4806. self.digits = "23025850929940456840179914546843642076011014886"
  4807. def getdigits(self, p):
  4808. """Given an integer p >= 0, return floor(10**p)*log(10).
  4809. For example, self.getdigits(3) returns 2302.
  4810. """
  4811. # digits are stored as a string, for quick conversion to
  4812. # integer in the case that we've already computed enough
  4813. # digits; the stored digits should always be correct
  4814. # (truncated, not rounded to nearest).
  4815. if p < 0:
  4816. raise ValueError("p should be nonnegative")
  4817. if p >= len(self.digits):
  4818. # compute p+3, p+6, p+9, ... digits; continue until at
  4819. # least one of the extra digits is nonzero
  4820. extra = 3
  4821. while True:
  4822. # compute p+extra digits, correct to within 1ulp
  4823. M = 10**(p+extra+2)
  4824. digits = str(_div_nearest(_ilog(10*M, M), 100))
  4825. if digits[-extra:] != '0'*extra:
  4826. break
  4827. extra += 3
  4828. # keep all reliable digits so far; remove trailing zeros
  4829. # and next nonzero digit
  4830. self.digits = digits.rstrip('0')[:-1]
  4831. return int(self.digits[:p+1])
  4832. _log10_digits = _Log10Memoize().getdigits
  4833. def _iexp(x, M, L=8):
  4834. """Given integers x and M, M > 0, such that x/M is small in absolute
  4835. value, compute an integer approximation to M*exp(x/M). For 0 <=
  4836. x/M <= 2.4, the absolute error in the result is bounded by 60 (and
  4837. is usually much smaller)."""
  4838. # Algorithm: to compute exp(z) for a real number z, first divide z
  4839. # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
  4840. # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
  4841. # series
  4842. #
  4843. # expm1(x) = x + x**2/2! + x**3/3! + ...
  4844. #
  4845. # Now use the identity
  4846. #
  4847. # expm1(2x) = expm1(x)*(expm1(x)+2)
  4848. #
  4849. # R times to compute the sequence expm1(z/2**R),
  4850. # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
  4851. # Find R such that x/2**R/M <= 2**-L
  4852. R = _nbits((long(x)<<L)//M)
  4853. # Taylor series. (2**L)**T > M
  4854. T = -int(-10*len(str(M))//(3*L))
  4855. y = _div_nearest(x, T)
  4856. Mshift = long(M)<<R
  4857. for i in xrange(T-1, 0, -1):
  4858. y = _div_nearest(x*(Mshift + y), Mshift * i)
  4859. # Expansion
  4860. for k in xrange(R-1, -1, -1):
  4861. Mshift = long(M)<<(k+2)
  4862. y = _div_nearest(y*(y+Mshift), Mshift)
  4863. return M+y
  4864. def _dexp(c, e, p):
  4865. """Compute an approximation to exp(c*10**e), with p decimal places of
  4866. precision.
  4867. Returns integers d, f such that:
  4868. 10**(p-1) <= d <= 10**p, and
  4869. (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
  4870. In other words, d*10**f is an approximation to exp(c*10**e) with p
  4871. digits of precision, and with an error in d of at most 1. This is
  4872. almost, but not quite, the same as the error being < 1ulp: when d
  4873. = 10**(p-1) the error could be up to 10 ulp."""
  4874. # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
  4875. p += 2
  4876. # compute log(10) with extra precision = adjusted exponent of c*10**e
  4877. extra = max(0, e + len(str(c)) - 1)
  4878. q = p + extra
  4879. # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
  4880. # rounding down
  4881. shift = e+q
  4882. if shift >= 0:
  4883. cshift = c*10**shift
  4884. else:
  4885. cshift = c//10**-shift
  4886. quot, rem = divmod(cshift, _log10_digits(q))
  4887. # reduce remainder back to original precision
  4888. rem = _div_nearest(rem, 10**extra)
  4889. # error in result of _iexp < 120; error after division < 0.62
  4890. return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
  4891. def _dpower(xc, xe, yc, ye, p):
  4892. """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
  4893. y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
  4894. 10**(p-1) <= c <= 10**p, and
  4895. (c-1)*10**e < x**y < (c+1)*10**e
  4896. in other words, c*10**e is an approximation to x**y with p digits
  4897. of precision, and with an error in c of at most 1. (This is
  4898. almost, but not quite, the same as the error being < 1ulp: when c
  4899. == 10**(p-1) we can only guarantee error < 10ulp.)
  4900. We assume that: x is positive and not equal to 1, and y is nonzero.
  4901. """
  4902. # Find b such that 10**(b-1) <= |y| <= 10**b
  4903. b = len(str(abs(yc))) + ye
  4904. # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
  4905. lxc = _dlog(xc, xe, p+b+1)
  4906. # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
  4907. shift = ye-b
  4908. if shift >= 0:
  4909. pc = lxc*yc*10**shift
  4910. else:
  4911. pc = _div_nearest(lxc*yc, 10**-shift)
  4912. if pc == 0:
  4913. # we prefer a result that isn't exactly 1; this makes it
  4914. # easier to compute a correctly rounded result in __pow__
  4915. if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
  4916. coeff, exp = 10**(p-1)+1, 1-p
  4917. else:
  4918. coeff, exp = 10**p-1, -p
  4919. else:
  4920. coeff, exp = _dexp(pc, -(p+1), p+1)
  4921. coeff = _div_nearest(coeff, 10)
  4922. exp += 1
  4923. return coeff, exp
  4924. def _log10_lb(c, correction = {
  4925. '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
  4926. '6': 23, '7': 16, '8': 10, '9': 5}):
  4927. """Compute a lower bound for 100*log10(c) for a positive integer c."""
  4928. if c <= 0:
  4929. raise ValueError("The argument to _log10_lb should be nonnegative.")
  4930. str_c = str(c)
  4931. return 100*len(str_c) - correction[str_c[0]]
  4932. ##### Helper Functions ####################################################
  4933. def _convert_other(other, raiseit=False, allow_float=False):
  4934. """Convert other to Decimal.
  4935. Verifies that it's ok to use in an implicit construction.
  4936. If allow_float is true, allow conversion from float; this
  4937. is used in the comparison methods (__eq__ and friends).
  4938. """
  4939. if isinstance(other, Decimal):
  4940. return other
  4941. if isinstance(other, (int, long)):
  4942. return Decimal(other)
  4943. if allow_float and isinstance(other, float):
  4944. return Decimal.from_float(other)
  4945. if raiseit:
  4946. raise TypeError("Unable to convert %s to Decimal" % other)
  4947. return NotImplemented
  4948. ##### Setup Specific Contexts ############################################
  4949. # The default context prototype used by Context()
  4950. # Is mutable, so that new contexts can have different default values
  4951. DefaultContext = Context(
  4952. prec=28, rounding=ROUND_HALF_EVEN,
  4953. traps=[DivisionByZero, Overflow, InvalidOperation],
  4954. flags=[],
  4955. Emax=999999999,
  4956. Emin=-999999999,
  4957. capitals=1
  4958. )
  4959. # Pre-made alternate contexts offered by the specification
  4960. # Don't change these; the user should be able to select these
  4961. # contexts and be able to reproduce results from other implementations
  4962. # of the spec.
  4963. BasicContext = Context(
  4964. prec=9, rounding=ROUND_HALF_UP,
  4965. traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
  4966. flags=[],
  4967. )
  4968. ExtendedContext = Context(
  4969. prec=9, rounding=ROUND_HALF_EVEN,
  4970. traps=[],
  4971. flags=[],
  4972. )
  4973. ##### crud for parsing strings #############################################
  4974. #
  4975. # Regular expression used for parsing numeric strings. Additional
  4976. # comments:
  4977. #
  4978. # 1. Uncomment the two '\s*' lines to allow leading and/or trailing
  4979. # whitespace. But note that the specification disallows whitespace in
  4980. # a numeric string.
  4981. #
  4982. # 2. For finite numbers (not infinities and NaNs) the body of the
  4983. # number between the optional sign and the optional exponent must have
  4984. # at least one decimal digit, possibly after the decimal point. The
  4985. # lookahead expression '(?=\d|\.\d)' checks this.
  4986. import re
  4987. _parser = re.compile(r""" # A numeric string consists of:
  4988. # \s*
  4989. (?P<sign>[-+])? # an optional sign, followed by either...
  4990. (
  4991. (?=\d|\.\d) # ...a number (with at least one digit)
  4992. (?P<int>\d*) # having a (possibly empty) integer part
  4993. (\.(?P<frac>\d*))? # followed by an optional fractional part
  4994. (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
  4995. |
  4996. Inf(inity)? # ...an infinity, or...
  4997. |
  4998. (?P<signal>s)? # ...an (optionally signaling)
  4999. NaN # NaN
  5000. (?P<diag>\d*) # with (possibly empty) diagnostic info.
  5001. )
  5002. # \s*
  5003. \Z
  5004. """, re.VERBOSE | re.IGNORECASE | re.UNICODE).match
  5005. _all_zeros = re.compile('0*$').match
  5006. _exact_half = re.compile('50*$').match
  5007. ##### PEP3101 support functions ##############################################
  5008. # The functions in this section have little to do with the Decimal
  5009. # class, and could potentially be reused or adapted for other pure
  5010. # Python numeric classes that want to implement __format__
  5011. #
  5012. # A format specifier for Decimal looks like:
  5013. #
  5014. # [[fill]align][sign][0][minimumwidth][,][.precision][type]
  5015. _parse_format_specifier_regex = re.compile(r"""\A
  5016. (?:
  5017. (?P<fill>.)?
  5018. (?P<align>[<>=^])
  5019. )?
  5020. (?P<sign>[-+ ])?
  5021. (?P<zeropad>0)?
  5022. (?P<minimumwidth>(?!0)\d+)?
  5023. (?P<thousands_sep>,)?
  5024. (?:\.(?P<precision>0|(?!0)\d+))?
  5025. (?P<type>[eEfFgGn%])?
  5026. \Z
  5027. """, re.VERBOSE)
  5028. del re
  5029. # The locale module is only needed for the 'n' format specifier. The
  5030. # rest of the PEP 3101 code functions quite happily without it, so we
  5031. # don't care too much if locale isn't present.
  5032. try:
  5033. import locale as _locale
  5034. except ImportError:
  5035. pass
  5036. def _parse_format_specifier(format_spec, _localeconv=None):
  5037. """Parse and validate a format specifier.
  5038. Turns a standard numeric format specifier into a dict, with the
  5039. following entries:
  5040. fill: fill character to pad field to minimum width
  5041. align: alignment type, either '<', '>', '=' or '^'
  5042. sign: either '+', '-' or ' '
  5043. minimumwidth: nonnegative integer giving minimum width
  5044. zeropad: boolean, indicating whether to pad with zeros
  5045. thousands_sep: string to use as thousands separator, or ''
  5046. grouping: grouping for thousands separators, in format
  5047. used by localeconv
  5048. decimal_point: string to use for decimal point
  5049. precision: nonnegative integer giving precision, or None
  5050. type: one of the characters 'eEfFgG%', or None
  5051. unicode: boolean (always True for Python 3.x)
  5052. """
  5053. m = _parse_format_specifier_regex.match(format_spec)
  5054. if m is None:
  5055. raise ValueError("Invalid format specifier: " + format_spec)
  5056. # get the dictionary
  5057. format_dict = m.groupdict()
  5058. # zeropad; defaults for fill and alignment. If zero padding
  5059. # is requested, the fill and align fields should be absent.
  5060. fill = format_dict['fill']
  5061. align = format_dict['align']
  5062. format_dict['zeropad'] = (format_dict['zeropad'] is not None)
  5063. if format_dict['zeropad']:
  5064. if fill is not None:
  5065. raise ValueError("Fill character conflicts with '0'"
  5066. " in format specifier: " + format_spec)
  5067. if align is not None:
  5068. raise ValueError("Alignment conflicts with '0' in "
  5069. "format specifier: " + format_spec)
  5070. format_dict['fill'] = fill or ' '
  5071. # PEP 3101 originally specified that the default alignment should
  5072. # be left; it was later agreed that right-aligned makes more sense
  5073. # for numeric types. See http://bugs.python.org/issue6857.
  5074. format_dict['align'] = align or '>'
  5075. # default sign handling: '-' for negative, '' for positive
  5076. if format_dict['sign'] is None:
  5077. format_dict['sign'] = '-'
  5078. # minimumwidth defaults to 0; precision remains None if not given
  5079. format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
  5080. if format_dict['precision'] is not None:
  5081. format_dict['precision'] = int(format_dict['precision'])
  5082. # if format type is 'g' or 'G' then a precision of 0 makes little
  5083. # sense; convert it to 1. Same if format type is unspecified.
  5084. if format_dict['precision'] == 0:
  5085. if format_dict['type'] is None or format_dict['type'] in 'gG':
  5086. format_dict['precision'] = 1
  5087. # determine thousands separator, grouping, and decimal separator, and
  5088. # add appropriate entries to format_dict
  5089. if format_dict['type'] == 'n':
  5090. # apart from separators, 'n' behaves just like 'g'
  5091. format_dict['type'] = 'g'
  5092. if _localeconv is None:
  5093. _localeconv = _locale.localeconv()
  5094. if format_dict['thousands_sep'] is not None:
  5095. raise ValueError("Explicit thousands separator conflicts with "
  5096. "'n' type in format specifier: " + format_spec)
  5097. format_dict['thousands_sep'] = _localeconv['thousands_sep']
  5098. format_dict['grouping'] = _localeconv['grouping']
  5099. format_dict['decimal_point'] = _localeconv['decimal_point']
  5100. else:
  5101. if format_dict['thousands_sep'] is None:
  5102. format_dict['thousands_sep'] = ''
  5103. format_dict['grouping'] = [3, 0]
  5104. format_dict['decimal_point'] = '.'
  5105. # record whether return type should be str or unicode
  5106. format_dict['unicode'] = isinstance(format_spec, unicode)
  5107. return format_dict
  5108. def _format_align(sign, body, spec):
  5109. """Given an unpadded, non-aligned numeric string 'body' and sign
  5110. string 'sign', add padding and alignment conforming to the given
  5111. format specifier dictionary 'spec' (as produced by
  5112. parse_format_specifier).
  5113. Also converts result to unicode if necessary.
  5114. """
  5115. # how much extra space do we have to play with?
  5116. minimumwidth = spec['minimumwidth']
  5117. fill = spec['fill']
  5118. padding = fill*(minimumwidth - len(sign) - len(body))
  5119. align = spec['align']
  5120. if align == '<':
  5121. result = sign + body + padding
  5122. elif align == '>':
  5123. result = padding + sign + body
  5124. elif align == '=':
  5125. result = sign + padding + body
  5126. elif align == '^':
  5127. half = len(padding)//2
  5128. result = padding[:half] + sign + body + padding[half:]
  5129. else:
  5130. raise ValueError('Unrecognised alignment field')
  5131. # make sure that result is unicode if necessary
  5132. if spec['unicode']:
  5133. result = unicode(result)
  5134. return result
  5135. def _group_lengths(grouping):
  5136. """Convert a localeconv-style grouping into a (possibly infinite)
  5137. iterable of integers representing group lengths.
  5138. """
  5139. # The result from localeconv()['grouping'], and the input to this
  5140. # function, should be a list of integers in one of the
  5141. # following three forms:
  5142. #
  5143. # (1) an empty list, or
  5144. # (2) nonempty list of positive integers + [0]
  5145. # (3) list of positive integers + [locale.CHAR_MAX], or
  5146. from itertools import chain, repeat
  5147. if not grouping:
  5148. return []
  5149. elif grouping[-1] == 0 and len(grouping) >= 2:
  5150. return chain(grouping[:-1], repeat(grouping[-2]))
  5151. elif grouping[-1] == _locale.CHAR_MAX:
  5152. return grouping[:-1]
  5153. else:
  5154. raise ValueError('unrecognised format for grouping')
  5155. def _insert_thousands_sep(digits, spec, min_width=1):
  5156. """Insert thousands separators into a digit string.
  5157. spec is a dictionary whose keys should include 'thousands_sep' and
  5158. 'grouping'; typically it's the result of parsing the format
  5159. specifier using _parse_format_specifier.
  5160. The min_width keyword argument gives the minimum length of the
  5161. result, which will be padded on the left with zeros if necessary.
  5162. If necessary, the zero padding adds an extra '0' on the left to
  5163. avoid a leading thousands separator. For example, inserting
  5164. commas every three digits in '123456', with min_width=8, gives
  5165. '0,123,456', even though that has length 9.
  5166. """
  5167. sep = spec['thousands_sep']
  5168. grouping = spec['grouping']
  5169. groups = []
  5170. for l in _group_lengths(grouping):
  5171. if l <= 0:
  5172. raise ValueError("group length should be positive")
  5173. # max(..., 1) forces at least 1 digit to the left of a separator
  5174. l = min(max(len(digits), min_width, 1), l)
  5175. groups.append('0'*(l - len(digits)) + digits[-l:])
  5176. digits = digits[:-l]
  5177. min_width -= l
  5178. if not digits and min_width <= 0:
  5179. break
  5180. min_width -= len(sep)
  5181. else:
  5182. l = max(len(digits), min_width, 1)
  5183. groups.append('0'*(l - len(digits)) + digits[-l:])
  5184. return sep.join(reversed(groups))
  5185. def _format_sign(is_negative, spec):
  5186. """Determine sign character."""
  5187. if is_negative:
  5188. return '-'
  5189. elif spec['sign'] in ' +':
  5190. return spec['sign']
  5191. else:
  5192. return ''
  5193. def _format_number(is_negative, intpart, fracpart, exp, spec):
  5194. """Format a number, given the following data:
  5195. is_negative: true if the number is negative, else false
  5196. intpart: string of digits that must appear before the decimal point
  5197. fracpart: string of digits that must come after the point
  5198. exp: exponent, as an integer
  5199. spec: dictionary resulting from parsing the format specifier
  5200. This function uses the information in spec to:
  5201. insert separators (decimal separator and thousands separators)
  5202. format the sign
  5203. format the exponent
  5204. add trailing '%' for the '%' type
  5205. zero-pad if necessary
  5206. fill and align if necessary
  5207. """
  5208. sign = _format_sign(is_negative, spec)
  5209. if fracpart:
  5210. fracpart = spec['decimal_point'] + fracpart
  5211. if exp != 0 or spec['type'] in 'eE':
  5212. echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
  5213. fracpart += "{0}{1:+}".format(echar, exp)
  5214. if spec['type'] == '%':
  5215. fracpart += '%'
  5216. if spec['zeropad']:
  5217. min_width = spec['minimumwidth'] - len(fracpart) - len(sign)
  5218. else:
  5219. min_width = 0
  5220. intpart = _insert_thousands_sep(intpart, spec, min_width)
  5221. return _format_align(sign, intpart+fracpart, spec)
  5222. ##### Useful Constants (internal use only) ################################
  5223. # Reusable defaults
  5224. _Infinity = Decimal('Inf')
  5225. _NegativeInfinity = Decimal('-Inf')
  5226. _NaN = Decimal('NaN')
  5227. _Zero = Decimal(0)
  5228. _One = Decimal(1)
  5229. _NegativeOne = Decimal(-1)
  5230. # _SignedInfinity[sign] is infinity w/ that sign
  5231. _SignedInfinity = (_Infinity, _NegativeInfinity)
  5232. if __name__ == '__main__':
  5233. import doctest, sys
  5234. doctest.testmod(sys.modules[__name__])