PageRenderTime 60ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/lib-python/2.7/decimal.py

https://bitbucket.org/evelyn559/pypy
Python | 6149 lines | 6117 code | 4 blank | 28 comment | 9 complexity | a9a71dfd7fcda25321ad62f70154f17a MD5 | raw file

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

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

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