_pydecimal.py 223 KB

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