_pydecimal.py 222 KB

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