decimal.py 216 KB

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