PageRenderTime 70ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/site-packages/win32com/decimal_23.py

http://github.com/IronLanguages/main
Python | 3047 lines | 3011 code | 4 blank | 32 comment | 3 complexity | a3cbe3594d683069d0339d36026b6260 MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception
  1. # <win32com>
  2. # This is a clone of Python 2.4's 'decimal' module. It will only be used when
  3. # 'import decimal' fails - so is likely to be used in Python 2.3.
  4. # </win32com>
  5. # Copyright (c) 2004 Python Software Foundation.
  6. # All rights reserved.
  7. # Written by Eric Price <eprice at tjhsst.edu>
  8. # and Facundo Batista <facundo at taniquetil.com.ar>
  9. # and Raymond Hettinger <python at rcn.com>
  10. # and Aahz <aahz at pobox.com>
  11. # and Tim Peters
  12. # This module is currently Py2.3 compatible and should be kept that way
  13. # unless a major compelling advantage arises. IOW, 2.3 compatibility is
  14. # strongly preferred, but not guaranteed.
  15. # Also, this module should be kept in sync with the latest updates of
  16. # the IBM specification as it evolves. Those updates will be treated
  17. # as bug fixes (deviation from the spec is a compatibility, usability
  18. # bug) and will be backported. At this point the spec is stabilizing
  19. # and the updates are becoming fewer, smaller, and less significant.
  20. """
  21. This is a Py2.3 implementation of decimal floating point arithmetic based on
  22. the General Decimal Arithmetic Specification:
  23. www2.hursley.ibm.com/decimal/decarith.html
  24. and IEEE standard 854-1987:
  25. www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
  26. Decimal floating point has finite precision with arbitrarily large bounds.
  27. The purpose of the module is to support arithmetic using familiar
  28. "schoolhouse" rules and to avoid the some of tricky representation
  29. issues associated with binary floating point. The package is especially
  30. useful for financial applications or for contexts where users have
  31. expectations that are at odds with binary floating point (for instance,
  32. in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
  33. of the expected Decimal("0.00") returned by decimal floating point).
  34. Here are some examples of using the decimal module:
  35. >>> from decimal import *
  36. >>> setcontext(ExtendedContext)
  37. >>> Decimal(0)
  38. Decimal("0")
  39. >>> Decimal("1")
  40. Decimal("1")
  41. >>> Decimal("-.0123")
  42. Decimal("-0.0123")
  43. >>> Decimal(123456)
  44. Decimal("123456")
  45. >>> Decimal("123.45e12345678901234567890")
  46. Decimal("1.2345E+12345678901234567892")
  47. >>> Decimal("1.33") + Decimal("1.27")
  48. Decimal("2.60")
  49. >>> Decimal("12.34") + Decimal("3.87") - Decimal("18.41")
  50. Decimal("-2.20")
  51. >>> dig = Decimal(1)
  52. >>> print dig / Decimal(3)
  53. 0.333333333
  54. >>> getcontext().prec = 18
  55. >>> print dig / Decimal(3)
  56. 0.333333333333333333
  57. >>> print dig.sqrt()
  58. 1
  59. >>> print Decimal(3).sqrt()
  60. 1.73205080756887729
  61. >>> print Decimal(3) ** 123
  62. 4.85192780976896427E+58
  63. >>> inf = Decimal(1) / Decimal(0)
  64. >>> print inf
  65. Infinity
  66. >>> neginf = Decimal(-1) / Decimal(0)
  67. >>> print neginf
  68. -Infinity
  69. >>> print neginf + inf
  70. NaN
  71. >>> print neginf * inf
  72. -Infinity
  73. >>> print dig / 0
  74. Infinity
  75. >>> getcontext().traps[DivisionByZero] = 1
  76. >>> print dig / 0
  77. Traceback (most recent call last):
  78. ...
  79. ...
  80. ...
  81. DivisionByZero: x / 0
  82. >>> c = Context()
  83. >>> c.traps[InvalidOperation] = 0
  84. >>> print c.flags[InvalidOperation]
  85. 0
  86. >>> c.divide(Decimal(0), Decimal(0))
  87. Decimal("NaN")
  88. >>> c.traps[InvalidOperation] = 1
  89. >>> print c.flags[InvalidOperation]
  90. 1
  91. >>> c.flags[InvalidOperation] = 0
  92. >>> print c.flags[InvalidOperation]
  93. 0
  94. >>> print c.divide(Decimal(0), Decimal(0))
  95. Traceback (most recent call last):
  96. ...
  97. ...
  98. ...
  99. InvalidOperation: 0 / 0
  100. >>> print c.flags[InvalidOperation]
  101. 1
  102. >>> c.flags[InvalidOperation] = 0
  103. >>> c.traps[InvalidOperation] = 0
  104. >>> print c.divide(Decimal(0), Decimal(0))
  105. NaN
  106. >>> print c.flags[InvalidOperation]
  107. 1
  108. >>>
  109. """
  110. __all__ = [
  111. # Two major classes
  112. 'Decimal', 'Context',
  113. # Contexts
  114. 'DefaultContext', 'BasicContext', 'ExtendedContext',
  115. # Exceptions
  116. 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
  117. 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
  118. # Constants for use in setting up contexts
  119. 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
  120. 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN',
  121. # Functions for manipulating contexts
  122. 'setcontext', 'getcontext'
  123. ]
  124. import copy
  125. #Rounding
  126. ROUND_DOWN = 'ROUND_DOWN'
  127. ROUND_HALF_UP = 'ROUND_HALF_UP'
  128. ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
  129. ROUND_CEILING = 'ROUND_CEILING'
  130. ROUND_FLOOR = 'ROUND_FLOOR'
  131. ROUND_UP = 'ROUND_UP'
  132. ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
  133. #Rounding decision (not part of the public API)
  134. NEVER_ROUND = 'NEVER_ROUND' # Round in division (non-divmod), sqrt ONLY
  135. ALWAYS_ROUND = 'ALWAYS_ROUND' # Every operation rounds at end.
  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. """
  181. def handle(self, context, *args):
  182. if args:
  183. if args[0] == 1: #sNaN, must drop 's' but keep diagnostics
  184. return Decimal( (args[1]._sign, args[1]._int, 'n') )
  185. return NaN
  186. class ConversionSyntax(InvalidOperation):
  187. """Trying to convert badly formed string.
  188. This occurs and signals invalid-operation if an string is being
  189. converted to a number and it does not conform to the numeric string
  190. syntax. The result is [0,qNaN].
  191. """
  192. def handle(self, context, *args):
  193. return (0, (0,), 'n') #Passed to something which uses a tuple.
  194. class DivisionByZero(DecimalException, ZeroDivisionError):
  195. """Division by 0.
  196. This occurs and signals division-by-zero if division of a finite number
  197. by zero was attempted (during a divide-integer or divide operation, or a
  198. power operation with negative right-hand operand), and the dividend was
  199. not zero.
  200. The result of the operation is [sign,inf], where sign is the exclusive
  201. or of the signs of the operands for divide, or is 1 for an odd power of
  202. -0, for power.
  203. """
  204. def handle(self, context, sign, double = None, *args):
  205. if double is not None:
  206. return (Infsign[sign],)*2
  207. return Infsign[sign]
  208. class DivisionImpossible(InvalidOperation):
  209. """Cannot perform the division adequately.
  210. This occurs and signals invalid-operation if the integer result of a
  211. divide-integer or remainder operation had too many digits (would be
  212. longer than precision). The result is [0,qNaN].
  213. """
  214. def handle(self, context, *args):
  215. return (NaN, NaN)
  216. class DivisionUndefined(InvalidOperation, ZeroDivisionError):
  217. """Undefined result of division.
  218. This occurs and signals invalid-operation if division by zero was
  219. attempted (during a divide-integer, divide, or remainder operation), and
  220. the dividend is also zero. The result is [0,qNaN].
  221. """
  222. def handle(self, context, tup=None, *args):
  223. if tup is not None:
  224. return (NaN, NaN) #for 0 %0, 0 // 0
  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. pass
  236. class InvalidContext(InvalidOperation):
  237. """Invalid context. Unknown rounding, for example.
  238. This occurs and signals invalid-operation if an invalid context was
  239. detected during an operation. This can occur if contexts are not checked
  240. on creation and either the precision exceeds the capability of the
  241. underlying concrete representation or an unknown or unsupported rounding
  242. was specified. These aspects of the context need only be checked when
  243. the values are required to be used. The result is [0,qNaN].
  244. """
  245. def handle(self, context, *args):
  246. return NaN
  247. class Rounded(DecimalException):
  248. """Number got rounded (not necessarily changed during rounding).
  249. This occurs and signals rounded whenever the result of an operation is
  250. rounded (that is, some zero or non-zero digits were discarded from the
  251. coefficient), or if an overflow or underflow condition occurs. The
  252. result in all cases is unchanged.
  253. The rounded signal may be tested (or trapped) to determine if a given
  254. operation (or sequence of operations) caused a loss of precision.
  255. """
  256. pass
  257. class Subnormal(DecimalException):
  258. """Exponent < Emin before rounding.
  259. This occurs and signals subnormal whenever the result of a conversion or
  260. operation is subnormal (that is, its adjusted exponent is less than
  261. Emin, before any rounding). The result in all cases is unchanged.
  262. The subnormal signal may be tested (or trapped) to determine if a given
  263. or operation (or sequence of operations) yielded a subnormal result.
  264. """
  265. pass
  266. class Overflow(Inexact, Rounded):
  267. """Numerical overflow.
  268. This occurs and signals overflow if the adjusted exponent of a result
  269. (from a conversion or from an operation that is not an attempt to divide
  270. by zero), after rounding, would be greater than the largest value that
  271. can be handled by the implementation (the value Emax).
  272. The result depends on the rounding mode:
  273. For round-half-up and round-half-even (and for round-half-down and
  274. round-up, if implemented), the result of the operation is [sign,inf],
  275. where sign is the sign of the intermediate result. For round-down, the
  276. result is the largest finite number that can be represented in the
  277. current precision, with the sign of the intermediate result. For
  278. round-ceiling, the result is the same as for round-down if the sign of
  279. the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
  280. the result is the same as for round-down if the sign of the intermediate
  281. result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
  282. will also be raised.
  283. """
  284. def handle(self, context, sign, *args):
  285. if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
  286. ROUND_HALF_DOWN, ROUND_UP):
  287. return Infsign[sign]
  288. if sign == 0:
  289. if context.rounding == ROUND_CEILING:
  290. return Infsign[sign]
  291. return Decimal((sign, (9,)*context.prec,
  292. context.Emax-context.prec+1))
  293. if sign == 1:
  294. if context.rounding == ROUND_FLOOR:
  295. return Infsign[sign]
  296. return Decimal( (sign, (9,)*context.prec,
  297. context.Emax-context.prec+1))
  298. class Underflow(Inexact, Rounded, Subnormal):
  299. """Numerical underflow with result rounded to 0.
  300. This occurs and signals underflow if a result is inexact and the
  301. adjusted exponent of the result would be smaller (more negative) than
  302. the smallest value that can be handled by the implementation (the value
  303. Emin). That is, the result is both inexact and subnormal.
  304. The result after an underflow will be a subnormal number rounded, if
  305. necessary, so that its exponent is not less than Etiny. This may result
  306. in 0 with the sign of the intermediate result and an exponent of Etiny.
  307. In all cases, Inexact, Rounded, and Subnormal will also be raised.
  308. """
  309. # List of public traps and flags
  310. _signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
  311. Underflow, InvalidOperation, Subnormal]
  312. # Map conditions (per the spec) to signals
  313. _condition_map = {ConversionSyntax:InvalidOperation,
  314. DivisionImpossible:InvalidOperation,
  315. DivisionUndefined:InvalidOperation,
  316. InvalidContext:InvalidOperation}
  317. ##### Context Functions #######################################
  318. # The getcontext() and setcontext() function manage access to a thread-local
  319. # current context. Py2.4 offers direct support for thread locals. If that
  320. # is not available, use threading.currentThread() which is slower but will
  321. # work for older Pythons. If threads are not part of the build, create a
  322. # mock threading object with threading.local() returning the module namespace.
  323. try:
  324. import threading
  325. except ImportError:
  326. # Python was compiled without threads; create a mock object instead
  327. import sys
  328. class MockThreading:
  329. def local(self, sys=sys):
  330. return sys.modules[__name__]
  331. threading = MockThreading()
  332. del sys, MockThreading
  333. try:
  334. threading.local
  335. except AttributeError:
  336. #To fix reloading, force it to create a new context
  337. #Old contexts have different exceptions in their dicts, making problems.
  338. if hasattr(threading.currentThread(), '__decimal_context__'):
  339. del threading.currentThread().__decimal_context__
  340. def setcontext(context):
  341. """Set this thread's context to context."""
  342. if context in (DefaultContext, BasicContext, ExtendedContext):
  343. context = context.copy()
  344. context.clear_flags()
  345. threading.currentThread().__decimal_context__ = context
  346. def getcontext():
  347. """Returns this thread's context.
  348. If this thread does not yet have a context, returns
  349. a new context and sets this thread's context.
  350. New contexts are copies of DefaultContext.
  351. """
  352. try:
  353. return threading.currentThread().__decimal_context__
  354. except AttributeError:
  355. context = Context()
  356. threading.currentThread().__decimal_context__ = context
  357. return context
  358. else:
  359. local = threading.local()
  360. if hasattr(local, '__decimal_context__'):
  361. del local.__decimal_context__
  362. def getcontext(_local=local):
  363. """Returns this thread's context.
  364. If this thread does not yet have a context, returns
  365. a new context and sets this thread's context.
  366. New contexts are copies of DefaultContext.
  367. """
  368. try:
  369. return _local.__decimal_context__
  370. except AttributeError:
  371. context = Context()
  372. _local.__decimal_context__ = context
  373. return context
  374. def setcontext(context, _local=local):
  375. """Set this thread's context to context."""
  376. if context in (DefaultContext, BasicContext, ExtendedContext):
  377. context = context.copy()
  378. context.clear_flags()
  379. _local.__decimal_context__ = context
  380. del threading, local # Don't contaminate the namespace
  381. ##### Decimal class ###########################################
  382. class Decimal(object):
  383. """Floating point class for decimal arithmetic."""
  384. __slots__ = ('_exp','_int','_sign', '_is_special')
  385. # Generally, the value of the Decimal instance is given by
  386. # (-1)**_sign * _int * 10**_exp
  387. # Special values are signified by _is_special == True
  388. # We're immutable, so use __new__ not __init__
  389. def __new__(cls, value="0", context=None):
  390. """Create a decimal point instance.
  391. >>> Decimal('3.14') # string input
  392. Decimal("3.14")
  393. >>> Decimal((0, (3, 1, 4), -2)) # tuple input (sign, digit_tuple, exponent)
  394. Decimal("3.14")
  395. >>> Decimal(314) # int or long
  396. Decimal("314")
  397. >>> Decimal(Decimal(314)) # another decimal instance
  398. Decimal("314")
  399. """
  400. self = object.__new__(cls)
  401. self._is_special = False
  402. # From an internal working value
  403. if isinstance(value, _WorkRep):
  404. self._sign = value.sign
  405. self._int = tuple(map(int, str(value.int)))
  406. self._exp = int(value.exp)
  407. return self
  408. # From another decimal
  409. if isinstance(value, Decimal):
  410. self._exp = value._exp
  411. self._sign = value._sign
  412. self._int = value._int
  413. self._is_special = value._is_special
  414. return self
  415. # From an integer
  416. if isinstance(value, (int,long)):
  417. if value >= 0:
  418. self._sign = 0
  419. else:
  420. self._sign = 1
  421. self._exp = 0
  422. self._int = tuple(map(int, str(abs(value))))
  423. return self
  424. # tuple/list conversion (possibly from as_tuple())
  425. if isinstance(value, (list,tuple)):
  426. if len(value) != 3:
  427. raise ValueError, 'Invalid arguments'
  428. if value[0] not in (0,1):
  429. raise ValueError, 'Invalid sign'
  430. for digit in value[1]:
  431. if not isinstance(digit, (int,long)) or digit < 0:
  432. raise ValueError, "The second value in the tuple must be composed of non negative integer elements."
  433. self._sign = value[0]
  434. self._int = tuple(value[1])
  435. if value[2] in ('F','n','N'):
  436. self._exp = value[2]
  437. self._is_special = True
  438. else:
  439. self._exp = int(value[2])
  440. return self
  441. if isinstance(value, float):
  442. raise TypeError("Cannot convert float to Decimal. " +
  443. "First convert the float to a string")
  444. # Other argument types may require the context during interpretation
  445. if context is None:
  446. context = getcontext()
  447. # From a string
  448. # REs insist on real strings, so we can too.
  449. if isinstance(value, basestring):
  450. if _isinfinity(value):
  451. self._exp = 'F'
  452. self._int = (0,)
  453. self._is_special = True
  454. if _isinfinity(value) == 1:
  455. self._sign = 0
  456. else:
  457. self._sign = 1
  458. return self
  459. if _isnan(value):
  460. sig, sign, diag = _isnan(value)
  461. self._is_special = True
  462. if len(diag) > context.prec: #Diagnostic info too long
  463. self._sign, self._int, self._exp = \
  464. context._raise_error(ConversionSyntax)
  465. return self
  466. if sig == 1:
  467. self._exp = 'n' #qNaN
  468. else: #sig == 2
  469. self._exp = 'N' #sNaN
  470. self._sign = sign
  471. self._int = tuple(map(int, diag)) #Diagnostic info
  472. return self
  473. try:
  474. self._sign, self._int, self._exp = _string2exact(value)
  475. except ValueError:
  476. self._is_special = True
  477. self._sign, self._int, self._exp = context._raise_error(ConversionSyntax)
  478. return self
  479. raise TypeError("Cannot convert %r to Decimal" % value)
  480. def _isnan(self):
  481. """Returns whether the number is not actually one.
  482. 0 if a number
  483. 1 if NaN
  484. 2 if sNaN
  485. """
  486. if self._is_special:
  487. exp = self._exp
  488. if exp == 'n':
  489. return 1
  490. elif exp == 'N':
  491. return 2
  492. return 0
  493. def _isinfinity(self):
  494. """Returns whether the number is infinite
  495. 0 if finite or not a number
  496. 1 if +INF
  497. -1 if -INF
  498. """
  499. if self._exp == 'F':
  500. if self._sign:
  501. return -1
  502. return 1
  503. return 0
  504. def _check_nans(self, other = None, context=None):
  505. """Returns whether the number is not actually one.
  506. if self, other are sNaN, signal
  507. if self, other are NaN return nan
  508. return 0
  509. Done before operations.
  510. """
  511. self_is_nan = self._isnan()
  512. if other is None:
  513. other_is_nan = False
  514. else:
  515. other_is_nan = other._isnan()
  516. if self_is_nan or other_is_nan:
  517. if context is None:
  518. context = getcontext()
  519. if self_is_nan == 2:
  520. return context._raise_error(InvalidOperation, 'sNaN',
  521. 1, self)
  522. if other_is_nan == 2:
  523. return context._raise_error(InvalidOperation, 'sNaN',
  524. 1, other)
  525. if self_is_nan:
  526. return self
  527. return other
  528. return 0
  529. def __nonzero__(self):
  530. """Is the number non-zero?
  531. 0 if self == 0
  532. 1 if self != 0
  533. """
  534. if self._is_special:
  535. return 1
  536. return sum(self._int) != 0
  537. def __cmp__(self, other, context=None):
  538. other = _convert_other(other)
  539. if self._is_special or other._is_special:
  540. ans = self._check_nans(other, context)
  541. if ans:
  542. return 1 # Comparison involving NaN's always reports self > other
  543. # INF = INF
  544. return cmp(self._isinfinity(), other._isinfinity())
  545. if not self and not other:
  546. return 0 #If both 0, sign comparison isn't certain.
  547. #If different signs, neg one is less
  548. if other._sign < self._sign:
  549. return -1
  550. if self._sign < other._sign:
  551. return 1
  552. self_adjusted = self.adjusted()
  553. other_adjusted = other.adjusted()
  554. if self_adjusted == other_adjusted and \
  555. self._int + (0,)*(self._exp - other._exp) == \
  556. other._int + (0,)*(other._exp - self._exp):
  557. return 0 #equal, except in precision. ([0]*(-x) = [])
  558. elif self_adjusted > other_adjusted and self._int[0] != 0:
  559. return (-1)**self._sign
  560. elif self_adjusted < other_adjusted and other._int[0] != 0:
  561. return -((-1)**self._sign)
  562. # Need to round, so make sure we have a valid context
  563. if context is None:
  564. context = getcontext()
  565. context = context._shallow_copy()
  566. rounding = context._set_rounding(ROUND_UP) #round away from 0
  567. flags = context._ignore_all_flags()
  568. res = self.__sub__(other, context=context)
  569. context._regard_flags(*flags)
  570. context.rounding = rounding
  571. if not res:
  572. return 0
  573. elif res._sign:
  574. return -1
  575. return 1
  576. def __eq__(self, other):
  577. if not isinstance(other, (Decimal, int, long)):
  578. return False
  579. return self.__cmp__(other) == 0
  580. def __ne__(self, other):
  581. if not isinstance(other, (Decimal, int, long)):
  582. return True
  583. return self.__cmp__(other) != 0
  584. def compare(self, other, context=None):
  585. """Compares one to another.
  586. -1 => a < b
  587. 0 => a = b
  588. 1 => a > b
  589. NaN => one is NaN
  590. Like __cmp__, but returns Decimal instances.
  591. """
  592. other = _convert_other(other)
  593. #compare(NaN, NaN) = NaN
  594. if (self._is_special or other and other._is_special):
  595. ans = self._check_nans(other, context)
  596. if ans:
  597. return ans
  598. return Decimal(self.__cmp__(other, context))
  599. def __hash__(self):
  600. """x.__hash__() <==> hash(x)"""
  601. # Decimal integers must hash the same as the ints
  602. # Non-integer decimals are normalized and hashed as strings
  603. # Normalization assures that hast(100E-1) == hash(10)
  604. if self._is_special:
  605. if self._isnan():
  606. raise TypeError('Cannot hash a NaN value.')
  607. return hash(str(self))
  608. i = int(self)
  609. if self == Decimal(i):
  610. return hash(i)
  611. assert self.__nonzero__() # '-0' handled by integer case
  612. return hash(str(self.normalize()))
  613. def as_tuple(self):
  614. """Represents the number as a triple tuple.
  615. To show the internals exactly as they are.
  616. """
  617. return (self._sign, self._int, self._exp)
  618. def __repr__(self):
  619. """Represents the number as an instance of Decimal."""
  620. # Invariant: eval(repr(d)) == d
  621. return 'Decimal("%s")' % str(self)
  622. def __str__(self, eng = 0, context=None):
  623. """Return string representation of the number in scientific notation.
  624. Captures all of the information in the underlying representation.
  625. """
  626. if self._isnan():
  627. minus = '-'*self._sign
  628. if self._int == (0,):
  629. info = ''
  630. else:
  631. info = ''.join(map(str, self._int))
  632. if self._isnan() == 2:
  633. return minus + 'sNaN' + info
  634. return minus + 'NaN' + info
  635. if self._isinfinity():
  636. minus = '-'*self._sign
  637. return minus + 'Infinity'
  638. if context is None:
  639. context = getcontext()
  640. tmp = map(str, self._int)
  641. numdigits = len(self._int)
  642. leftdigits = self._exp + numdigits
  643. if eng and not self: #self = 0eX wants 0[.0[0]]eY, not [[0]0]0eY
  644. if self._exp < 0 and self._exp >= -6: #short, no need for e/E
  645. s = '-'*self._sign + '0.' + '0'*(abs(self._exp))
  646. return s
  647. #exp is closest mult. of 3 >= self._exp
  648. exp = ((self._exp - 1)// 3 + 1) * 3
  649. if exp != self._exp:
  650. s = '0.'+'0'*(exp - self._exp)
  651. else:
  652. s = '0'
  653. if exp != 0:
  654. if context.capitals:
  655. s += 'E'
  656. else:
  657. s += 'e'
  658. if exp > 0:
  659. s += '+' #0.0e+3, not 0.0e3
  660. s += str(exp)
  661. s = '-'*self._sign + s
  662. return s
  663. if eng:
  664. dotplace = (leftdigits-1)%3+1
  665. adjexp = leftdigits -1 - (leftdigits-1)%3
  666. else:
  667. adjexp = leftdigits-1
  668. dotplace = 1
  669. if self._exp == 0:
  670. pass
  671. elif self._exp < 0 and adjexp >= 0:
  672. tmp.insert(leftdigits, '.')
  673. elif self._exp < 0 and adjexp >= -6:
  674. tmp[0:0] = ['0'] * int(-leftdigits)
  675. tmp.insert(0, '0.')
  676. else:
  677. if numdigits > dotplace:
  678. tmp.insert(dotplace, '.')
  679. elif numdigits < dotplace:
  680. tmp.extend(['0']*(dotplace-numdigits))
  681. if adjexp:
  682. if not context.capitals:
  683. tmp.append('e')
  684. else:
  685. tmp.append('E')
  686. if adjexp > 0:
  687. tmp.append('+')
  688. tmp.append(str(adjexp))
  689. if eng:
  690. while tmp[0:1] == ['0']:
  691. tmp[0:1] = []
  692. if len(tmp) == 0 or tmp[0] == '.' or tmp[0].lower() == 'e':
  693. tmp[0:0] = ['0']
  694. if self._sign:
  695. tmp.insert(0, '-')
  696. return ''.join(tmp)
  697. def to_eng_string(self, context=None):
  698. """Convert to engineering-type string.
  699. Engineering notation has an exponent which is a multiple of 3, so there
  700. are up to 3 digits left of the decimal place.
  701. Same rules for when in exponential and when as a value as in __str__.
  702. """
  703. return self.__str__(eng=1, context=context)
  704. def __neg__(self, context=None):
  705. """Returns a copy with the sign switched.
  706. Rounds, if it has reason.
  707. """
  708. if self._is_special:
  709. ans = self._check_nans(context=context)
  710. if ans:
  711. return ans
  712. if not self:
  713. # -Decimal('0') is Decimal('0'), not Decimal('-0')
  714. sign = 0
  715. elif self._sign:
  716. sign = 0
  717. else:
  718. sign = 1
  719. if context is None:
  720. context = getcontext()
  721. if context._rounding_decision == ALWAYS_ROUND:
  722. return Decimal((sign, self._int, self._exp))._fix(context)
  723. return Decimal( (sign, self._int, self._exp))
  724. def __pos__(self, context=None):
  725. """Returns a copy, unless it is a sNaN.
  726. Rounds the number (if more then precision digits)
  727. """
  728. if self._is_special:
  729. ans = self._check_nans(context=context)
  730. if ans:
  731. return ans
  732. sign = self._sign
  733. if not self:
  734. # + (-0) = 0
  735. sign = 0
  736. if context is None:
  737. context = getcontext()
  738. if context._rounding_decision == ALWAYS_ROUND:
  739. ans = self._fix(context)
  740. else:
  741. ans = Decimal(self)
  742. ans._sign = sign
  743. return ans
  744. def __abs__(self, round=1, context=None):
  745. """Returns the absolute value of self.
  746. If the second argument is 0, do not round.
  747. """
  748. if self._is_special:
  749. ans = self._check_nans(context=context)
  750. if ans:
  751. return ans
  752. if not round:
  753. if context is None:
  754. context = getcontext()
  755. context = context._shallow_copy()
  756. context._set_rounding_decision(NEVER_ROUND)
  757. if self._sign:
  758. ans = self.__neg__(context=context)
  759. else:
  760. ans = self.__pos__(context=context)
  761. return ans
  762. def __add__(self, other, context=None):
  763. """Returns self + other.
  764. -INF + INF (or the reverse) cause InvalidOperation errors.
  765. """
  766. other = _convert_other(other)
  767. if context is None:
  768. context = getcontext()
  769. if self._is_special or other._is_special:
  770. ans = self._check_nans(other, context)
  771. if ans:
  772. return ans
  773. if self._isinfinity():
  774. #If both INF, same sign => same as both, opposite => error.
  775. if self._sign != other._sign and other._isinfinity():
  776. return context._raise_error(InvalidOperation, '-INF + INF')
  777. return Decimal(self)
  778. if other._isinfinity():
  779. return Decimal(other) #Can't both be infinity here
  780. shouldround = context._rounding_decision == ALWAYS_ROUND
  781. exp = min(self._exp, other._exp)
  782. negativezero = 0
  783. if context.rounding == ROUND_FLOOR and self._sign != other._sign:
  784. #If the answer is 0, the sign should be negative, in this case.
  785. negativezero = 1
  786. if not self and not other:
  787. sign = min(self._sign, other._sign)
  788. if negativezero:
  789. sign = 1
  790. return Decimal( (sign, (0,), exp))
  791. if not self:
  792. exp = max(exp, other._exp - context.prec-1)
  793. ans = other._rescale(exp, watchexp=0, context=context)
  794. if shouldround:
  795. ans = ans._fix(context)
  796. return ans
  797. if not other:
  798. exp = max(exp, self._exp - context.prec-1)
  799. ans = self._rescale(exp, watchexp=0, context=context)
  800. if shouldround:
  801. ans = ans._fix(context)
  802. return ans
  803. op1 = _WorkRep(self)
  804. op2 = _WorkRep(other)
  805. op1, op2 = _normalize(op1, op2, shouldround, context.prec)
  806. result = _WorkRep()
  807. if op1.sign != op2.sign:
  808. # Equal and opposite
  809. if op1.int == op2.int:
  810. if exp < context.Etiny():
  811. exp = context.Etiny()
  812. context._raise_error(Clamped)
  813. return Decimal((negativezero, (0,), exp))
  814. if op1.int < op2.int:
  815. op1, op2 = op2, op1
  816. #OK, now abs(op1) > abs(op2)
  817. if op1.sign == 1:
  818. result.sign = 1
  819. op1.sign, op2.sign = op2.sign, op1.sign
  820. else:
  821. result.sign = 0
  822. #So we know the sign, and op1 > 0.
  823. elif op1.sign == 1:
  824. result.sign = 1
  825. op1.sign, op2.sign = (0, 0)
  826. else:
  827. result.sign = 0
  828. #Now, op1 > abs(op2) > 0
  829. if op2.sign == 0:
  830. result.int = op1.int + op2.int
  831. else:
  832. result.int = op1.int - op2.int
  833. result.exp = op1.exp
  834. ans = Decimal(result)
  835. if shouldround:
  836. ans = ans._fix(context)
  837. return ans
  838. __radd__ = __add__
  839. def __sub__(self, other, context=None):
  840. """Return self + (-other)"""
  841. other = _convert_other(other)
  842. if self._is_special or other._is_special:
  843. ans = self._check_nans(other, context=context)
  844. if ans:
  845. return ans
  846. # -Decimal(0) = Decimal(0), which we don't want since
  847. # (-0 - 0 = -0 + (-0) = -0, but -0 + 0 = 0.)
  848. # so we change the sign directly to a copy
  849. tmp = Decimal(other)
  850. tmp._sign = 1-tmp._sign
  851. return self.__add__(tmp, context=context)
  852. def __rsub__(self, other, context=None):
  853. """Return other + (-self)"""
  854. other = _convert_other(other)
  855. tmp = Decimal(self)
  856. tmp._sign = 1 - tmp._sign
  857. return other.__add__(tmp, context=context)
  858. def _increment(self, round=1, context=None):
  859. """Special case of add, adding 1eExponent
  860. Since it is common, (rounding, for example) this adds
  861. (sign)*one E self._exp to the number more efficiently than add.
  862. For example:
  863. Decimal('5.624e10')._increment() == Decimal('5.625e10')
  864. """
  865. if self._is_special:
  866. ans = self._check_nans(context=context)
  867. if ans:
  868. return ans
  869. return Decimal(self) # Must be infinite, and incrementing makes no difference
  870. L = list(self._int)
  871. L[-1] += 1
  872. spot = len(L)-1
  873. while L[spot] == 10:
  874. L[spot] = 0
  875. if spot == 0:
  876. L[0:0] = [1]
  877. break
  878. L[spot-1] += 1
  879. spot -= 1
  880. ans = Decimal((self._sign, L, self._exp))
  881. if context is None:
  882. context = getcontext()
  883. if round and context._rounding_decision == ALWAYS_ROUND:
  884. ans = ans._fix(context)
  885. return ans
  886. def __mul__(self, other, context=None):
  887. """Return self * other.
  888. (+-) INF * 0 (or its reverse) raise InvalidOperation.
  889. """
  890. other = _convert_other(other)
  891. if context is None:
  892. context = getcontext()
  893. resultsign = self._sign ^ other._sign
  894. if self._is_special or other._is_special:
  895. ans = self._check_nans(other, context)
  896. if ans:
  897. return ans
  898. if self._isinfinity():
  899. if not other:
  900. return context._raise_error(InvalidOperation, '(+-)INF * 0')
  901. return Infsign[resultsign]
  902. if other._isinfinity():
  903. if not self:
  904. return context._raise_error(InvalidOperation, '0 * (+-)INF')
  905. return Infsign[resultsign]
  906. resultexp = self._exp + other._exp
  907. shouldround = context._rounding_decision == ALWAYS_ROUND
  908. # Special case for multiplying by zero
  909. if not self or not other:
  910. ans = Decimal((resultsign, (0,), resultexp))
  911. if shouldround:
  912. #Fixing in case the exponent is out of bounds
  913. ans = ans._fix(context)
  914. return ans
  915. # Special case for multiplying by power of 10
  916. if self._int == (1,):
  917. ans = Decimal((resultsign, other._int, resultexp))
  918. if shouldround:
  919. ans = ans._fix(context)
  920. return ans
  921. if other._int == (1,):
  922. ans = Decimal((resultsign, self._int, resultexp))
  923. if shouldround:
  924. ans = ans._fix(context)
  925. return ans
  926. op1 = _WorkRep(self)
  927. op2 = _WorkRep(other)
  928. ans = Decimal( (resultsign, map(int, str(op1.int * op2.int)), resultexp))
  929. if shouldround:
  930. ans = ans._fix(context)
  931. return ans
  932. __rmul__ = __mul__
  933. def __div__(self, other, context=None):
  934. """Return self / other."""
  935. return self._divide(other, context=context)
  936. __truediv__ = __div__
  937. def _divide(self, other, divmod = 0, context=None):
  938. """Return a / b, to context.prec precision.
  939. divmod:
  940. 0 => true division
  941. 1 => (a //b, a%b)
  942. 2 => a //b
  943. 3 => a%b
  944. Actually, if divmod is 2 or 3 a tuple is returned, but errors for
  945. computing the other value are not raised.
  946. """
  947. other = _convert_other(other)
  948. if context is None:
  949. context = getcontext()
  950. sign = self._sign ^ other._sign
  951. if self._is_special or other._is_special:
  952. ans = self._check_nans(other, context)
  953. if ans:
  954. if divmod:
  955. return (ans, ans)
  956. return ans
  957. if self._isinfinity() and other._isinfinity():
  958. if divmod:
  959. return (context._raise_error(InvalidOperation,
  960. '(+-)INF // (+-)INF'),
  961. context._raise_error(InvalidOperation,
  962. '(+-)INF % (+-)INF'))
  963. return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
  964. if self._isinfinity():
  965. if divmod == 1:
  966. return (Infsign[sign],
  967. context._raise_error(InvalidOperation, 'INF % x'))
  968. elif divmod == 2:
  969. return (Infsign[sign], NaN)
  970. elif divmod == 3:
  971. return (Infsign[sign],
  972. context._raise_error(InvalidOperation, 'INF % x'))
  973. return Infsign[sign]
  974. if other._isinfinity():
  975. if divmod:
  976. return (Decimal((sign, (0,), 0)), Decimal(self))
  977. context._raise_error(Clamped, 'Division by infinity')
  978. return Decimal((sign, (0,), context.Etiny()))
  979. # Special cases for zeroes
  980. if not self and not other:
  981. if divmod:
  982. return context._raise_error(DivisionUndefined, '0 / 0', 1)
  983. return context._raise_error(DivisionUndefined, '0 / 0')
  984. if not self:
  985. if divmod:
  986. otherside = Decimal(self)
  987. otherside._exp = min(self._exp, other._exp)
  988. return (Decimal((sign, (0,), 0)), otherside)
  989. exp = self._exp - other._exp
  990. if exp < context.Etiny():
  991. exp = context.Etiny()
  992. context._raise_error(Clamped, '0e-x / y')
  993. if exp > context.Emax:
  994. exp = context.Emax
  995. context._raise_error(Clamped, '0e+x / y')
  996. return Decimal( (sign, (0,), exp) )
  997. if not other:
  998. if divmod:
  999. return context._raise_error(DivisionByZero, 'divmod(x,0)',
  1000. sign, 1)
  1001. return context._raise_error(DivisionByZero, 'x / 0', sign)
  1002. #OK, so neither = 0, INF or NaN
  1003. shouldround = context._rounding_decision == ALWAYS_ROUND
  1004. #If we're dividing into ints, and self < other, stop.
  1005. #self.__abs__(0) does not round.
  1006. if divmod and (self.__abs__(0, context) < other.__abs__(0, context)):
  1007. if divmod == 1 or divmod == 3:
  1008. exp = min(self._exp, other._exp)
  1009. ans2 = self._rescale(exp, context=context, watchexp=0)
  1010. if shouldround:
  1011. ans2 = ans2._fix(context)
  1012. return (Decimal( (sign, (0,), 0) ),
  1013. ans2)
  1014. elif divmod == 2:
  1015. #Don't round the mod part, if we don't need it.
  1016. return (Decimal( (sign, (0,), 0) ), Decimal(self))
  1017. op1 = _WorkRep(self)
  1018. op2 = _WorkRep(other)
  1019. op1, op2, adjust = _adjust_coefficients(op1, op2)
  1020. res = _WorkRep( (sign, 0, (op1.exp - op2.exp)) )
  1021. if divmod and res.exp > context.prec + 1:
  1022. return context._raise_error(DivisionImpossible)
  1023. prec_limit = 10 ** context.prec
  1024. while 1:
  1025. while op2.int <= op1.int:
  1026. res.int += 1
  1027. op1.int -= op2.int
  1028. if res.exp == 0 and divmod:
  1029. if res.int >= prec_limit and shouldround:
  1030. return context._raise_error(DivisionImpossible)
  1031. otherside = Decimal(op1)
  1032. frozen = context._ignore_all_flags()
  1033. exp = min(self._exp, other._exp)
  1034. otherside = otherside._rescale(exp, context=context, watchexp=0)
  1035. context._regard_flags(*frozen)
  1036. if shouldround:
  1037. otherside = otherside._fix(context)
  1038. return (Decimal(res), otherside)
  1039. if op1.int == 0 and adjust >= 0 and not divmod:
  1040. break
  1041. if res.int >= prec_limit and shouldround:
  1042. if divmod:
  1043. return context._raise_error(DivisionImpossible)
  1044. shouldround=1
  1045. # Really, the answer is a bit higher, so adding a one to
  1046. # the end will make sure the rounding is right.
  1047. if op1.int != 0:
  1048. res.int *= 10
  1049. res.int += 1
  1050. res.exp -= 1
  1051. break
  1052. res.int *= 10
  1053. res.exp -= 1
  1054. adjust += 1
  1055. op1.int *= 10
  1056. op1.exp -= 1
  1057. if res.exp == 0 and divmod and op2.int > op1.int:
  1058. #Solves an error in precision. Same as a previous block.
  1059. if res.int >= prec_limit and shouldround:
  1060. return context._raise_error(DivisionImpossible)
  1061. otherside = Decimal(op1)
  1062. frozen = context._ignore_all_flags()
  1063. exp = min(self._exp, other._exp)
  1064. otherside = otherside._rescale(exp, context=context)
  1065. context._regard_flags(*frozen)
  1066. return (Decimal(res), otherside)
  1067. ans = Decimal(res)
  1068. if shouldround:
  1069. ans = ans._fix(context)
  1070. return ans
  1071. def __rdiv__(self, other, context=None):
  1072. """Swaps self/other and returns __div__."""
  1073. other = _convert_other(other)
  1074. return other.__div__(self, context=context)
  1075. __rtruediv__ = __rdiv__
  1076. def __divmod__(self, other, context=None):
  1077. """
  1078. (self // other, self % other)
  1079. """
  1080. return self._divide(other, 1, context)
  1081. def __rdivmod__(self, other, context=None):
  1082. """Swaps self/other and returns __divmod__."""
  1083. other = _convert_other(other)
  1084. return other.__divmod__(self, context=context)
  1085. def __mod__(self, other, context=None):
  1086. """
  1087. self % other
  1088. """
  1089. other = _convert_other(other)
  1090. if self._is_special or other._is_special:
  1091. ans = self._check_nans(other, context)
  1092. if ans:
  1093. return ans
  1094. if self and not other:
  1095. return context._raise_error(InvalidOperation, 'x % 0')
  1096. return self._divide(other, 3, context)[1]
  1097. def __rmod__(self, other, context=None):
  1098. """Swaps self/other and returns __mod__."""
  1099. other = _convert_other(other)
  1100. return other.__mod__(self, context=context)
  1101. def remainder_near(self, other, context=None):
  1102. """
  1103. Remainder nearest to 0- abs(remainder-near) <= other/2
  1104. """
  1105. other = _convert_other(other)
  1106. if self._is_special or other._is_special:
  1107. ans = self._check_nans(other, context)
  1108. if ans:
  1109. return ans
  1110. if self and not other:
  1111. return context._raise_error(InvalidOperation, 'x % 0')
  1112. if context is None:
  1113. context = getcontext()
  1114. # If DivisionImpossible causes an error, do not leave Rounded/Inexact
  1115. # ignored in the calling function.
  1116. context = context._shallow_copy()
  1117. flags = context._ignore_flags(Rounded, Inexact)
  1118. #keep DivisionImpossible flags
  1119. (side, r) = self.__divmod__(other, context=context)
  1120. if r._isnan():
  1121. context._regard_flags(*flags)
  1122. return r
  1123. context = context._shallow_copy()
  1124. rounding = context._set_rounding_decision(NEVER_ROUND)
  1125. if other._sign:
  1126. comparison = other.__div__(Decimal(-2), context=context)
  1127. else:
  1128. comparison = other.__div__(Decimal(2), context=context)
  1129. context._set_rounding_decision(rounding)
  1130. context._regard_flags(*flags)
  1131. s1, s2 = r._sign, comparison._sign
  1132. r._sign, comparison._sign = 0, 0
  1133. if r < comparison:
  1134. r._sign, comparison._sign = s1, s2
  1135. #Get flags now
  1136. self.__divmod__(other, context=context)
  1137. return r._fix(context)
  1138. r._sign, comparison._sign = s1, s2
  1139. rounding = context._set_rounding_decision(NEVER_ROUND)
  1140. (side, r) = self.__divmod__(other, context=context)
  1141. context._set_rounding_decision(rounding)
  1142. if r._isnan():
  1143. return r
  1144. decrease = not side._iseven()
  1145. rounding = context._set_rounding_decision(NEVER_ROUND)
  1146. side = side.__abs__(context=context)
  1147. context._set_rounding_decision(rounding)
  1148. s1, s2 = r._sign, comparison._sign
  1149. r._sign, comparison._sign = 0, 0
  1150. if r > comparison or decrease and r == comparison:
  1151. r._sign, comparison._sign = s1, s2
  1152. context.prec += 1
  1153. if len(side.__add__(Decimal(1), context=context)._int) >= context.prec:
  1154. context.prec -= 1
  1155. return context._raise_error(DivisionImpossible)[1]
  1156. context.prec -= 1
  1157. if self._sign == other._sign:
  1158. r = r.__sub__(other, context=context)
  1159. else:
  1160. r = r.__add__(other, context=context)
  1161. else:
  1162. r._sign, comparison._sign = s1, s2
  1163. return r._fix(context)
  1164. def __floordiv__(self, other, context=None):
  1165. """self // other"""
  1166. return self._divide(other, 2, context)[0]
  1167. def __rfloordiv__(self, other, context=None):
  1168. """Swaps self/other and returns __floordiv__."""
  1169. other = _convert_other(other)
  1170. return other.__floordiv__(self, context=context)
  1171. def __float__(self):
  1172. """Float representation."""
  1173. return float(str(self))
  1174. def __int__(self):
  1175. """Converts self to an int, truncating if necessary."""
  1176. if self._is_special:
  1177. if self._isnan():
  1178. context = getcontext()
  1179. return context._raise_error(InvalidContext)
  1180. elif self._isinfinity():
  1181. raise OverflowError, "Cannot convert infinity to long"
  1182. if self._exp >= 0:
  1183. s = ''.join(map(str, self._int)) + '0'*self._exp
  1184. else:
  1185. s = ''.join(map(str, self._int))[:self._exp]
  1186. if s == '':
  1187. s = '0'
  1188. sign = '-'*self._sign
  1189. return int(sign + s)
  1190. def __long__(self):
  1191. """Converts to a long.
  1192. Equivalent to long(int(self))
  1193. """
  1194. return long(self.__int__())
  1195. def _fix(self, context):
  1196. """Round if it is necessary to keep self within prec precision.
  1197. Rounds and fixes the exponent. Does not raise on a sNaN.
  1198. Arguments:
  1199. self - Decimal instance
  1200. context - context used.
  1201. """
  1202. if self._is_special:
  1203. return self
  1204. if context is None:
  1205. context = getcontext()
  1206. prec = context.prec
  1207. ans = self._fixexponents(context)
  1208. if len(ans._int) > prec:
  1209. ans = ans._round(prec, context=context)
  1210. ans = ans._fixexponents(context)
  1211. return ans
  1212. def _fixexponents(self, context):
  1213. """Fix the exponents and return a copy with the exponent in bounds.
  1214. Only call if known to not be a special value.
  1215. """
  1216. folddown = context._clamp
  1217. Emin = context.Emin
  1218. ans = self
  1219. ans_adjusted = ans.adjusted()
  1220. if ans_adjusted < Emin:
  1221. Etiny = context.Etiny()
  1222. if ans._exp < Etiny:
  1223. if not ans:
  1224. ans = Decimal(self)
  1225. ans._exp = Etiny
  1226. context._raise_error(Clamped)
  1227. return ans
  1228. ans = ans._rescale(Etiny, context=context)
  1229. #It isn't zero, and exp < Emin => subnormal
  1230. context._raise_error(Subnormal)
  1231. if context.flags[Inexact]:
  1232. context._raise_error(Underflow)
  1233. else:
  1234. if ans:
  1235. #Only raise subnormal if non-zero.
  1236. context._raise_error(Subnormal)
  1237. else:
  1238. Etop = context.Etop()
  1239. if folddown and ans._exp > Etop:
  1240. context._raise_error(Clamped)
  1241. ans = ans._rescale(Etop, context=context)
  1242. else:
  1243. Emax = context.Emax
  1244. if ans_adjusted > Emax:
  1245. if not ans:
  1246. ans = Decimal(self)
  1247. ans._exp = Emax
  1248. context._raise_error(Clamped)
  1249. return ans
  1250. context._raise_error(Inexact)
  1251. context._raise_error(Rounded)
  1252. return context._raise_error(Overflow, 'above Emax', ans._sign)
  1253. return ans
  1254. def _round(self, prec=None, rounding=None, context=None):
  1255. """Returns a rounded version of self.
  1256. You can specify the precision or rounding method. Otherwise, the
  1257. context determines it.
  1258. """
  1259. if self._is_special:
  1260. ans = self._check_nans(context=context)
  1261. if ans:
  1262. return ans
  1263. if self._isinfinity():
  1264. return Decimal(self)
  1265. if context is None:
  1266. context = getcontext()
  1267. if rounding is None:
  1268. rounding = context.rounding
  1269. if prec is None:
  1270. prec = context.prec
  1271. if not self:
  1272. if prec <= 0:
  1273. dig = (0,)
  1274. exp = len(self._int) - prec + self._exp
  1275. else:
  1276. dig = (0,) * prec
  1277. exp = len(self._int) + self._exp - prec
  1278. ans = Decimal((self._sign, dig, exp))
  1279. context._raise_error(Rounded)
  1280. return ans
  1281. if prec == 0:
  1282. temp = Decimal(self)
  1283. temp._int = (0,)+temp._int
  1284. prec = 1
  1285. elif prec < 0:
  1286. exp = self._exp + len(self._int) - prec - 1
  1287. temp = Decimal( (self._sign, (0, 1), exp))
  1288. prec = 1
  1289. else:
  1290. temp = Decimal(self)
  1291. numdigits = len(temp._int)
  1292. if prec == numdigits:
  1293. return temp
  1294. # See if we need to extend precision
  1295. expdiff = prec - numdigits
  1296. if expdiff > 0:
  1297. tmp = list(temp._int)
  1298. tmp.extend([0] * expdiff)
  1299. ans = Decimal( (temp._sign, tmp, temp._exp - expdiff))
  1300. return ans
  1301. #OK, but maybe all the lost digits are 0.
  1302. lostdigits = self._int[expdiff:]
  1303. if lostdigits == (0,) * len(lostdigits):
  1304. ans = Decimal( (temp._sign, temp._int[:prec], temp._exp - expdiff))
  1305. #Rounded, but not Inexact
  1306. context._raise_error(Rounded)
  1307. return ans
  1308. # Okay, let's round and lose data
  1309. this_function = getattr(temp, self._pick_rounding_function[rounding])
  1310. #Now we've got the rounding function
  1311. if prec != context.prec:
  1312. context = context._shallow_copy()
  1313. context.prec = prec
  1314. ans = this_function(prec, expdiff, context)
  1315. context._raise_error(Rounded)
  1316. context._raise_error(Inexact, 'Changed in rounding')
  1317. return ans
  1318. _pick_rounding_function = {}
  1319. def _round_down(self, prec, expdiff, context):
  1320. """Also known as round-towards-0, truncate."""
  1321. return Decimal( (self._sign, self._int[:prec], self._exp - expdiff) )
  1322. def _round_half_up(self, prec, expdiff, context, tmp = None):
  1323. """Rounds 5 up (away from 0)"""
  1324. if tmp is None:
  1325. tmp = Decimal( (self._sign,self._int[:prec], self._exp - expdiff))
  1326. if self._int[prec] >= 5:
  1327. tmp = tmp._increment(round=0, context=context)
  1328. if len(tmp._int) > prec:
  1329. return Decimal( (tmp._sign, tmp._int[:-1], tmp._exp + 1))
  1330. return tmp
  1331. def _round_half_even(self, prec, expdiff, context):
  1332. """Round 5 to even, rest to nearest."""
  1333. tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff))
  1334. half = (self._int[prec] == 5)
  1335. if half:
  1336. for digit in self._int[prec+1:]:
  1337. if digit != 0:
  1338. half = 0
  1339. break
  1340. if half:
  1341. if self._int[prec-1] & 1 == 0:
  1342. return tmp
  1343. return self._round_half_up(prec, expdiff, context, tmp)
  1344. def _round_half_down(self, prec, expdiff, context):
  1345. """Round 5 down"""
  1346. tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff))
  1347. half = (self._int[prec] == 5)
  1348. if half:
  1349. for digit in self._int[prec+1:]:
  1350. if digit != 0:
  1351. half = 0
  1352. break
  1353. if half:
  1354. return tmp
  1355. return self._round_half_up(prec, expdiff, context, tmp)
  1356. def _round_up(self, prec, expdiff, context):
  1357. """Rounds away from 0."""
  1358. tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff) )
  1359. for digit in self._int[prec:]:
  1360. if digit != 0:
  1361. tmp = tmp._increment(round=1, context=context)
  1362. if len(tmp._int) > prec:
  1363. return Decimal( (tmp._sign, tmp._int[:-1], tmp._exp + 1))
  1364. else:
  1365. return tmp
  1366. return tmp
  1367. def _round_ceiling(self, prec, expdiff, context):
  1368. """Rounds up (not away from 0 if negative.)"""
  1369. if self._sign:
  1370. return self._round_down(prec, expdiff, context)
  1371. else:
  1372. return self._round_up(prec, expdiff, context)
  1373. def _round_floor(self, prec, expdiff, context):
  1374. """Rounds down (not towards 0 if negative)"""
  1375. if not self._sign:
  1376. return self._round_down(prec, expdiff, context)
  1377. else:
  1378. return self._round_up(prec, expdiff, context)
  1379. def __pow__(self, n, modulo = None, context=None):
  1380. """Return self ** n (mod modulo)
  1381. If modulo is None (default), don't take it mod modulo.
  1382. """
  1383. n = _convert_other(n)
  1384. if context is None:
  1385. context = getcontext()
  1386. if self._is_special or n._is_special or n.adjusted() > 8:
  1387. #Because the spot << doesn't work with really big exponents
  1388. if n._isinfinity() or n.adjusted() > 8:
  1389. return context._raise_error(InvalidOperation, 'x ** INF')
  1390. ans = self._check_nans(n, context)
  1391. if ans:
  1392. return ans
  1393. if not n._isinteger():
  1394. return context._raise_error(InvalidOperation, 'x ** (non-integer)')
  1395. if not self and not n:
  1396. return context._raise_error(InvalidOperation, '0 ** 0')
  1397. if not n:
  1398. return Decimal(1)
  1399. if self == Decimal(1):
  1400. return Decimal(1)
  1401. sign = self._sign and not n._iseven()
  1402. n = int(n)
  1403. if self._isinfinity():
  1404. if modulo:
  1405. return context._raise_error(InvalidOperation, 'INF % x')
  1406. if n > 0:
  1407. return Infsign[sign]
  1408. return Decimal( (sign, (0,), 0) )
  1409. #with ludicrously large exponent, just raise an overflow and return inf.
  1410. if not modulo and n > 0 and (self._exp + len(self._int) - 1) * n > context.Emax \
  1411. and self:
  1412. tmp = Decimal('inf')
  1413. tmp._sign = sign
  1414. context._raise_error(Rounded)
  1415. context._raise_error(Inexact)
  1416. context._raise_error(Overflow, 'Big power', sign)
  1417. return tmp
  1418. elength = len(str(abs(n)))
  1419. firstprec = context.prec
  1420. if not modulo and firstprec + elength + 1 > DefaultContext.Emax:
  1421. return context._raise_error(Overflow, 'Too much precision.', sign)
  1422. mul = Decimal(self)
  1423. val = Decimal(1)
  1424. context = context._shallow_copy()
  1425. context.prec = firstprec + elength + 1
  1426. if n < 0:
  1427. #n is a long now, not Decimal instance
  1428. n = -n
  1429. mul = Decimal(1).__div__(mul, context=context)
  1430. spot = 1
  1431. while spot <= n:
  1432. spot <<= 1
  1433. spot >>= 1
  1434. #Spot is the highest power of 2 less than n
  1435. while spot:
  1436. val = val.__mul__(val, context=context)
  1437. if val._isinfinity():
  1438. val = Infsign[sign]
  1439. break
  1440. if spot & n:
  1441. val = val.__mul__(mul, context=context)
  1442. if modulo is not None:
  1443. val = val.__mod__(modulo, context=context)
  1444. spot >>= 1
  1445. context.prec = firstprec
  1446. if context._rounding_decision == ALWAYS_ROUND:
  1447. return val._fix(context)
  1448. return val
  1449. def __rpow__(self, other, context=None):
  1450. """Swaps self/other and returns __pow__."""
  1451. other = _convert_other(other)
  1452. return other.__pow__(self, context=context)
  1453. def normalize(self, context=None):
  1454. """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
  1455. if self._is_special:
  1456. ans = self._check_nans(context=context)
  1457. if ans:
  1458. return ans
  1459. dup = self._fix(context)
  1460. if dup._isinfinity():
  1461. return dup
  1462. if not dup:
  1463. return Decimal( (dup._sign, (0,), 0) )
  1464. end = len(dup._int)
  1465. exp = dup._exp
  1466. while dup._int[end-1] == 0:
  1467. exp += 1
  1468. end -= 1
  1469. return Decimal( (dup._sign, dup._int[:end], exp) )
  1470. def quantize(self, exp, rounding=None, context=None, watchexp=1):
  1471. """Quantize self so its exponent is the same as that of exp.
  1472. Similar to self._rescale(exp._exp) but with error checking.
  1473. """
  1474. if self._is_special or exp._is_special:
  1475. ans = self._check_nans(exp, context)
  1476. if ans:
  1477. return ans
  1478. if exp._isinfinity() or self._isinfinity():
  1479. if exp._isinfinity() and self._isinfinity():
  1480. return self #if both are inf, it is OK
  1481. if context is None:
  1482. context = getcontext()
  1483. return context._raise_error(InvalidOperation,
  1484. 'quantize with one INF')
  1485. return self._rescale(exp._exp, rounding, context, watchexp)
  1486. def same_quantum(self, other):
  1487. """Test whether self and other have the same exponent.
  1488. same as self._exp == other._exp, except NaN == sNaN
  1489. """
  1490. if self._is_special or other._is_special:
  1491. if self._isnan() or other._isnan():
  1492. return self._isnan() and other._isnan() and True
  1493. if self._isinfinity() or other._isinfinity():
  1494. return self._isinfinity() and other._isinfinity() and True
  1495. return self._exp == other._exp
  1496. def _rescale(self, exp, rounding=None, context=None, watchexp=1):
  1497. """Rescales so that the exponent is exp.
  1498. exp = exp to scale to (an integer)
  1499. rounding = rounding version
  1500. watchexp: if set (default) an error is returned if exp is greater
  1501. than Emax or less than Etiny.
  1502. """
  1503. if context is None:
  1504. context = getcontext()
  1505. if self._is_special:
  1506. if self._isinfinity():
  1507. return context._raise_error(InvalidOperation, 'rescale with an INF')
  1508. ans = self._check_nans(context=context)
  1509. if ans:
  1510. return ans
  1511. if watchexp and (context.Emax < exp or context.Etiny() > exp):
  1512. return context._raise_error(InvalidOperation, 'rescale(a, INF)')
  1513. if not self:
  1514. ans = Decimal(self)
  1515. ans._int = (0,)
  1516. ans._exp = exp
  1517. return ans
  1518. diff = self._exp - exp
  1519. digits = len(self._int) + diff
  1520. if watchexp and digits > context.prec:
  1521. return context._raise_error(InvalidOperation, 'Rescale > prec')
  1522. tmp = Decimal(self)
  1523. tmp._int = (0,) + tmp._int
  1524. digits += 1
  1525. if digits < 0:
  1526. tmp._exp = -digits + tmp._exp
  1527. tmp._int = (0,1)
  1528. digits = 1
  1529. tmp = tmp._round(digits, rounding, context=context)
  1530. if tmp._int[0] == 0 and len(tmp._int) > 1:
  1531. tmp._int = tmp._int[1:]
  1532. tmp._exp = exp
  1533. tmp_adjusted = tmp.adjusted()
  1534. if tmp and tmp_adjusted < context.Emin:
  1535. context._raise_error(Subnormal)
  1536. elif tmp and tmp_adjusted > context.Emax:
  1537. return context._raise_error(InvalidOperation, 'rescale(a, INF)')
  1538. return tmp
  1539. def to_integral(self, rounding=None, context=None):
  1540. """Rounds to the nearest integer, without raising inexact, rounded."""
  1541. if self._is_special:
  1542. ans = self._check_nans(context=context)
  1543. if ans:
  1544. return ans
  1545. if self._exp >= 0:
  1546. return self
  1547. if context is None:
  1548. context = getcontext()
  1549. flags = context._ignore_flags(Rounded, Inexact)
  1550. ans = self._rescale(0, rounding, context=context)
  1551. context._regard_flags(flags)
  1552. return ans
  1553. def sqrt(self, context=None):
  1554. """Return the square root of self.
  1555. Uses a converging algorithm (Xn+1 = 0.5*(Xn + self / Xn))
  1556. Should quadratically approach the right answer.
  1557. """
  1558. if self._is_special:
  1559. ans = self._check_nans(context=context)
  1560. if ans:
  1561. return ans
  1562. if self._isinfinity() and self._sign == 0:
  1563. return Decimal(self)
  1564. if not self:
  1565. #exponent = self._exp / 2, using round_down.
  1566. #if self._exp < 0:
  1567. # exp = (self._exp+1) // 2
  1568. #else:
  1569. exp = (self._exp) // 2
  1570. if self._sign == 1:
  1571. #sqrt(-0) = -0
  1572. return Decimal( (1, (0,), exp))
  1573. else:
  1574. return Decimal( (0, (0,), exp))
  1575. if context is None:
  1576. context = getcontext()
  1577. if self._sign == 1:
  1578. return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
  1579. tmp = Decimal(self)
  1580. expadd = tmp._exp // 2
  1581. if tmp._exp & 1:
  1582. tmp._int += (0,)
  1583. tmp._exp = 0
  1584. else:
  1585. tmp._exp = 0
  1586. context = context._shallow_copy()
  1587. flags = context._ignore_all_flags()
  1588. firstprec = context.prec
  1589. context.prec = 3
  1590. if tmp.adjusted() & 1 == 0:
  1591. ans = Decimal( (0, (8,1,9), tmp.adjusted() - 2) )
  1592. ans = ans.__add__(tmp.__mul__(Decimal((0, (2,5,9), -2)),
  1593. context=context), context=context)
  1594. ans._exp -= 1 + tmp.adjusted() // 2
  1595. else:
  1596. ans = Decimal( (0, (2,5,9), tmp._exp + len(tmp._int)- 3) )
  1597. ans = ans.__add__(tmp.__mul__(Decimal((0, (8,1,9), -3)),
  1598. context=context), context=context)
  1599. ans._exp -= 1 + tmp.adjusted() // 2
  1600. #ans is now a linear approximation.
  1601. Emax, Emin = context.Emax, context.Emin
  1602. context.Emax, context.Emin = DefaultContext.Emax, DefaultContext.Emin
  1603. half = Decimal('0.5')
  1604. maxp = firstprec + 2
  1605. rounding = context._set_rounding(ROUND_HALF_EVEN)
  1606. while 1:
  1607. context.prec = min(2*context.prec - 2, maxp)
  1608. ans = half.__mul__(ans.__add__(tmp.__div__(ans, context=context),
  1609. context=context), context=context)
  1610. if context.prec == maxp:
  1611. break
  1612. #round to the answer's precision-- the only error can be 1 ulp.
  1613. context.prec = firstprec
  1614. prevexp = ans.adjusted()
  1615. ans = ans._round(context=context)
  1616. #Now, check if the other last digits are better.
  1617. context.prec = firstprec + 1
  1618. # In case we rounded up another digit and we should actually go lower.
  1619. if prevexp != ans.adjusted():
  1620. ans._int += (0,)
  1621. ans._exp -= 1
  1622. lower = ans.__sub__(Decimal((0, (5,), ans._exp-1)), context=context)
  1623. context._set_rounding(ROUND_UP)
  1624. if lower.__mul__(lower, context=context) > (tmp):
  1625. ans = ans.__sub__(Decimal((0, (1,), ans._exp)), context=context)
  1626. else:
  1627. upper = ans.__add__(Decimal((0, (5,), ans._exp-1)),context=context)
  1628. context._set_rounding(ROUND_DOWN)
  1629. if upper.__mul__(upper, context=context) < tmp:
  1630. ans = ans.__add__(Decimal((0, (1,), ans._exp)),context=context)
  1631. ans._exp += expadd
  1632. context.prec = firstprec
  1633. context.rounding = rounding
  1634. ans = ans._fix(context)
  1635. rounding = context._set_rounding_decision(NEVER_ROUND)
  1636. if not ans.__mul__(ans, context=context) == self:
  1637. # Only rounded/inexact if here.
  1638. context._regard_flags(flags)
  1639. context._raise_error(Rounded)
  1640. context._raise_error(Inexact)
  1641. else:
  1642. #Exact answer, so let's set the exponent right.
  1643. #if self._exp < 0:
  1644. # exp = (self._exp +1)// 2
  1645. #else:
  1646. exp = self._exp // 2
  1647. context.prec += ans._exp - exp
  1648. ans = ans._rescale(exp, context=context)
  1649. context.prec = firstprec
  1650. context._regard_flags(flags)
  1651. context.Emax, context.Emin = Emax, Emin
  1652. return ans._fix(context)
  1653. def max(self, other, context=None):
  1654. """Returns the larger value.
  1655. like max(self, other) except if one is not a number, returns
  1656. NaN (and signals if one is sNaN). Also rounds.
  1657. """
  1658. other = _convert_other(other)
  1659. if self._is_special or other._is_special:
  1660. # if one operand is a quiet NaN and the other is number, then the
  1661. # number is always returned
  1662. sn = self._isnan()
  1663. on = other._isnan()
  1664. if sn or on:
  1665. if on == 1 and sn != 2:
  1666. return self
  1667. if sn == 1 and on != 2:
  1668. return other
  1669. return self._check_nans(other, context)
  1670. ans = self
  1671. c = self.__cmp__(other)
  1672. if c == 0:
  1673. # if both operands are finite and equal in numerical value
  1674. # then an ordering is applied:
  1675. #
  1676. # if the signs differ then max returns the operand with the
  1677. # positive sign and min returns the operand with the negative sign
  1678. #
  1679. # if the signs are the same then the exponent is used to select
  1680. # the result.
  1681. if self._sign != other._sign:
  1682. if self._sign:
  1683. ans = other
  1684. elif self._exp < other._exp and not self._sign:
  1685. ans = other
  1686. elif self._exp > other._exp and self._sign:
  1687. ans = other
  1688. elif c == -1:
  1689. ans = other
  1690. if context is None:
  1691. context = getcontext()
  1692. if context._rounding_decision == ALWAYS_ROUND:
  1693. return ans._fix(context)
  1694. return ans
  1695. def min(self, other, context=None):
  1696. """Returns the smaller value.
  1697. like min(self, other) except if one is not a number, returns
  1698. NaN (and signals if one is sNaN). Also rounds.
  1699. """
  1700. other = _convert_other(other)
  1701. if self._is_special or other._is_special:
  1702. # if one operand is a quiet NaN and the other is number, then the
  1703. # number is always returned
  1704. sn = self._isnan()
  1705. on = other._isnan()
  1706. if sn or on:
  1707. if on == 1 and sn != 2:
  1708. return self
  1709. if sn == 1 and on != 2:
  1710. return other
  1711. return self._check_nans(other, context)
  1712. ans = self
  1713. c = self.__cmp__(other)
  1714. if c == 0:
  1715. # if both operands are finite and equal in numerical value
  1716. # then an ordering is applied:
  1717. #
  1718. # if the signs differ then max returns the operand with the
  1719. # positive sign and min returns the operand with the negative sign
  1720. #
  1721. # if the signs are the same then the exponent is used to select
  1722. # the result.
  1723. if self._sign != other._sign:
  1724. if other._sign:
  1725. ans = other
  1726. elif self._exp > other._exp and not self._sign:
  1727. ans = other
  1728. elif self._exp < other._exp and self._sign:
  1729. ans = other
  1730. elif c == 1:
  1731. ans = other
  1732. if context is None:
  1733. context = getcontext()
  1734. if context._rounding_decision == ALWAYS_ROUND:
  1735. return ans._fix(context)
  1736. return ans
  1737. def _isinteger(self):
  1738. """Returns whether self is an integer"""
  1739. if self._exp >= 0:
  1740. return True
  1741. rest = self._int[self._exp:]
  1742. return rest == (0,)*len(rest)
  1743. def _iseven(self):
  1744. """Returns 1 if self is even. Assumes self is an integer."""
  1745. if self._exp > 0:
  1746. return 1
  1747. return self._int[-1+self._exp] & 1 == 0
  1748. def adjusted(self):
  1749. """Return the adjusted exponent of self"""
  1750. try:
  1751. return self._exp + len(self._int) - 1
  1752. #If NaN or Infinity, self._exp is string
  1753. except TypeError:
  1754. return 0
  1755. # support for pickling, copy, and deepcopy
  1756. def __reduce__(self):
  1757. return (self.__class__, (str(self),))
  1758. def __copy__(self):
  1759. if type(self) == Decimal:
  1760. return self # I'm immutable; therefore I am my own clone
  1761. return self.__class__(str(self))
  1762. def __deepcopy__(self, memo):
  1763. if type(self) == Decimal:
  1764. return self # My components are also immutable
  1765. return self.__class__(str(self))
  1766. ##### Context class ###########################################
  1767. # get rounding method function:
  1768. rounding_functions = [name for name in Decimal.__dict__.keys() if name.startswith('_round_')]
  1769. for name in rounding_functions:
  1770. #name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
  1771. globalname = name[1:].upper()
  1772. val = globals()[globalname]
  1773. Decimal._pick_rounding_function[val] = name
  1774. del name, val, globalname, rounding_functions
  1775. class Context(object):
  1776. """Contains the context for a Decimal instance.
  1777. Contains:
  1778. prec - precision (for use in rounding, division, square roots..)
  1779. rounding - rounding type. (how you round)
  1780. _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round?
  1781. traps - If traps[exception] = 1, then the exception is
  1782. raised when it is caused. Otherwise, a value is
  1783. substituted in.
  1784. flags - When an exception is caused, flags[exception] is incremented.
  1785. (Whether or not the trap_enabler is set)
  1786. Should be reset by user of Decimal instance.
  1787. Emin - Minimum exponent
  1788. Emax - Maximum exponent
  1789. capitals - If 1, 1*10^1 is printed as 1E+1.
  1790. If 0, printed as 1e1
  1791. _clamp - If 1, change exponents if too high (Default 0)
  1792. """
  1793. def __init__(self, prec=None, rounding=None,
  1794. traps=None, flags=None,
  1795. _rounding_decision=None,
  1796. Emin=None, Emax=None,
  1797. capitals=None, _clamp=0,
  1798. _ignored_flags=None):
  1799. if flags is None:
  1800. flags = []
  1801. if _ignored_flags is None:
  1802. _ignored_flags = []
  1803. if not isinstance(flags, dict):
  1804. flags = dict([(s,s in flags) for s in _signals])
  1805. del s
  1806. if traps is not None and not isinstance(traps, dict):
  1807. traps = dict([(s,s in traps) for s in _signals])
  1808. del s
  1809. for name, val in locals().items():
  1810. if val is None:
  1811. setattr(self, name, copy.copy(getattr(DefaultContext, name)))
  1812. else:
  1813. setattr(self, name, val)
  1814. del self.self
  1815. def __repr__(self):
  1816. """Show the current context."""
  1817. s = []
  1818. s.append('Context(prec=%(prec)d, rounding=%(rounding)s, Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d' % vars(self))
  1819. s.append('flags=[' + ', '.join([f.__name__ for f, v in self.flags.items() if v]) + ']')
  1820. s.append('traps=[' + ', '.join([t.__name__ for t, v in self.traps.items() if v]) + ']')
  1821. return ', '.join(s) + ')'
  1822. def clear_flags(self):
  1823. """Reset all flags to zero"""
  1824. for flag in self.flags:
  1825. self.flags[flag] = 0
  1826. def _shallow_copy(self):
  1827. """Returns a shallow copy from self."""
  1828. nc = Context(self.prec, self.rounding, self.traps, self.flags,
  1829. self._rounding_decision, self.Emin, self.Emax,
  1830. self.capitals, self._clamp, self._ignored_flags)
  1831. return nc
  1832. def copy(self):
  1833. """Returns a deep copy from self."""
  1834. nc = Context(self.prec, self.rounding, self.traps.copy(), self.flags.copy(),
  1835. self._rounding_decision, self.Emin, self.Emax,
  1836. self.capitals, self._clamp, self._ignored_flags)
  1837. return nc
  1838. __copy__ = copy
  1839. def _raise_error(self, condition, explanation = None, *args):
  1840. """Handles an error
  1841. If the flag is in _ignored_flags, returns the default response.
  1842. Otherwise, it increments the flag, then, if the corresponding
  1843. trap_enabler is set, it reaises the exception. Otherwise, it returns
  1844. the default value after incrementing the flag.
  1845. """
  1846. error = _condition_map.get(condition, condition)
  1847. if error in self._ignored_flags:
  1848. #Don't touch the flag
  1849. return error().handle(self, *args)
  1850. self.flags[error] += 1
  1851. if not self.traps[error]:
  1852. #The errors define how to handle themselves.
  1853. return condition().handle(self, *args)
  1854. # Errors should only be risked on copies of the context
  1855. #self._ignored_flags = []
  1856. raise error, explanation
  1857. def _ignore_all_flags(self):
  1858. """Ignore all flags, if they are raised"""
  1859. return self._ignore_flags(*_signals)
  1860. def _ignore_flags(self, *flags):
  1861. """Ignore the flags, if they are raised"""
  1862. # Do not mutate-- This way, copies of a context leave the original
  1863. # alone.
  1864. self._ignored_flags = (self._ignored_flags + list(flags))
  1865. return list(flags)
  1866. def _regard_flags(self, *flags):
  1867. """Stop ignoring the flags, if they are raised"""
  1868. if flags and isinstance(flags[0], (tuple,list)):
  1869. flags = flags[0]
  1870. for flag in flags:
  1871. self._ignored_flags.remove(flag)
  1872. def __hash__(self):
  1873. """A Context cannot be hashed."""
  1874. # We inherit object.__hash__, so we must deny this explicitly
  1875. raise TypeError, "Cannot hash a Context."
  1876. def Etiny(self):
  1877. """Returns Etiny (= Emin - prec + 1)"""
  1878. return int(self.Emin - self.prec + 1)
  1879. def Etop(self):
  1880. """Returns maximum exponent (= Emax - prec + 1)"""
  1881. return int(self.Emax - self.prec + 1)
  1882. def _set_rounding_decision(self, type):
  1883. """Sets the rounding decision.
  1884. Sets the rounding decision, and returns the current (previous)
  1885. rounding decision. Often used like:
  1886. context = context._shallow_copy()
  1887. # That so you don't change the calling context
  1888. # if an error occurs in the middle (say DivisionImpossible is raised).
  1889. rounding = context._set_rounding_decision(NEVER_ROUND)
  1890. instance = instance / Decimal(2)
  1891. context._set_rounding_decision(rounding)
  1892. This will make it not round for that operation.
  1893. """
  1894. rounding = self._rounding_decision
  1895. self._rounding_decision = type
  1896. return rounding
  1897. def _set_rounding(self, type):
  1898. """Sets the rounding type.
  1899. Sets the rounding type, and returns the current (previous)
  1900. rounding type. Often used like:
  1901. context = context.copy()
  1902. # so you don't change the calling context
  1903. # if an error occurs in the middle.
  1904. rounding = context._set_rounding(ROUND_UP)
  1905. val = self.__sub__(other, context=context)
  1906. context._set_rounding(rounding)
  1907. This will make it round up for that operation.
  1908. """
  1909. rounding = self.rounding
  1910. self.rounding= type
  1911. return rounding
  1912. def create_decimal(self, num='0'):
  1913. """Creates a new Decimal instance but using self as context."""
  1914. d = Decimal(num, context=self)
  1915. return d._fix(self)
  1916. #Methods
  1917. def abs(self, a):
  1918. """Returns the absolute value of the operand.
  1919. If the operand is negative, the result is the same as using the minus
  1920. operation on the operand. Otherwise, the result is the same as using
  1921. the plus operation on the operand.
  1922. >>> ExtendedContext.abs(Decimal('2.1'))
  1923. Decimal("2.1")
  1924. >>> ExtendedContext.abs(Decimal('-100'))
  1925. Decimal("100")
  1926. >>> ExtendedContext.abs(Decimal('101.5'))
  1927. Decimal("101.5")
  1928. >>> ExtendedContext.abs(Decimal('-101.5'))
  1929. Decimal("101.5")
  1930. """
  1931. return a.__abs__(context=self)
  1932. def add(self, a, b):
  1933. """Return the sum of the two operands.
  1934. >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
  1935. Decimal("19.00")
  1936. >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
  1937. Decimal("1.02E+4")
  1938. """
  1939. return a.__add__(b, context=self)
  1940. def _apply(self, a):
  1941. return str(a._fix(self))
  1942. def compare(self, a, b):
  1943. """Compares values numerically.
  1944. If the signs of the operands differ, a value representing each operand
  1945. ('-1' if the operand is less than zero, '0' if the operand is zero or
  1946. negative zero, or '1' if the operand is greater than zero) is used in
  1947. place of that operand for the comparison instead of the actual
  1948. operand.
  1949. The comparison is then effected by subtracting the second operand from
  1950. the first and then returning a value according to the result of the
  1951. subtraction: '-1' if the result is less than zero, '0' if the result is
  1952. zero or negative zero, or '1' if the result is greater than zero.
  1953. >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
  1954. Decimal("-1")
  1955. >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
  1956. Decimal("0")
  1957. >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
  1958. Decimal("0")
  1959. >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
  1960. Decimal("1")
  1961. >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
  1962. Decimal("1")
  1963. >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
  1964. Decimal("-1")
  1965. """
  1966. return a.compare(b, context=self)
  1967. def divide(self, a, b):
  1968. """Decimal division in a specified context.
  1969. >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
  1970. Decimal("0.333333333")
  1971. >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
  1972. Decimal("0.666666667")
  1973. >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
  1974. Decimal("2.5")
  1975. >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
  1976. Decimal("0.1")
  1977. >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
  1978. Decimal("1")
  1979. >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
  1980. Decimal("4.00")
  1981. >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
  1982. Decimal("1.20")
  1983. >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
  1984. Decimal("10")
  1985. >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
  1986. Decimal("1000")
  1987. >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
  1988. Decimal("1.20E+6")
  1989. """
  1990. return a.__div__(b, context=self)
  1991. def divide_int(self, a, b):
  1992. """Divides two numbers and returns the integer part of the result.
  1993. >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
  1994. Decimal("0")
  1995. >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
  1996. Decimal("3")
  1997. >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
  1998. Decimal("3")
  1999. """
  2000. return a.__floordiv__(b, context=self)
  2001. def divmod(self, a, b):
  2002. return a.__divmod__(b, context=self)
  2003. def max(self, a,b):
  2004. """max compares two values numerically and returns the maximum.
  2005. If either operand is a NaN then the general rules apply.
  2006. Otherwise, the operands are compared as as though by the compare
  2007. operation. If they are numerically equal then the left-hand operand
  2008. is chosen as the result. Otherwise the maximum (closer to positive
  2009. infinity) of the two operands is chosen as the result.
  2010. >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
  2011. Decimal("3")
  2012. >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
  2013. Decimal("3")
  2014. >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
  2015. Decimal("1")
  2016. >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
  2017. Decimal("7")
  2018. """
  2019. return a.max(b, context=self)
  2020. def min(self, a,b):
  2021. """min compares two values numerically and returns the minimum.
  2022. If either operand is a NaN then the general rules apply.
  2023. Otherwise, the operands are compared as as though by the compare
  2024. operation. If they are numerically equal then the left-hand operand
  2025. is chosen as the result. Otherwise the minimum (closer to negative
  2026. infinity) of the two operands is chosen as the result.
  2027. >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
  2028. Decimal("2")
  2029. >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
  2030. Decimal("-10")
  2031. >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
  2032. Decimal("1.0")
  2033. >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
  2034. Decimal("7")
  2035. """
  2036. return a.min(b, context=self)
  2037. def minus(self, a):
  2038. """Minus corresponds to unary prefix minus in Python.
  2039. The operation is evaluated using the same rules as subtract; the
  2040. operation minus(a) is calculated as subtract('0', a) where the '0'
  2041. has the same exponent as the operand.
  2042. >>> ExtendedContext.minus(Decimal('1.3'))
  2043. Decimal("-1.3")
  2044. >>> ExtendedContext.minus(Decimal('-1.3'))
  2045. Decimal("1.3")
  2046. """
  2047. return a.__neg__(context=self)
  2048. def multiply(self, a, b):
  2049. """multiply multiplies two operands.
  2050. If either operand is a special value then the general rules apply.
  2051. Otherwise, the operands are multiplied together ('long multiplication'),
  2052. resulting in a number which may be as long as the sum of the lengths
  2053. of the two operands.
  2054. >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
  2055. Decimal("3.60")
  2056. >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
  2057. Decimal("21")
  2058. >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
  2059. Decimal("0.72")
  2060. >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
  2061. Decimal("-0.0")
  2062. >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
  2063. Decimal("4.28135971E+11")
  2064. """
  2065. return a.__mul__(b, context=self)
  2066. def normalize(self, a):
  2067. """normalize reduces an operand to its simplest form.
  2068. Essentially a plus operation with all trailing zeros removed from the
  2069. result.
  2070. >>> ExtendedContext.normalize(Decimal('2.1'))
  2071. Decimal("2.1")
  2072. >>> ExtendedContext.normalize(Decimal('-2.0'))
  2073. Decimal("-2")
  2074. >>> ExtendedContext.normalize(Decimal('1.200'))
  2075. Decimal("1.2")
  2076. >>> ExtendedContext.normalize(Decimal('-120'))
  2077. Decimal("-1.2E+2")
  2078. >>> ExtendedContext.normalize(Decimal('120.00'))
  2079. Decimal("1.2E+2")
  2080. >>> ExtendedContext.normalize(Decimal('0.00'))
  2081. Decimal("0")
  2082. """
  2083. return a.normalize(context=self)
  2084. def plus(self, a):
  2085. """Plus corresponds to unary prefix plus in Python.
  2086. The operation is evaluated using the same rules as add; the
  2087. operation plus(a) is calculated as add('0', a) where the '0'
  2088. has the same exponent as the operand.
  2089. >>> ExtendedContext.plus(Decimal('1.3'))
  2090. Decimal("1.3")
  2091. >>> ExtendedContext.plus(Decimal('-1.3'))
  2092. Decimal("-1.3")
  2093. """
  2094. return a.__pos__(context=self)
  2095. def power(self, a, b, modulo=None):
  2096. """Raises a to the power of b, to modulo if given.
  2097. The right-hand operand must be a whole number whose integer part (after
  2098. any exponent has been applied) has no more than 9 digits and whose
  2099. fractional part (if any) is all zeros before any rounding. The operand
  2100. may be positive, negative, or zero; if negative, the absolute value of
  2101. the power is used, and the left-hand operand is inverted (divided into
  2102. 1) before use.
  2103. If the increased precision needed for the intermediate calculations
  2104. exceeds the capabilities of the implementation then an Invalid operation
  2105. condition is raised.
  2106. If, when raising to a negative power, an underflow occurs during the
  2107. division into 1, the operation is not halted at that point but
  2108. continues.
  2109. >>> ExtendedContext.power(Decimal('2'), Decimal('3'))
  2110. Decimal("8")
  2111. >>> ExtendedContext.power(Decimal('2'), Decimal('-3'))
  2112. Decimal("0.125")
  2113. >>> ExtendedContext.power(Decimal('1.7'), Decimal('8'))
  2114. Decimal("69.7575744")
  2115. >>> ExtendedContext.power(Decimal('Infinity'), Decimal('-2'))
  2116. Decimal("0")
  2117. >>> ExtendedContext.power(Decimal('Infinity'), Decimal('-1'))
  2118. Decimal("0")
  2119. >>> ExtendedContext.power(Decimal('Infinity'), Decimal('0'))
  2120. Decimal("1")
  2121. >>> ExtendedContext.power(Decimal('Infinity'), Decimal('1'))
  2122. Decimal("Infinity")
  2123. >>> ExtendedContext.power(Decimal('Infinity'), Decimal('2'))
  2124. Decimal("Infinity")
  2125. >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('-2'))
  2126. Decimal("0")
  2127. >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('-1'))
  2128. Decimal("-0")
  2129. >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('0'))
  2130. Decimal("1")
  2131. >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('1'))
  2132. Decimal("-Infinity")
  2133. >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('2'))
  2134. Decimal("Infinity")
  2135. >>> ExtendedContext.power(Decimal('0'), Decimal('0'))
  2136. Decimal("NaN")
  2137. """
  2138. return a.__pow__(b, modulo, context=self)
  2139. def quantize(self, a, b):
  2140. """Returns a value equal to 'a' (rounded) and having the exponent of 'b'.
  2141. The coefficient of the result is derived from that of the left-hand
  2142. operand. It may be rounded using the current rounding setting (if the
  2143. exponent is being increased), multiplied by a positive power of ten (if
  2144. the exponent is being decreased), or is unchanged (if the exponent is
  2145. already equal to that of the right-hand operand).
  2146. Unlike other operations, if the length of the coefficient after the
  2147. quantize operation would be greater than precision then an Invalid
  2148. operation condition is raised. This guarantees that, unless there is an
  2149. error condition, the exponent of the result of a quantize is always
  2150. equal to that of the right-hand operand.
  2151. Also unlike other operations, quantize will never raise Underflow, even
  2152. if the result is subnormal and inexact.
  2153. >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
  2154. Decimal("2.170")
  2155. >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
  2156. Decimal("2.17")
  2157. >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
  2158. Decimal("2.2")
  2159. >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
  2160. Decimal("2")
  2161. >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
  2162. Decimal("0E+1")
  2163. >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
  2164. Decimal("-Infinity")
  2165. >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
  2166. Decimal("NaN")
  2167. >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
  2168. Decimal("-0")
  2169. >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
  2170. Decimal("-0E+5")
  2171. >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
  2172. Decimal("NaN")
  2173. >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
  2174. Decimal("NaN")
  2175. >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
  2176. Decimal("217.0")
  2177. >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
  2178. Decimal("217")
  2179. >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
  2180. Decimal("2.2E+2")
  2181. >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
  2182. Decimal("2E+2")
  2183. """
  2184. return a.quantize(b, context=self)
  2185. def remainder(self, a, b):
  2186. """Returns the remainder from integer division.
  2187. The result is the residue of the dividend after the operation of
  2188. calculating integer division as described for divide-integer, rounded to
  2189. precision digits if necessary. The sign of the result, if non-zero, is
  2190. the same as that of the original dividend.
  2191. This operation will fail under the same conditions as integer division
  2192. (that is, if integer division on the same two operands would fail, the
  2193. remainder cannot be calculated).
  2194. >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
  2195. Decimal("2.1")
  2196. >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
  2197. Decimal("1")
  2198. >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
  2199. Decimal("-1")
  2200. >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
  2201. Decimal("0.2")
  2202. >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
  2203. Decimal("0.1")
  2204. >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
  2205. Decimal("1.0")
  2206. """
  2207. return a.__mod__(b, context=self)
  2208. def remainder_near(self, a, b):
  2209. """Returns to be "a - b * n", where n is the integer nearest the exact
  2210. value of "x / b" (if two integers are equally near then the even one
  2211. is chosen). If the result is equal to 0 then its sign will be the
  2212. sign of a.
  2213. This operation will fail under the same conditions as integer division
  2214. (that is, if integer division on the same two operands would fail, the
  2215. remainder cannot be calculated).
  2216. >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
  2217. Decimal("-0.9")
  2218. >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
  2219. Decimal("-2")
  2220. >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
  2221. Decimal("1")
  2222. >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
  2223. Decimal("-1")
  2224. >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
  2225. Decimal("0.2")
  2226. >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
  2227. Decimal("0.1")
  2228. >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
  2229. Decimal("-0.3")
  2230. """
  2231. return a.remainder_near(b, context=self)
  2232. def same_quantum(self, a, b):
  2233. """Returns True if the two operands have the same exponent.
  2234. The result is never affected by either the sign or the coefficient of
  2235. either operand.
  2236. >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
  2237. False
  2238. >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
  2239. True
  2240. >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
  2241. False
  2242. >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
  2243. True
  2244. """
  2245. return a.same_quantum(b)
  2246. def sqrt(self, a):
  2247. """Returns the square root of a non-negative number to context precision.
  2248. If the result must be inexact, it is rounded using the round-half-even
  2249. algorithm.
  2250. >>> ExtendedContext.sqrt(Decimal('0'))
  2251. Decimal("0")
  2252. >>> ExtendedContext.sqrt(Decimal('-0'))
  2253. Decimal("-0")
  2254. >>> ExtendedContext.sqrt(Decimal('0.39'))
  2255. Decimal("0.624499800")
  2256. >>> ExtendedContext.sqrt(Decimal('100'))
  2257. Decimal("10")
  2258. >>> ExtendedContext.sqrt(Decimal('1'))
  2259. Decimal("1")
  2260. >>> ExtendedContext.sqrt(Decimal('1.0'))
  2261. Decimal("1.0")
  2262. >>> ExtendedContext.sqrt(Decimal('1.00'))
  2263. Decimal("1.0")
  2264. >>> ExtendedContext.sqrt(Decimal('7'))
  2265. Decimal("2.64575131")
  2266. >>> ExtendedContext.sqrt(Decimal('10'))
  2267. Decimal("3.16227766")
  2268. >>> ExtendedContext.prec
  2269. 9
  2270. """
  2271. return a.sqrt(context=self)
  2272. def subtract(self, a, b):
  2273. """Return the sum of the two operands.
  2274. >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
  2275. Decimal("0.23")
  2276. >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
  2277. Decimal("0.00")
  2278. >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
  2279. Decimal("-0.77")
  2280. """
  2281. return a.__sub__(b, context=self)
  2282. def to_eng_string(self, a):
  2283. """Converts a number to a string, using scientific notation.
  2284. The operation is not affected by the context.
  2285. """
  2286. return a.to_eng_string(context=self)
  2287. def to_sci_string(self, a):
  2288. """Converts a number to a string, using scientific notation.
  2289. The operation is not affected by the context.
  2290. """
  2291. return a.__str__(context=self)
  2292. def to_integral(self, a):
  2293. """Rounds to an integer.
  2294. When the operand has a negative exponent, the result is the same
  2295. as using the quantize() operation using the given operand as the
  2296. left-hand-operand, 1E+0 as the right-hand-operand, and the precision
  2297. of the operand as the precision setting, except that no flags will
  2298. be set. The rounding mode is taken from the context.
  2299. >>> ExtendedContext.to_integral(Decimal('2.1'))
  2300. Decimal("2")
  2301. >>> ExtendedContext.to_integral(Decimal('100'))
  2302. Decimal("100")
  2303. >>> ExtendedContext.to_integral(Decimal('100.0'))
  2304. Decimal("100")
  2305. >>> ExtendedContext.to_integral(Decimal('101.5'))
  2306. Decimal("102")
  2307. >>> ExtendedContext.to_integral(Decimal('-101.5'))
  2308. Decimal("-102")
  2309. >>> ExtendedContext.to_integral(Decimal('10E+5'))
  2310. Decimal("1.0E+6")
  2311. >>> ExtendedContext.to_integral(Decimal('7.89E+77'))
  2312. Decimal("7.89E+77")
  2313. >>> ExtendedContext.to_integral(Decimal('-Inf'))
  2314. Decimal("-Infinity")
  2315. """
  2316. return a.to_integral(context=self)
  2317. class _WorkRep(object):
  2318. __slots__ = ('sign','int','exp')
  2319. # sign: 0 or 1
  2320. # int: int or long
  2321. # exp: None, int, or string
  2322. def __init__(self, value=None):
  2323. if value is None:
  2324. self.sign = None
  2325. self.int = 0
  2326. self.exp = None
  2327. elif isinstance(value, Decimal):
  2328. self.sign = value._sign
  2329. cum = 0
  2330. for digit in value._int:
  2331. cum = cum * 10 + digit
  2332. self.int = cum
  2333. self.exp = value._exp
  2334. else:
  2335. # assert isinstance(value, tuple)
  2336. self.sign = value[0]
  2337. self.int = value[1]
  2338. self.exp = value[2]
  2339. def __repr__(self):
  2340. return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
  2341. __str__ = __repr__
  2342. def _normalize(op1, op2, shouldround = 0, prec = 0):
  2343. """Normalizes op1, op2 to have the same exp and length of coefficient.
  2344. Done during addition.
  2345. """
  2346. # Yes, the exponent is a long, but the difference between exponents
  2347. # must be an int-- otherwise you'd get a big memory problem.
  2348. numdigits = int(op1.exp - op2.exp)
  2349. if numdigits < 0:
  2350. numdigits = -numdigits
  2351. tmp = op2
  2352. other = op1
  2353. else:
  2354. tmp = op1
  2355. other = op2
  2356. if shouldround and numdigits > prec + 1:
  2357. # Big difference in exponents - check the adjusted exponents
  2358. tmp_len = len(str(tmp.int))
  2359. other_len = len(str(other.int))
  2360. if numdigits > (other_len + prec + 1 - tmp_len):
  2361. # If the difference in adjusted exps is > prec+1, we know
  2362. # other is insignificant, so might as well put a 1 after the precision.
  2363. # (since this is only for addition.) Also stops use of massive longs.
  2364. extend = prec + 2 - tmp_len
  2365. if extend <= 0:
  2366. extend = 1
  2367. tmp.int *= 10 ** extend
  2368. tmp.exp -= extend
  2369. other.int = 1
  2370. other.exp = tmp.exp
  2371. return op1, op2
  2372. tmp.int *= 10 ** numdigits
  2373. tmp.exp -= numdigits
  2374. return op1, op2
  2375. def _adjust_coefficients(op1, op2):
  2376. """Adjust op1, op2 so that op2.int * 10 > op1.int >= op2.int.
  2377. Returns the adjusted op1, op2 as well as the change in op1.exp-op2.exp.
  2378. Used on _WorkRep instances during division.
  2379. """
  2380. adjust = 0
  2381. #If op1 is smaller, make it larger
  2382. while op2.int > op1.int:
  2383. op1.int *= 10
  2384. op1.exp -= 1
  2385. adjust += 1
  2386. #If op2 is too small, make it larger
  2387. while op1.int >= (10 * op2.int):
  2388. op2.int *= 10
  2389. op2.exp -= 1
  2390. adjust -= 1
  2391. return op1, op2, adjust
  2392. ##### Helper Functions ########################################
  2393. def _convert_other(other):
  2394. """Convert other to Decimal.
  2395. Verifies that it's ok to use in an implicit construction.
  2396. """
  2397. if isinstance(other, Decimal):
  2398. return other
  2399. if isinstance(other, (int, long)):
  2400. return Decimal(other)
  2401. raise TypeError, "You can interact Decimal only with int, long or Decimal data types."
  2402. _infinity_map = {
  2403. 'inf' : 1,
  2404. 'infinity' : 1,
  2405. '+inf' : 1,
  2406. '+infinity' : 1,
  2407. '-inf' : -1,
  2408. '-infinity' : -1
  2409. }
  2410. def _isinfinity(num):
  2411. """Determines whether a string or float is infinity.
  2412. +1 for negative infinity; 0 for finite ; +1 for positive infinity
  2413. """
  2414. num = str(num).lower()
  2415. return _infinity_map.get(num, 0)
  2416. def _isnan(num):
  2417. """Determines whether a string or float is NaN
  2418. (1, sign, diagnostic info as string) => NaN
  2419. (2, sign, diagnostic info as string) => sNaN
  2420. 0 => not a NaN
  2421. """
  2422. num = str(num).lower()
  2423. if not num:
  2424. return 0
  2425. #get the sign, get rid of trailing [+-]
  2426. sign = 0
  2427. if num[0] == '+':
  2428. num = num[1:]
  2429. elif num[0] == '-': #elif avoids '+-nan'
  2430. num = num[1:]
  2431. sign = 1
  2432. if num.startswith('nan'):
  2433. if len(num) > 3 and not num[3:].isdigit(): #diagnostic info
  2434. return 0
  2435. return (1, sign, num[3:].lstrip('0'))
  2436. if num.startswith('snan'):
  2437. if len(num) > 4 and not num[4:].isdigit():
  2438. return 0
  2439. return (2, sign, num[4:].lstrip('0'))
  2440. return 0
  2441. ##### Setup Specific Contexts ################################
  2442. # The default context prototype used by Context()
  2443. # Is mutable, so that new contexts can have different default values
  2444. DefaultContext = Context(
  2445. prec=28, rounding=ROUND_HALF_EVEN,
  2446. traps=[DivisionByZero, Overflow, InvalidOperation],
  2447. flags=[],
  2448. _rounding_decision=ALWAYS_ROUND,
  2449. Emax=999999999,
  2450. Emin=-999999999,
  2451. capitals=1
  2452. )
  2453. # Pre-made alternate contexts offered by the specification
  2454. # Don't change these; the user should be able to select these
  2455. # contexts and be able to reproduce results from other implementations
  2456. # of the spec.
  2457. BasicContext = Context(
  2458. prec=9, rounding=ROUND_HALF_UP,
  2459. traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
  2460. flags=[],
  2461. )
  2462. ExtendedContext = Context(
  2463. prec=9, rounding=ROUND_HALF_EVEN,
  2464. traps=[],
  2465. flags=[],
  2466. )
  2467. ##### Useful Constants (internal use only) ####################
  2468. #Reusable defaults
  2469. Inf = Decimal('Inf')
  2470. negInf = Decimal('-Inf')
  2471. #Infsign[sign] is infinity w/ that sign
  2472. Infsign = (Inf, negInf)
  2473. NaN = Decimal('NaN')
  2474. ##### crud for parsing strings #################################
  2475. import re
  2476. # There's an optional sign at the start, and an optional exponent
  2477. # at the end. The exponent has an optional sign and at least one
  2478. # digit. In between, must have either at least one digit followed
  2479. # by an optional fraction, or a decimal point followed by at least
  2480. # one digit. Yuck.
  2481. _parser = re.compile(r"""
  2482. # \s*
  2483. (?P<sign>[-+])?
  2484. (
  2485. (?P<int>\d+) (\. (?P<frac>\d*))?
  2486. |
  2487. \. (?P<onlyfrac>\d+)
  2488. )
  2489. ([eE](?P<exp>[-+]? \d+))?
  2490. # \s*
  2491. $
  2492. """, re.VERBOSE).match #Uncomment the \s* to allow leading or trailing spaces.
  2493. del re
  2494. # return sign, n, p s.t. float string value == -1**sign * n * 10**p exactly
  2495. def _string2exact(s):
  2496. m = _parser(s)
  2497. if m is None:
  2498. raise ValueError("invalid literal for Decimal: %r" % s)
  2499. if m.group('sign') == "-":
  2500. sign = 1
  2501. else:
  2502. sign = 0
  2503. exp = m.group('exp')
  2504. if exp is None:
  2505. exp = 0
  2506. else:
  2507. exp = int(exp)
  2508. intpart = m.group('int')
  2509. if intpart is None:
  2510. intpart = ""
  2511. fracpart = m.group('onlyfrac')
  2512. else:
  2513. fracpart = m.group('frac')
  2514. if fracpart is None:
  2515. fracpart = ""
  2516. exp -= len(fracpart)
  2517. mantissa = intpart + fracpart
  2518. tmp = map(int, mantissa)
  2519. backup = tmp
  2520. while tmp and tmp[0] == 0:
  2521. del tmp[0]
  2522. # It's a zero
  2523. if not tmp:
  2524. if backup:
  2525. return (sign, tuple(backup), exp)
  2526. return (sign, (0,), exp)
  2527. mantissa = tuple(tmp)
  2528. return (sign, mantissa, exp)
  2529. if __name__ == '__main__':
  2530. import doctest, sys
  2531. doctest.testmod(sys.modules[__name__])