_pydecimal.py 224 KB

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