PageRenderTime 88ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/Lib/decimal.py

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