decimal.py 106 KB

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