PageRenderTime 54ms CodeModel.GetById 17ms 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

Large files files are truncated, but you can click here to view the full file

  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]:

Large files files are truncated, but you can click here to view the full file