PageRenderTime 46ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/decimal.py

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