/Lib/decimal.py

http://unladen-swallow.googlecode.com/ · Python · 5521 lines · 4289 code · 332 blank · 900 comment · 506 complexity · a2fb9fedfd7e1dd04d8d7dd11cdfca13 MD5 · raw file

Large files are truncated click here to view the full file

  1. # Copyright (c) 2004 Python Software Foundation.
  2. # All rights reserved.
  3. # Written by Eric Price <eprice at tjhsst.edu>
  4. # and Facundo Batista <facundo at taniquetil.com.ar>
  5. # and Raymond Hettinger <python at rcn.com>
  6. # and Aahz <aahz at pobox.com>
  7. # and Tim Peters
  8. # This module is currently Py2.3 compatible and should be kept that way
  9. # unless a major compelling advantage arises. IOW, 2.3 compatibility is
  10. # strongly preferred, but not guaranteed.
  11. # Also, this module should be kept in sync with the latest updates of
  12. # the IBM specification as it evolves. Those updates will be treated
  13. # as bug fixes (deviation from the spec is a compatibility, usability
  14. # bug) and will be backported. At this point the spec is stabilizing
  15. # and the updates are becoming fewer, smaller, and less significant.
  16. """
  17. This is a Py2.3 implementation of decimal floating point arithmetic based on
  18. the General Decimal Arithmetic Specification:
  19. www2.hursley.ibm.com/decimal/decarith.html
  20. and IEEE standard 854-1987:
  21. www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
  22. Decimal floating point has finite precision with arbitrarily large bounds.
  23. The purpose of this module is to support arithmetic using familiar
  24. "schoolhouse" rules and to avoid some of the tricky representation
  25. issues associated with binary floating point. The package is especially
  26. useful for financial applications or for contexts where users have
  27. expectations that are at odds with binary floating point (for instance,
  28. in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
  29. of the expected Decimal('0.00') returned by decimal floating point).
  30. Here are some examples of using the decimal module:
  31. >>> from decimal import *
  32. >>> setcontext(ExtendedContext)
  33. >>> Decimal(0)
  34. Decimal('0')
  35. >>> Decimal('1')
  36. Decimal('1')
  37. >>> Decimal('-.0123')
  38. Decimal('-0.0123')
  39. >>> Decimal(123456)
  40. Decimal('123456')
  41. >>> Decimal('123.45e12345678901234567890')
  42. Decimal('1.2345E+12345678901234567892')
  43. >>> Decimal('1.33') + Decimal('1.27')
  44. Decimal('2.60')
  45. >>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41')
  46. Decimal('-2.20')
  47. >>> dig = Decimal(1)
  48. >>> print dig / Decimal(3)
  49. 0.333333333
  50. >>> getcontext().prec = 18
  51. >>> print dig / Decimal(3)
  52. 0.333333333333333333
  53. >>> print dig.sqrt()
  54. 1
  55. >>> print Decimal(3).sqrt()
  56. 1.73205080756887729
  57. >>> print Decimal(3) ** 123
  58. 4.85192780976896427E+58
  59. >>> inf = Decimal(1) / Decimal(0)
  60. >>> print inf
  61. Infinity
  62. >>> neginf = Decimal(-1) / Decimal(0)
  63. >>> print neginf
  64. -Infinity
  65. >>> print neginf + inf
  66. NaN
  67. >>> print neginf * inf
  68. -Infinity
  69. >>> print dig / 0
  70. Infinity
  71. >>> getcontext().traps[DivisionByZero] = 1
  72. >>> print dig / 0
  73. Traceback (most recent call last):
  74. ...
  75. ...
  76. ...
  77. DivisionByZero: x / 0
  78. >>> c = Context()
  79. >>> c.traps[InvalidOperation] = 0
  80. >>> print c.flags[InvalidOperation]
  81. 0
  82. >>> c.divide(Decimal(0), Decimal(0))
  83. Decimal('NaN')
  84. >>> c.traps[InvalidOperation] = 1
  85. >>> print c.flags[InvalidOperation]
  86. 1
  87. >>> c.flags[InvalidOperation] = 0
  88. >>> print c.flags[InvalidOperation]
  89. 0
  90. >>> print c.divide(Decimal(0), Decimal(0))
  91. Traceback (most recent call last):
  92. ...
  93. ...
  94. ...
  95. InvalidOperation: 0 / 0
  96. >>> print c.flags[InvalidOperation]
  97. 1
  98. >>> c.flags[InvalidOperation] = 0
  99. >>> c.traps[InvalidOperation] = 0
  100. >>> print c.divide(Decimal(0), Decimal(0))
  101. NaN
  102. >>> print c.flags[InvalidOperation]
  103. 1
  104. >>>
  105. """
  106. __all__ = [
  107. # Two major classes
  108. 'Decimal', 'Context',
  109. # Contexts
  110. 'DefaultContext', 'BasicContext', 'ExtendedContext',
  111. # Exceptions
  112. 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
  113. 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
  114. # Constants for use in setting up contexts
  115. 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
  116. 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
  117. # Functions for manipulating contexts
  118. 'setcontext', 'getcontext', 'localcontext'
  119. ]
  120. 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)