decNumber.c 380 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141
  1. /* ------------------------------------------------------------------ */
  2. /* Decimal Number arithmetic module */
  3. /* ------------------------------------------------------------------ */
  4. /* Copyright (c) IBM Corporation, 2000, 2009. All rights reserved. */
  5. /* */
  6. /* This software is made available under the terms of the */
  7. /* ICU License -- ICU 1.8.1 and later. */
  8. /* */
  9. /* The description and User's Guide ("The decNumber C Library") for */
  10. /* this software is called decNumber.pdf. This document is */
  11. /* available, together with arithmetic and format specifications, */
  12. /* testcases, and Web links, on the General Decimal Arithmetic page. */
  13. /* */
  14. /* Please send comments, suggestions, and corrections to the author: */
  15. /* [email protected] */
  16. /* Mike Cowlishaw, IBM Fellow */
  17. /* IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK */
  18. /* ------------------------------------------------------------------ */
  19. /* This module comprises the routines for arbitrary-precision General */
  20. /* Decimal Arithmetic as defined in the specification which may be */
  21. /* found on the General Decimal Arithmetic pages. It implements both */
  22. /* the full ('extended') arithmetic and the simpler ('subset') */
  23. /* arithmetic. */
  24. /* */
  25. /* Usage notes: */
  26. /* */
  27. /* 1. This code is ANSI C89 except: */
  28. /* */
  29. /* a) C99 line comments (double forward slash) are used. (Most C */
  30. /* compilers accept these. If yours does not, a simple script */
  31. /* can be used to convert them to ANSI C comments.) */
  32. /* */
  33. /* b) Types from C99 stdint.h are used. If you do not have this */
  34. /* header file, see the User's Guide section of the decNumber */
  35. /* documentation; this lists the necessary definitions. */
  36. /* */
  37. /* c) If DECDPUN>4 or DECUSE64=1, the C99 64-bit int64_t and */
  38. /* uint64_t types may be used. To avoid these, set DECUSE64=0 */
  39. /* and DECDPUN<=4 (see documentation). */
  40. /* */
  41. /* The code also conforms to C99 restrictions; in particular, */
  42. /* strict aliasing rules are observed. */
  43. /* */
  44. /* 2. The decNumber format which this library uses is optimized for */
  45. /* efficient processing of relatively short numbers; in particular */
  46. /* it allows the use of fixed sized structures and minimizes copy */
  47. /* and move operations. It does, however, support arbitrary */
  48. /* precision (up to 999,999,999 digits) and arbitrary exponent */
  49. /* range (Emax in the range 0 through 999,999,999 and Emin in the */
  50. /* range -999,999,999 through 0). Mathematical functions (for */
  51. /* example decNumberExp) as identified below are restricted more */
  52. /* tightly: digits, emax, and -emin in the context must be <= */
  53. /* DEC_MAX_MATH (999999), and their operand(s) must be within */
  54. /* these bounds. */
  55. /* */
  56. /* 3. Logical functions are further restricted; their operands must */
  57. /* be finite, positive, have an exponent of zero, and all digits */
  58. /* must be either 0 or 1. The result will only contain digits */
  59. /* which are 0 or 1 (and will have exponent=0 and a sign of 0). */
  60. /* */
  61. /* 4. Operands to operator functions are never modified unless they */
  62. /* are also specified to be the result number (which is always */
  63. /* permitted). Other than that case, operands must not overlap. */
  64. /* */
  65. /* 5. Error handling: the type of the error is ORed into the status */
  66. /* flags in the current context (decContext structure). The */
  67. /* SIGFPE signal is then raised if the corresponding trap-enabler */
  68. /* flag in the decContext is set (is 1). */
  69. /* */
  70. /* It is the responsibility of the caller to clear the status */
  71. /* flags as required. */
  72. /* */
  73. /* The result of any routine which returns a number will always */
  74. /* be a valid number (which may be a special value, such as an */
  75. /* Infinity or NaN). */
  76. /* */
  77. /* 6. The decNumber format is not an exchangeable concrete */
  78. /* representation as it comprises fields which may be machine- */
  79. /* dependent (packed or unpacked, or special length, for example). */
  80. /* Canonical conversions to and from strings are provided; other */
  81. /* conversions are available in separate modules. */
  82. /* */
  83. /* 7. Normally, input operands are assumed to be valid. Set DECCHECK */
  84. /* to 1 for extended operand checking (including NULL operands). */
  85. /* Results are undefined if a badly-formed structure (or a NULL */
  86. /* pointer to a structure) is provided, though with DECCHECK */
  87. /* enabled the operator routines are protected against exceptions. */
  88. /* (Except if the result pointer is NULL, which is unrecoverable.) */
  89. /* */
  90. /* However, the routines will never cause exceptions if they are */
  91. /* given well-formed operands, even if the value of the operands */
  92. /* is inappropriate for the operation and DECCHECK is not set. */
  93. /* (Except for SIGFPE, as and where documented.) */
  94. /* */
  95. /* 8. Subset arithmetic is available only if DECSUBSET is set to 1. */
  96. /* ------------------------------------------------------------------ */
  97. /* Implementation notes for maintenance of this module: */
  98. /* */
  99. /* 1. Storage leak protection: Routines which use malloc are not */
  100. /* permitted to use return for fastpath or error exits (i.e., */
  101. /* they follow strict structured programming conventions). */
  102. /* Instead they have a do{}while(0); construct surrounding the */
  103. /* code which is protected -- break may be used to exit this. */
  104. /* Other routines can safely use the return statement inline. */
  105. /* */
  106. /* Storage leak accounting can be enabled using DECALLOC. */
  107. /* */
  108. /* 2. All loops use the for(;;) construct. Any do construct does */
  109. /* not loop; it is for allocation protection as just described. */
  110. /* */
  111. /* 3. Setting status in the context must always be the very last */
  112. /* action in a routine, as non-0 status may raise a trap and hence */
  113. /* the call to set status may not return (if the handler uses long */
  114. /* jump). Therefore all cleanup must be done first. In general, */
  115. /* to achieve this status is accumulated and is only applied just */
  116. /* before return by calling decContextSetStatus (via decStatus). */
  117. /* */
  118. /* Routines which allocate storage cannot, in general, use the */
  119. /* 'top level' routines which could cause a non-returning */
  120. /* transfer of control. The decXxxxOp routines are safe (do not */
  121. /* call decStatus even if traps are set in the context) and should */
  122. /* be used instead (they are also a little faster). */
  123. /* */
  124. /* 4. Exponent checking is minimized by allowing the exponent to */
  125. /* grow outside its limits during calculations, provided that */
  126. /* the decFinalize function is called later. Multiplication and */
  127. /* division, and intermediate calculations in exponentiation, */
  128. /* require more careful checks because of the risk of 31-bit */
  129. /* overflow (the most negative valid exponent is -1999999997, for */
  130. /* a 999999999-digit number with adjusted exponent of -999999999). */
  131. /* */
  132. /* 5. Rounding is deferred until finalization of results, with any */
  133. /* 'off to the right' data being represented as a single digit */
  134. /* residue (in the range -1 through 9). This avoids any double- */
  135. /* rounding when more than one shortening takes place (for */
  136. /* example, when a result is subnormal). */
  137. /* */
  138. /* 6. The digits count is allowed to rise to a multiple of DECDPUN */
  139. /* during many operations, so whole Units are handled and exact */
  140. /* accounting of digits is not needed. The correct digits value */
  141. /* is found by decGetDigits, which accounts for leading zeros. */
  142. /* This must be called before any rounding if the number of digits */
  143. /* is not known exactly. */
  144. /* */
  145. /* 7. The multiply-by-reciprocal 'trick' is used for partitioning */
  146. /* numbers up to four digits, using appropriate constants. This */
  147. /* is not useful for longer numbers because overflow of 32 bits */
  148. /* would lead to 4 multiplies, which is almost as expensive as */
  149. /* a divide (unless a floating-point or 64-bit multiply is */
  150. /* assumed to be available). */
  151. /* */
  152. /* 8. Unusual abbreviations that may be used in the commentary: */
  153. /* lhs -- left hand side (operand, of an operation) */
  154. /* lsd -- least significant digit (of coefficient) */
  155. /* lsu -- least significant Unit (of coefficient) */
  156. /* msd -- most significant digit (of coefficient) */
  157. /* msi -- most significant item (in an array) */
  158. /* msu -- most significant Unit (of coefficient) */
  159. /* rhs -- right hand side (operand, of an operation) */
  160. /* +ve -- positive */
  161. /* -ve -- negative */
  162. /* ** -- raise to the power */
  163. /* ------------------------------------------------------------------ */
  164. #include <stdlib.h> // for malloc, free, etc.
  165. #include <stdio.h> // for printf [if needed]
  166. #include <string.h> // for strcpy
  167. #include <ctype.h> // for lower
  168. #include "decNumber.h" // base number library
  169. #include "decNumberLocal.h" // decNumber local types, etc.
  170. /* Constants */
  171. // Public lookup table used by the D2U macro
  172. const uByte d2utable[DECMAXD2U+1]=D2UTABLE;
  173. #define DECVERB 1 // set to 1 for verbose DECCHECK
  174. #define powers DECPOWERS // old internal name
  175. // Local constants
  176. #define DIVIDE 0x80 // Divide operators
  177. #define REMAINDER 0x40 // ..
  178. #define DIVIDEINT 0x20 // ..
  179. #define REMNEAR 0x10 // ..
  180. #define COMPARE 0x01 // Compare operators
  181. #define COMPMAX 0x02 // ..
  182. #define COMPMIN 0x03 // ..
  183. #define COMPTOTAL 0x04 // ..
  184. #define COMPNAN 0x05 // .. [NaN processing]
  185. #define COMPSIG 0x06 // .. [signaling COMPARE]
  186. #define COMPMAXMAG 0x07 // ..
  187. #define COMPMINMAG 0x08 // ..
  188. #define DEC_sNaN 0x40000000 // local status: sNaN signal
  189. #define BADINT (Int)0x80000000 // most-negative Int; error indicator
  190. // Next two indicate an integer >= 10**6, and its parity (bottom bit)
  191. #define BIGEVEN (Int)0x80000002
  192. #define BIGODD (Int)0x80000003
  193. static Unit uarrone[1]={1}; // Unit array of 1, used for incrementing
  194. /* Granularity-dependent code */
  195. #if DECDPUN<=4
  196. #define eInt Int // extended integer
  197. #define ueInt uInt // unsigned extended integer
  198. // Constant multipliers for divide-by-power-of five using reciprocal
  199. // multiply, after removing powers of 2 by shifting, and final shift
  200. // of 17 [we only need up to **4]
  201. static const uInt multies[]={131073, 26215, 5243, 1049, 210};
  202. // QUOT10 -- macro to return the quotient of unit u divided by 10**n
  203. #define QUOT10(u, n) ((((uInt)(u)>>(n))*multies[n])>>17)
  204. #else
  205. // For DECDPUN>4 non-ANSI-89 64-bit types are needed.
  206. #if !DECUSE64
  207. #error decNumber.c: DECUSE64 must be 1 when DECDPUN>4
  208. #endif
  209. #define eInt Long // extended integer
  210. #define ueInt uLong // unsigned extended integer
  211. #endif
  212. /* Local routines */
  213. static decNumber * decAddOp(decNumber *, const decNumber *, const decNumber *,
  214. decContext *, uByte, uInt *);
  215. static Flag decBiStr(const char *, const char *, const char *);
  216. static uInt decCheckMath(const decNumber *, decContext *, uInt *);
  217. static void decApplyRound(decNumber *, decContext *, Int, uInt *);
  218. static Int decCompare(const decNumber *lhs, const decNumber *rhs, Flag);
  219. static decNumber * decCompareOp(decNumber *, const decNumber *,
  220. const decNumber *, decContext *,
  221. Flag, uInt *);
  222. static void decCopyFit(decNumber *, const decNumber *, decContext *,
  223. Int *, uInt *);
  224. static decNumber * decDecap(decNumber *, Int);
  225. static decNumber * decDivideOp(decNumber *, const decNumber *,
  226. const decNumber *, decContext *, Flag, uInt *);
  227. static decNumber * decExpOp(decNumber *, const decNumber *,
  228. decContext *, uInt *);
  229. static void decFinalize(decNumber *, decContext *, Int *, uInt *);
  230. static Int decGetDigits(Unit *, Int);
  231. static Int decGetInt(const decNumber *);
  232. static decNumber * decLnOp(decNumber *, const decNumber *,
  233. decContext *, uInt *);
  234. static decNumber * decMultiplyOp(decNumber *, const decNumber *,
  235. const decNumber *, decContext *,
  236. uInt *);
  237. static decNumber * decNaNs(decNumber *, const decNumber *,
  238. const decNumber *, decContext *, uInt *);
  239. static decNumber * decQuantizeOp(decNumber *, const decNumber *,
  240. const decNumber *, decContext *, Flag,
  241. uInt *);
  242. static void decReverse(Unit *, Unit *);
  243. static void decSetCoeff(decNumber *, decContext *, const Unit *,
  244. Int, Int *, uInt *);
  245. static void decSetMaxValue(decNumber *, decContext *);
  246. static void decSetOverflow(decNumber *, decContext *, uInt *);
  247. static void decSetSubnormal(decNumber *, decContext *, Int *, uInt *);
  248. static Int decShiftToLeast(Unit *, Int, Int);
  249. static Int decShiftToMost(Unit *, Int, Int);
  250. static void decStatus(decNumber *, uInt, decContext *);
  251. static void decToString(const decNumber *, char[], Flag);
  252. static decNumber * decTrim(decNumber *, decContext *, Flag, Flag, Int *);
  253. static Int decUnitAddSub(const Unit *, Int, const Unit *, Int, Int,
  254. Unit *, Int);
  255. static Int decUnitCompare(const Unit *, Int, const Unit *, Int, Int);
  256. #if !DECSUBSET
  257. /* decFinish == decFinalize when no subset arithmetic needed */
  258. #define decFinish(a,b,c,d) decFinalize(a,b,c,d)
  259. #else
  260. static void decFinish(decNumber *, decContext *, Int *, uInt *);
  261. static decNumber * decRoundOperand(const decNumber *, decContext *, uInt *);
  262. #endif
  263. /* Local macros */
  264. // masked special-values bits
  265. #define SPECIALARG (rhs->bits & DECSPECIAL)
  266. #define SPECIALARGS ((lhs->bits | rhs->bits) & DECSPECIAL)
  267. /* Diagnostic macros, etc. */
  268. #if DECALLOC
  269. // Handle malloc/free accounting. If enabled, our accountable routines
  270. // are used; otherwise the code just goes straight to the system malloc
  271. // and free routines.
  272. #define malloc(a) decMalloc(a)
  273. #define free(a) decFree(a)
  274. #define DECFENCE 0x5a // corruption detector
  275. // 'Our' malloc and free:
  276. static void *decMalloc(size_t);
  277. static void decFree(void *);
  278. uInt decAllocBytes=0; // count of bytes allocated
  279. // Note that DECALLOC code only checks for storage buffer overflow.
  280. // To check for memory leaks, the decAllocBytes variable must be
  281. // checked to be 0 at appropriate times (e.g., after the test
  282. // harness completes a set of tests). This checking may be unreliable
  283. // if the testing is done in a multi-thread environment.
  284. #endif
  285. #if DECCHECK
  286. // Optional checking routines. Enabling these means that decNumber
  287. // and decContext operands to operator routines are checked for
  288. // correctness. This roughly doubles the execution time of the
  289. // fastest routines (and adds 600+ bytes), so should not normally be
  290. // used in 'production'.
  291. // decCheckInexact is used to check that inexact results have a full
  292. // complement of digits (where appropriate -- this is not the case
  293. // for Quantize, for example)
  294. #define DECUNRESU ((decNumber *)(void *)0xffffffff)
  295. #define DECUNUSED ((const decNumber *)(void *)0xffffffff)
  296. #define DECUNCONT ((decContext *)(void *)(0xffffffff))
  297. static Flag decCheckOperands(decNumber *, const decNumber *,
  298. const decNumber *, decContext *);
  299. static Flag decCheckNumber(const decNumber *);
  300. static void decCheckInexact(const decNumber *, decContext *);
  301. #endif
  302. #if DECTRACE || DECCHECK
  303. // Optional trace/debugging routines (may or may not be used)
  304. void decNumberShow(const decNumber *); // displays the components of a number
  305. static void decDumpAr(char, const Unit *, Int);
  306. #endif
  307. /* ================================================================== */
  308. /* Conversions */
  309. /* ================================================================== */
  310. /* ------------------------------------------------------------------ */
  311. /* from-int32 -- conversion from Int or uInt */
  312. /* */
  313. /* dn is the decNumber to receive the integer */
  314. /* in or uin is the integer to be converted */
  315. /* returns dn */
  316. /* */
  317. /* No error is possible. */
  318. /* ------------------------------------------------------------------ */
  319. decNumber * decNumberFromInt32(decNumber *dn, Int in) {
  320. uInt unsig;
  321. if (in>=0) unsig=in;
  322. else { // negative (possibly BADINT)
  323. if (in==BADINT) unsig=(uInt)1073741824*2; // special case
  324. else unsig=-in; // invert
  325. }
  326. // in is now positive
  327. decNumberFromUInt32(dn, unsig);
  328. if (in<0) dn->bits=DECNEG; // sign needed
  329. return dn;
  330. } // decNumberFromInt32
  331. decNumber * decNumberFromUInt32(decNumber *dn, uInt uin) {
  332. Unit *up; // work pointer
  333. decNumberZero(dn); // clean
  334. if (uin==0) return dn; // [or decGetDigits bad call]
  335. for (up=dn->lsu; uin>0; up++) {
  336. *up=(Unit)(uin%(DECDPUNMAX+1));
  337. uin=uin/(DECDPUNMAX+1);
  338. }
  339. dn->digits=decGetDigits(dn->lsu, up-dn->lsu);
  340. return dn;
  341. } // decNumberFromUInt32
  342. /* ------------------------------------------------------------------ */
  343. /* to-int32 -- conversion to Int or uInt */
  344. /* */
  345. /* dn is the decNumber to convert */
  346. /* set is the context for reporting errors */
  347. /* returns the converted decNumber, or 0 if Invalid is set */
  348. /* */
  349. /* Invalid is set if the decNumber does not have exponent==0 or if */
  350. /* it is a NaN, Infinite, or out-of-range. */
  351. /* ------------------------------------------------------------------ */
  352. Int decNumberToInt32(const decNumber *dn, decContext *set) {
  353. #if DECCHECK
  354. if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
  355. #endif
  356. // special or too many digits, or bad exponent
  357. if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0) ; // bad
  358. else { // is a finite integer with 10 or fewer digits
  359. Int d; // work
  360. const Unit *up; // ..
  361. uInt hi=0, lo; // ..
  362. up=dn->lsu; // -> lsu
  363. lo=*up; // get 1 to 9 digits
  364. #if DECDPUN>1 // split to higher
  365. hi=lo/10;
  366. lo=lo%10;
  367. #endif
  368. up++;
  369. // collect remaining Units, if any, into hi
  370. for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
  371. // now low has the lsd, hi the remainder
  372. if (hi>214748364 || (hi==214748364 && lo>7)) { // out of range?
  373. // most-negative is a reprieve
  374. if (dn->bits&DECNEG && hi==214748364 && lo==8) return 0x80000000;
  375. // bad -- drop through
  376. }
  377. else { // in-range always
  378. Int i=X10(hi)+lo;
  379. if (dn->bits&DECNEG) return -i;
  380. return i;
  381. }
  382. } // integer
  383. decContextSetStatus(set, DEC_Invalid_operation); // [may not return]
  384. return 0;
  385. } // decNumberToInt32
  386. uInt decNumberToUInt32(const decNumber *dn, decContext *set) {
  387. #if DECCHECK
  388. if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
  389. #endif
  390. // special or too many digits, or bad exponent, or negative (<0)
  391. if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0
  392. || (dn->bits&DECNEG && !ISZERO(dn))); // bad
  393. else { // is a finite integer with 10 or fewer digits
  394. Int d; // work
  395. const Unit *up; // ..
  396. uInt hi=0, lo; // ..
  397. up=dn->lsu; // -> lsu
  398. lo=*up; // get 1 to 9 digits
  399. #if DECDPUN>1 // split to higher
  400. hi=lo/10;
  401. lo=lo%10;
  402. #endif
  403. up++;
  404. // collect remaining Units, if any, into hi
  405. for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
  406. // now low has the lsd, hi the remainder
  407. if (hi>429496729 || (hi==429496729 && lo>5)) ; // no reprieve possible
  408. else return X10(hi)+lo;
  409. } // integer
  410. decContextSetStatus(set, DEC_Invalid_operation); // [may not return]
  411. return 0;
  412. } // decNumberToUInt32
  413. /* ------------------------------------------------------------------ */
  414. /* to-scientific-string -- conversion to numeric string */
  415. /* to-engineering-string -- conversion to numeric string */
  416. /* */
  417. /* decNumberToString(dn, string); */
  418. /* decNumberToEngString(dn, string); */
  419. /* */
  420. /* dn is the decNumber to convert */
  421. /* string is the string where the result will be laid out */
  422. /* */
  423. /* string must be at least dn->digits+14 characters long */
  424. /* */
  425. /* No error is possible, and no status can be set. */
  426. /* ------------------------------------------------------------------ */
  427. char * decNumberToString(const decNumber *dn, char *string){
  428. decToString(dn, string, 0);
  429. return string;
  430. } // DecNumberToString
  431. char * decNumberToEngString(const decNumber *dn, char *string){
  432. decToString(dn, string, 1);
  433. return string;
  434. } // DecNumberToEngString
  435. /* ------------------------------------------------------------------ */
  436. /* to-number -- conversion from numeric string */
  437. /* */
  438. /* decNumberFromString -- convert string to decNumber */
  439. /* dn -- the number structure to fill */
  440. /* chars[] -- the string to convert ('\0' terminated) */
  441. /* set -- the context used for processing any error, */
  442. /* determining the maximum precision available */
  443. /* (set.digits), determining the maximum and minimum */
  444. /* exponent (set.emax and set.emin), determining if */
  445. /* extended values are allowed, and checking the */
  446. /* rounding mode if overflow occurs or rounding is */
  447. /* needed. */
  448. /* */
  449. /* The length of the coefficient and the size of the exponent are */
  450. /* checked by this routine, so the correct error (Underflow or */
  451. /* Overflow) can be reported or rounding applied, as necessary. */
  452. /* */
  453. /* If bad syntax is detected, the result will be a quiet NaN. */
  454. /* ------------------------------------------------------------------ */
  455. decNumber * decNumberFromString(decNumber *dn, const char chars[],
  456. decContext *set) {
  457. Int exponent=0; // working exponent [assume 0]
  458. uByte bits=0; // working flags [assume +ve]
  459. Unit *res; // where result will be built
  460. Unit resbuff[SD2U(DECBUFFER+9)];// local buffer in case need temporary
  461. // [+9 allows for ln() constants]
  462. Unit *allocres=NULL; // -> allocated result, iff allocated
  463. Int d=0; // count of digits found in decimal part
  464. const char *dotchar=NULL; // where dot was found
  465. const char *cfirst=chars; // -> first character of decimal part
  466. const char *last=NULL; // -> last digit of decimal part
  467. const char *c; // work
  468. Unit *up; // ..
  469. #if DECDPUN>1
  470. Int cut, out; // ..
  471. #endif
  472. Int residue; // rounding residue
  473. uInt status=0; // error code
  474. #if DECCHECK
  475. if (decCheckOperands(DECUNRESU, DECUNUSED, DECUNUSED, set))
  476. return decNumberZero(dn);
  477. #endif
  478. do { // status & malloc protection
  479. for (c=chars;; c++) { // -> input character
  480. if (*c>='0' && *c<='9') { // test for Arabic digit
  481. last=c;
  482. d++; // count of real digits
  483. continue; // still in decimal part
  484. }
  485. if (*c=='.' && dotchar==NULL) { // first '.'
  486. dotchar=c; // record offset into decimal part
  487. if (c==cfirst) cfirst++; // first digit must follow
  488. continue;}
  489. if (c==chars) { // first in string...
  490. if (*c=='-') { // valid - sign
  491. cfirst++;
  492. bits=DECNEG;
  493. continue;}
  494. if (*c=='+') { // valid + sign
  495. cfirst++;
  496. continue;}
  497. }
  498. // *c is not a digit, or a valid +, -, or '.'
  499. break;
  500. } // c
  501. if (last==NULL) { // no digits yet
  502. status=DEC_Conversion_syntax;// assume the worst
  503. if (*c=='\0') break; // and no more to come...
  504. #if DECSUBSET
  505. // if subset then infinities and NaNs are not allowed
  506. if (!set->extended) break; // hopeless
  507. #endif
  508. // Infinities and NaNs are possible, here
  509. if (dotchar!=NULL) break; // .. unless had a dot
  510. decNumberZero(dn); // be optimistic
  511. if (decBiStr(c, "infinity", "INFINITY")
  512. || decBiStr(c, "inf", "INF")) {
  513. dn->bits=bits | DECINF;
  514. status=0; // is OK
  515. break; // all done
  516. }
  517. // a NaN expected
  518. // 2003.09.10 NaNs are now permitted to have a sign
  519. dn->bits=bits | DECNAN; // assume simple NaN
  520. if (*c=='s' || *c=='S') { // looks like an sNaN
  521. c++;
  522. dn->bits=bits | DECSNAN;
  523. }
  524. if (*c!='n' && *c!='N') break; // check caseless "NaN"
  525. c++;
  526. if (*c!='a' && *c!='A') break; // ..
  527. c++;
  528. if (*c!='n' && *c!='N') break; // ..
  529. c++;
  530. // now either nothing, or nnnn payload, expected
  531. // -> start of integer and skip leading 0s [including plain 0]
  532. for (cfirst=c; *cfirst=='0';) cfirst++;
  533. if (*cfirst=='\0') { // "NaN" or "sNaN", maybe with all 0s
  534. status=0; // it's good
  535. break; // ..
  536. }
  537. // something other than 0s; setup last and d as usual [no dots]
  538. for (c=cfirst;; c++, d++) {
  539. if (*c<'0' || *c>'9') break; // test for Arabic digit
  540. last=c;
  541. }
  542. if (*c!='\0') break; // not all digits
  543. if (d>set->digits-1) {
  544. // [NB: payload in a decNumber can be full length unless
  545. // clamped, in which case can only be digits-1]
  546. if (set->clamp) break;
  547. if (d>set->digits) break;
  548. } // too many digits?
  549. // good; drop through to convert the integer to coefficient
  550. status=0; // syntax is OK
  551. bits=dn->bits; // for copy-back
  552. } // last==NULL
  553. else if (*c!='\0') { // more to process...
  554. // had some digits; exponent is only valid sequence now
  555. Flag nege; // 1=negative exponent
  556. const char *firstexp; // -> first significant exponent digit
  557. status=DEC_Conversion_syntax;// assume the worst
  558. if (*c!='e' && *c!='E') break;
  559. /* Found 'e' or 'E' -- now process explicit exponent */
  560. // 1998.07.11: sign no longer required
  561. nege=0;
  562. c++; // to (possible) sign
  563. if (*c=='-') {nege=1; c++;}
  564. else if (*c=='+') c++;
  565. if (*c=='\0') break;
  566. for (; *c=='0' && *(c+1)!='\0';) c++; // strip insignificant zeros
  567. firstexp=c; // save exponent digit place
  568. for (; ;c++) {
  569. if (*c<'0' || *c>'9') break; // not a digit
  570. exponent=X10(exponent)+(Int)*c-(Int)'0';
  571. } // c
  572. // if not now on a '\0', *c must not be a digit
  573. if (*c!='\0') break;
  574. // (this next test must be after the syntax checks)
  575. // if it was too long the exponent may have wrapped, so check
  576. // carefully and set it to a certain overflow if wrap possible
  577. if (c>=firstexp+9+1) {
  578. if (c>firstexp+9+1 || *firstexp>'1') exponent=DECNUMMAXE*2;
  579. // [up to 1999999999 is OK, for example 1E-1000000998]
  580. }
  581. if (nege) exponent=-exponent; // was negative
  582. status=0; // is OK
  583. } // stuff after digits
  584. // Here when whole string has been inspected; syntax is good
  585. // cfirst->first digit (never dot), last->last digit (ditto)
  586. // strip leading zeros/dot [leave final 0 if all 0's]
  587. if (*cfirst=='0') { // [cfirst has stepped over .]
  588. for (c=cfirst; c<last; c++, cfirst++) {
  589. if (*c=='.') continue; // ignore dots
  590. if (*c!='0') break; // non-zero found
  591. d--; // 0 stripped
  592. } // c
  593. #if DECSUBSET
  594. // make a rapid exit for easy zeros if !extended
  595. if (*cfirst=='0' && !set->extended) {
  596. decNumberZero(dn); // clean result
  597. break; // [could be return]
  598. }
  599. #endif
  600. } // at least one leading 0
  601. // Handle decimal point...
  602. if (dotchar!=NULL && dotchar<last) // non-trailing '.' found?
  603. exponent-=(last-dotchar); // adjust exponent
  604. // [we can now ignore the .]
  605. // OK, the digits string is good. Assemble in the decNumber, or in
  606. // a temporary units array if rounding is needed
  607. if (d<=set->digits) res=dn->lsu; // fits into supplied decNumber
  608. else { // rounding needed
  609. Int needbytes=D2U(d)*sizeof(Unit);// bytes needed
  610. res=resbuff; // assume use local buffer
  611. if (needbytes>(Int)sizeof(resbuff)) { // too big for local
  612. allocres=(Unit *)malloc(needbytes);
  613. if (allocres==NULL) {status|=DEC_Insufficient_storage; break;}
  614. res=allocres;
  615. }
  616. }
  617. // res now -> number lsu, buffer, or allocated storage for Unit array
  618. // Place the coefficient into the selected Unit array
  619. // [this is often 70% of the cost of this function when DECDPUN>1]
  620. #if DECDPUN>1
  621. out=0; // accumulator
  622. up=res+D2U(d)-1; // -> msu
  623. cut=d-(up-res)*DECDPUN; // digits in top unit
  624. for (c=cfirst;; c++) { // along the digits
  625. if (*c=='.') continue; // ignore '.' [don't decrement cut]
  626. out=X10(out)+(Int)*c-(Int)'0';
  627. if (c==last) break; // done [never get to trailing '.']
  628. cut--;
  629. if (cut>0) continue; // more for this unit
  630. *up=(Unit)out; // write unit
  631. up--; // prepare for unit below..
  632. cut=DECDPUN; // ..
  633. out=0; // ..
  634. } // c
  635. *up=(Unit)out; // write lsu
  636. #else
  637. // DECDPUN==1
  638. up=res; // -> lsu
  639. for (c=last; c>=cfirst; c--) { // over each character, from least
  640. if (*c=='.') continue; // ignore . [don't step up]
  641. *up=(Unit)((Int)*c-(Int)'0');
  642. up++;
  643. } // c
  644. #endif
  645. dn->bits=bits;
  646. dn->exponent=exponent;
  647. dn->digits=d;
  648. // if not in number (too long) shorten into the number
  649. if (d>set->digits) {
  650. residue=0;
  651. decSetCoeff(dn, set, res, d, &residue, &status);
  652. // always check for overflow or subnormal and round as needed
  653. decFinalize(dn, set, &residue, &status);
  654. }
  655. else { // no rounding, but may still have overflow or subnormal
  656. // [these tests are just for performance; finalize repeats them]
  657. if ((dn->exponent-1<set->emin-dn->digits)
  658. || (dn->exponent-1>set->emax-set->digits)) {
  659. residue=0;
  660. decFinalize(dn, set, &residue, &status);
  661. }
  662. }
  663. // decNumberShow(dn);
  664. } while(0); // [for break]
  665. if (allocres!=NULL) free(allocres); // drop any storage used
  666. if (status!=0) decStatus(dn, status, set);
  667. return dn;
  668. } /* decNumberFromString */
  669. /* ================================================================== */
  670. /* Operators */
  671. /* ================================================================== */
  672. /* ------------------------------------------------------------------ */
  673. /* decNumberAbs -- absolute value operator */
  674. /* */
  675. /* This computes C = abs(A) */
  676. /* */
  677. /* res is C, the result. C may be A */
  678. /* rhs is A */
  679. /* set is the context */
  680. /* */
  681. /* See also decNumberCopyAbs for a quiet bitwise version of this. */
  682. /* C must have space for set->digits digits. */
  683. /* ------------------------------------------------------------------ */
  684. /* This has the same effect as decNumberPlus unless A is negative, */
  685. /* in which case it has the same effect as decNumberMinus. */
  686. /* ------------------------------------------------------------------ */
  687. decNumber * decNumberAbs(decNumber *res, const decNumber *rhs,
  688. decContext *set) {
  689. decNumber dzero; // for 0
  690. uInt status=0; // accumulator
  691. #if DECCHECK
  692. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  693. #endif
  694. decNumberZero(&dzero); // set 0
  695. dzero.exponent=rhs->exponent; // [no coefficient expansion]
  696. decAddOp(res, &dzero, rhs, set, (uByte)(rhs->bits & DECNEG), &status);
  697. if (status!=0) decStatus(res, status, set);
  698. #if DECCHECK
  699. decCheckInexact(res, set);
  700. #endif
  701. return res;
  702. } // decNumberAbs
  703. /* ------------------------------------------------------------------ */
  704. /* decNumberAdd -- add two Numbers */
  705. /* */
  706. /* This computes C = A + B */
  707. /* */
  708. /* res is C, the result. C may be A and/or B (e.g., X=X+X) */
  709. /* lhs is A */
  710. /* rhs is B */
  711. /* set is the context */
  712. /* */
  713. /* C must have space for set->digits digits. */
  714. /* ------------------------------------------------------------------ */
  715. /* This just calls the routine shared with Subtract */
  716. decNumber * decNumberAdd(decNumber *res, const decNumber *lhs,
  717. const decNumber *rhs, decContext *set) {
  718. uInt status=0; // accumulator
  719. decAddOp(res, lhs, rhs, set, 0, &status);
  720. if (status!=0) decStatus(res, status, set);
  721. #if DECCHECK
  722. decCheckInexact(res, set);
  723. #endif
  724. return res;
  725. } // decNumberAdd
  726. /* ------------------------------------------------------------------ */
  727. /* decNumberAnd -- AND two Numbers, digitwise */
  728. /* */
  729. /* This computes C = A & B */
  730. /* */
  731. /* res is C, the result. C may be A and/or B (e.g., X=X&X) */
  732. /* lhs is A */
  733. /* rhs is B */
  734. /* set is the context (used for result length and error report) */
  735. /* */
  736. /* C must have space for set->digits digits. */
  737. /* */
  738. /* Logical function restrictions apply (see above); a NaN is */
  739. /* returned with Invalid_operation if a restriction is violated. */
  740. /* ------------------------------------------------------------------ */
  741. decNumber * decNumberAnd(decNumber *res, const decNumber *lhs,
  742. const decNumber *rhs, decContext *set) {
  743. const Unit *ua, *ub; // -> operands
  744. const Unit *msua, *msub; // -> operand msus
  745. Unit *uc, *msuc; // -> result and its msu
  746. Int msudigs; // digits in res msu
  747. #if DECCHECK
  748. if (decCheckOperands(res, lhs, rhs, set)) return res;
  749. #endif
  750. if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
  751. || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
  752. decStatus(res, DEC_Invalid_operation, set);
  753. return res;
  754. }
  755. // operands are valid
  756. ua=lhs->lsu; // bottom-up
  757. ub=rhs->lsu; // ..
  758. uc=res->lsu; // ..
  759. msua=ua+D2U(lhs->digits)-1; // -> msu of lhs
  760. msub=ub+D2U(rhs->digits)-1; // -> msu of rhs
  761. msuc=uc+D2U(set->digits)-1; // -> msu of result
  762. msudigs=MSUDIGITS(set->digits); // [faster than remainder]
  763. for (; uc<=msuc; ua++, ub++, uc++) { // Unit loop
  764. Unit a, b; // extract units
  765. if (ua>msua) a=0;
  766. else a=*ua;
  767. if (ub>msub) b=0;
  768. else b=*ub;
  769. *uc=0; // can now write back
  770. if (a|b) { // maybe 1 bits to examine
  771. Int i, j;
  772. *uc=0; // can now write back
  773. // This loop could be unrolled and/or use BIN2BCD tables
  774. for (i=0; i<DECDPUN; i++) {
  775. if (a&b&1) *uc=*uc+(Unit)powers[i]; // effect AND
  776. j=a%10;
  777. a=a/10;
  778. j|=b%10;
  779. b=b/10;
  780. if (j>1) {
  781. decStatus(res, DEC_Invalid_operation, set);
  782. return res;
  783. }
  784. if (uc==msuc && i==msudigs-1) break; // just did final digit
  785. } // each digit
  786. } // both OK
  787. } // each unit
  788. // [here uc-1 is the msu of the result]
  789. res->digits=decGetDigits(res->lsu, uc-res->lsu);
  790. res->exponent=0; // integer
  791. res->bits=0; // sign=0
  792. return res; // [no status to set]
  793. } // decNumberAnd
  794. /* ------------------------------------------------------------------ */
  795. /* decNumberCompare -- compare two Numbers */
  796. /* */
  797. /* This computes C = A ? B */
  798. /* */
  799. /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
  800. /* lhs is A */
  801. /* rhs is B */
  802. /* set is the context */
  803. /* */
  804. /* C must have space for one digit (or NaN). */
  805. /* ------------------------------------------------------------------ */
  806. decNumber * decNumberCompare(decNumber *res, const decNumber *lhs,
  807. const decNumber *rhs, decContext *set) {
  808. uInt status=0; // accumulator
  809. decCompareOp(res, lhs, rhs, set, COMPARE, &status);
  810. if (status!=0) decStatus(res, status, set);
  811. return res;
  812. } // decNumberCompare
  813. /* ------------------------------------------------------------------ */
  814. /* decNumberCompareSignal -- compare, signalling on all NaNs */
  815. /* */
  816. /* This computes C = A ? B */
  817. /* */
  818. /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
  819. /* lhs is A */
  820. /* rhs is B */
  821. /* set is the context */
  822. /* */
  823. /* C must have space for one digit (or NaN). */
  824. /* ------------------------------------------------------------------ */
  825. decNumber * decNumberCompareSignal(decNumber *res, const decNumber *lhs,
  826. const decNumber *rhs, decContext *set) {
  827. uInt status=0; // accumulator
  828. decCompareOp(res, lhs, rhs, set, COMPSIG, &status);
  829. if (status!=0) decStatus(res, status, set);
  830. return res;
  831. } // decNumberCompareSignal
  832. /* ------------------------------------------------------------------ */
  833. /* decNumberCompareTotal -- compare two Numbers, using total ordering */
  834. /* */
  835. /* This computes C = A ? B, under total ordering */
  836. /* */
  837. /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
  838. /* lhs is A */
  839. /* rhs is B */
  840. /* set is the context */
  841. /* */
  842. /* C must have space for one digit; the result will always be one of */
  843. /* -1, 0, or 1. */
  844. /* ------------------------------------------------------------------ */
  845. decNumber * decNumberCompareTotal(decNumber *res, const decNumber *lhs,
  846. const decNumber *rhs, decContext *set) {
  847. uInt status=0; // accumulator
  848. decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
  849. if (status!=0) decStatus(res, status, set);
  850. return res;
  851. } // decNumberCompareTotal
  852. /* ------------------------------------------------------------------ */
  853. /* decNumberCompareTotalMag -- compare, total ordering of magnitudes */
  854. /* */
  855. /* This computes C = |A| ? |B|, under total ordering */
  856. /* */
  857. /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
  858. /* lhs is A */
  859. /* rhs is B */
  860. /* set is the context */
  861. /* */
  862. /* C must have space for one digit; the result will always be one of */
  863. /* -1, 0, or 1. */
  864. /* ------------------------------------------------------------------ */
  865. decNumber * decNumberCompareTotalMag(decNumber *res, const decNumber *lhs,
  866. const decNumber *rhs, decContext *set) {
  867. uInt status=0; // accumulator
  868. uInt needbytes; // for space calculations
  869. decNumber bufa[D2N(DECBUFFER+1)];// +1 in case DECBUFFER=0
  870. decNumber *allocbufa=NULL; // -> allocated bufa, iff allocated
  871. decNumber bufb[D2N(DECBUFFER+1)];
  872. decNumber *allocbufb=NULL; // -> allocated bufb, iff allocated
  873. decNumber *a, *b; // temporary pointers
  874. #if DECCHECK
  875. if (decCheckOperands(res, lhs, rhs, set)) return res;
  876. #endif
  877. do { // protect allocated storage
  878. // if either is negative, take a copy and absolute
  879. if (decNumberIsNegative(lhs)) { // lhs<0
  880. a=bufa;
  881. needbytes=sizeof(decNumber)+(D2U(lhs->digits)-1)*sizeof(Unit);
  882. if (needbytes>sizeof(bufa)) { // need malloc space
  883. allocbufa=(decNumber *)malloc(needbytes);
  884. if (allocbufa==NULL) { // hopeless -- abandon
  885. status|=DEC_Insufficient_storage;
  886. break;}
  887. a=allocbufa; // use the allocated space
  888. }
  889. decNumberCopy(a, lhs); // copy content
  890. a->bits&=~DECNEG; // .. and clear the sign
  891. lhs=a; // use copy from here on
  892. }
  893. if (decNumberIsNegative(rhs)) { // rhs<0
  894. b=bufb;
  895. needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
  896. if (needbytes>sizeof(bufb)) { // need malloc space
  897. allocbufb=(decNumber *)malloc(needbytes);
  898. if (allocbufb==NULL) { // hopeless -- abandon
  899. status|=DEC_Insufficient_storage;
  900. break;}
  901. b=allocbufb; // use the allocated space
  902. }
  903. decNumberCopy(b, rhs); // copy content
  904. b->bits&=~DECNEG; // .. and clear the sign
  905. rhs=b; // use copy from here on
  906. }
  907. decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
  908. } while(0); // end protected
  909. if (allocbufa!=NULL) free(allocbufa); // drop any storage used
  910. if (allocbufb!=NULL) free(allocbufb); // ..
  911. if (status!=0) decStatus(res, status, set);
  912. return res;
  913. } // decNumberCompareTotalMag
  914. /* ------------------------------------------------------------------ */
  915. /* decNumberDivide -- divide one number by another */
  916. /* */
  917. /* This computes C = A / B */
  918. /* */
  919. /* res is C, the result. C may be A and/or B (e.g., X=X/X) */
  920. /* lhs is A */
  921. /* rhs is B */
  922. /* set is the context */
  923. /* */
  924. /* C must have space for set->digits digits. */
  925. /* ------------------------------------------------------------------ */
  926. decNumber * decNumberDivide(decNumber *res, const decNumber *lhs,
  927. const decNumber *rhs, decContext *set) {
  928. uInt status=0; // accumulator
  929. decDivideOp(res, lhs, rhs, set, DIVIDE, &status);
  930. if (status!=0) decStatus(res, status, set);
  931. #if DECCHECK
  932. decCheckInexact(res, set);
  933. #endif
  934. return res;
  935. } // decNumberDivide
  936. /* ------------------------------------------------------------------ */
  937. /* decNumberDivideInteger -- divide and return integer quotient */
  938. /* */
  939. /* This computes C = A # B, where # is the integer divide operator */
  940. /* */
  941. /* res is C, the result. C may be A and/or B (e.g., X=X#X) */
  942. /* lhs is A */
  943. /* rhs is B */
  944. /* set is the context */
  945. /* */
  946. /* C must have space for set->digits digits. */
  947. /* ------------------------------------------------------------------ */
  948. decNumber * decNumberDivideInteger(decNumber *res, const decNumber *lhs,
  949. const decNumber *rhs, decContext *set) {
  950. uInt status=0; // accumulator
  951. decDivideOp(res, lhs, rhs, set, DIVIDEINT, &status);
  952. if (status!=0) decStatus(res, status, set);
  953. return res;
  954. } // decNumberDivideInteger
  955. /* ------------------------------------------------------------------ */
  956. /* decNumberExp -- exponentiation */
  957. /* */
  958. /* This computes C = exp(A) */
  959. /* */
  960. /* res is C, the result. C may be A */
  961. /* rhs is A */
  962. /* set is the context; note that rounding mode has no effect */
  963. /* */
  964. /* C must have space for set->digits digits. */
  965. /* */
  966. /* Mathematical function restrictions apply (see above); a NaN is */
  967. /* returned with Invalid_operation if a restriction is violated. */
  968. /* */
  969. /* Finite results will always be full precision and Inexact, except */
  970. /* when A is a zero or -Infinity (giving 1 or 0 respectively). */
  971. /* */
  972. /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */
  973. /* almost always be correctly rounded, but may be up to 1 ulp in */
  974. /* error in rare cases. */
  975. /* ------------------------------------------------------------------ */
  976. /* This is a wrapper for decExpOp which can handle the slightly wider */
  977. /* (double) range needed by Ln (which has to be able to calculate */
  978. /* exp(-a) where a can be the tiniest number (Ntiny). */
  979. /* ------------------------------------------------------------------ */
  980. decNumber * decNumberExp(decNumber *res, const decNumber *rhs,
  981. decContext *set) {
  982. uInt status=0; // accumulator
  983. #if DECSUBSET
  984. decNumber *allocrhs=NULL; // non-NULL if rounded rhs allocated
  985. #endif
  986. #if DECCHECK
  987. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  988. #endif
  989. // Check restrictions; these restrictions ensure that if h=8 (see
  990. // decExpOp) then the result will either overflow or underflow to 0.
  991. // Other math functions restrict the input range, too, for inverses.
  992. // If not violated then carry out the operation.
  993. if (!decCheckMath(rhs, set, &status)) do { // protect allocation
  994. #if DECSUBSET
  995. if (!set->extended) {
  996. // reduce operand and set lostDigits status, as needed
  997. if (rhs->digits>set->digits) {
  998. allocrhs=decRoundOperand(rhs, set, &status);
  999. if (allocrhs==NULL) break;
  1000. rhs=allocrhs;
  1001. }
  1002. }
  1003. #endif
  1004. decExpOp(res, rhs, set, &status);
  1005. } while(0); // end protected
  1006. #if DECSUBSET
  1007. if (allocrhs !=NULL) free(allocrhs); // drop any storage used
  1008. #endif
  1009. // apply significant status
  1010. if (status!=0) decStatus(res, status, set);
  1011. #if DECCHECK
  1012. decCheckInexact(res, set);
  1013. #endif
  1014. return res;
  1015. } // decNumberExp
  1016. /* ------------------------------------------------------------------ */
  1017. /* decNumberFMA -- fused multiply add */
  1018. /* */
  1019. /* This computes D = (A * B) + C with only one rounding */
  1020. /* */
  1021. /* res is D, the result. D may be A or B or C (e.g., X=FMA(X,X,X)) */
  1022. /* lhs is A */
  1023. /* rhs is B */
  1024. /* fhs is C [far hand side] */
  1025. /* set is the context */
  1026. /* */
  1027. /* Mathematical function restrictions apply (see above); a NaN is */
  1028. /* returned with Invalid_operation if a restriction is violated. */
  1029. /* */
  1030. /* C must have space for set->digits digits. */
  1031. /* ------------------------------------------------------------------ */
  1032. decNumber * decNumberFMA(decNumber *res, const decNumber *lhs,
  1033. const decNumber *rhs, const decNumber *fhs,
  1034. decContext *set) {
  1035. uInt status=0; // accumulator
  1036. decContext dcmul; // context for the multiplication
  1037. uInt needbytes; // for space calculations
  1038. decNumber bufa[D2N(DECBUFFER*2+1)];
  1039. decNumber *allocbufa=NULL; // -> allocated bufa, iff allocated
  1040. decNumber *acc; // accumulator pointer
  1041. decNumber dzero; // work
  1042. #if DECCHECK
  1043. if (decCheckOperands(res, lhs, rhs, set)) return res;
  1044. if (decCheckOperands(res, fhs, DECUNUSED, set)) return res;
  1045. #endif
  1046. do { // protect allocated storage
  1047. #if DECSUBSET
  1048. if (!set->extended) { // [undefined if subset]
  1049. status|=DEC_Invalid_operation;
  1050. break;}
  1051. #endif
  1052. // Check math restrictions [these ensure no overflow or underflow]
  1053. if ((!decNumberIsSpecial(lhs) && decCheckMath(lhs, set, &status))
  1054. || (!decNumberIsSpecial(rhs) && decCheckMath(rhs, set, &status))
  1055. || (!decNumberIsSpecial(fhs) && decCheckMath(fhs, set, &status))) break;
  1056. // set up context for multiply
  1057. dcmul=*set;
  1058. dcmul.digits=lhs->digits+rhs->digits; // just enough
  1059. // [The above may be an over-estimate for subset arithmetic, but that's OK]
  1060. dcmul.emax=DEC_MAX_EMAX; // effectively unbounded ..
  1061. dcmul.emin=DEC_MIN_EMIN; // [thanks to Math restrictions]
  1062. // set up decNumber space to receive the result of the multiply
  1063. acc=bufa; // may fit
  1064. needbytes=sizeof(decNumber)+(D2U(dcmul.digits)-1)*sizeof(Unit);
  1065. if (needbytes>sizeof(bufa)) { // need malloc space
  1066. allocbufa=(decNumber *)malloc(needbytes);
  1067. if (allocbufa==NULL) { // hopeless -- abandon
  1068. status|=DEC_Insufficient_storage;
  1069. break;}
  1070. acc=allocbufa; // use the allocated space
  1071. }
  1072. // multiply with extended range and necessary precision
  1073. //printf("emin=%ld\n", dcmul.emin);
  1074. decMultiplyOp(acc, lhs, rhs, &dcmul, &status);
  1075. // Only Invalid operation (from sNaN or Inf * 0) is possible in
  1076. // status; if either is seen than ignore fhs (in case it is
  1077. // another sNaN) and set acc to NaN unless we had an sNaN
  1078. // [decMultiplyOp leaves that to caller]
  1079. // Note sNaN has to go through addOp to shorten payload if
  1080. // necessary
  1081. if ((status&DEC_Invalid_operation)!=0) {
  1082. if (!(status&DEC_sNaN)) { // but be true invalid
  1083. decNumberZero(res); // acc not yet set
  1084. res->bits=DECNAN;
  1085. break;
  1086. }
  1087. decNumberZero(&dzero); // make 0 (any non-NaN would do)
  1088. fhs=&dzero; // use that
  1089. }
  1090. #if DECCHECK
  1091. else { // multiply was OK
  1092. if (status!=0) printf("Status=%08lx after FMA multiply\n", (LI)status);
  1093. }
  1094. #endif
  1095. // add the third operand and result -> res, and all is done
  1096. decAddOp(res, acc, fhs, set, 0, &status);
  1097. } while(0); // end protected
  1098. if (allocbufa!=NULL) free(allocbufa); // drop any storage used
  1099. if (status!=0) decStatus(res, status, set);
  1100. #if DECCHECK
  1101. decCheckInexact(res, set);
  1102. #endif
  1103. return res;
  1104. } // decNumberFMA
  1105. /* ------------------------------------------------------------------ */
  1106. /* decNumberInvert -- invert a Number, digitwise */
  1107. /* */
  1108. /* This computes C = ~A */
  1109. /* */
  1110. /* res is C, the result. C may be A (e.g., X=~X) */
  1111. /* rhs is A */
  1112. /* set is the context (used for result length and error report) */
  1113. /* */
  1114. /* C must have space for set->digits digits. */
  1115. /* */
  1116. /* Logical function restrictions apply (see above); a NaN is */
  1117. /* returned with Invalid_operation if a restriction is violated. */
  1118. /* ------------------------------------------------------------------ */
  1119. decNumber * decNumberInvert(decNumber *res, const decNumber *rhs,
  1120. decContext *set) {
  1121. const Unit *ua, *msua; // -> operand and its msu
  1122. Unit *uc, *msuc; // -> result and its msu
  1123. Int msudigs; // digits in res msu
  1124. #if DECCHECK
  1125. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  1126. #endif
  1127. if (rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
  1128. decStatus(res, DEC_Invalid_operation, set);
  1129. return res;
  1130. }
  1131. // operand is valid
  1132. ua=rhs->lsu; // bottom-up
  1133. uc=res->lsu; // ..
  1134. msua=ua+D2U(rhs->digits)-1; // -> msu of rhs
  1135. msuc=uc+D2U(set->digits)-1; // -> msu of result
  1136. msudigs=MSUDIGITS(set->digits); // [faster than remainder]
  1137. for (; uc<=msuc; ua++, uc++) { // Unit loop
  1138. Unit a; // extract unit
  1139. Int i, j; // work
  1140. if (ua>msua) a=0;
  1141. else a=*ua;
  1142. *uc=0; // can now write back
  1143. // always need to examine all bits in rhs
  1144. // This loop could be unrolled and/or use BIN2BCD tables
  1145. for (i=0; i<DECDPUN; i++) {
  1146. if ((~a)&1) *uc=*uc+(Unit)powers[i]; // effect INVERT
  1147. j=a%10;
  1148. a=a/10;
  1149. if (j>1) {
  1150. decStatus(res, DEC_Invalid_operation, set);
  1151. return res;
  1152. }
  1153. if (uc==msuc && i==msudigs-1) break; // just did final digit
  1154. } // each digit
  1155. } // each unit
  1156. // [here uc-1 is the msu of the result]
  1157. res->digits=decGetDigits(res->lsu, uc-res->lsu);
  1158. res->exponent=0; // integer
  1159. res->bits=0; // sign=0
  1160. return res; // [no status to set]
  1161. } // decNumberInvert
  1162. /* ------------------------------------------------------------------ */
  1163. /* decNumberLn -- natural logarithm */
  1164. /* */
  1165. /* This computes C = ln(A) */
  1166. /* */
  1167. /* res is C, the result. C may be A */
  1168. /* rhs is A */
  1169. /* set is the context; note that rounding mode has no effect */
  1170. /* */
  1171. /* C must have space for set->digits digits. */
  1172. /* */
  1173. /* Notable cases: */
  1174. /* A<0 -> Invalid */
  1175. /* A=0 -> -Infinity (Exact) */
  1176. /* A=+Infinity -> +Infinity (Exact) */
  1177. /* A=1 exactly -> 0 (Exact) */
  1178. /* */
  1179. /* Mathematical function restrictions apply (see above); a NaN is */
  1180. /* returned with Invalid_operation if a restriction is violated. */
  1181. /* */
  1182. /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */
  1183. /* almost always be correctly rounded, but may be up to 1 ulp in */
  1184. /* error in rare cases. */
  1185. /* ------------------------------------------------------------------ */
  1186. /* This is a wrapper for decLnOp which can handle the slightly wider */
  1187. /* (+11) range needed by Ln, Log10, etc. (which may have to be able */
  1188. /* to calculate at p+e+2). */
  1189. /* ------------------------------------------------------------------ */
  1190. decNumber * decNumberLn(decNumber *res, const decNumber *rhs,
  1191. decContext *set) {
  1192. uInt status=0; // accumulator
  1193. #if DECSUBSET
  1194. decNumber *allocrhs=NULL; // non-NULL if rounded rhs allocated
  1195. #endif
  1196. #if DECCHECK
  1197. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  1198. #endif
  1199. // Check restrictions; this is a math function; if not violated
  1200. // then carry out the operation.
  1201. if (!decCheckMath(rhs, set, &status)) do { // protect allocation
  1202. #if DECSUBSET
  1203. if (!set->extended) {
  1204. // reduce operand and set lostDigits status, as needed
  1205. if (rhs->digits>set->digits) {
  1206. allocrhs=decRoundOperand(rhs, set, &status);
  1207. if (allocrhs==NULL) break;
  1208. rhs=allocrhs;
  1209. }
  1210. // special check in subset for rhs=0
  1211. if (ISZERO(rhs)) { // +/- zeros -> error
  1212. status|=DEC_Invalid_operation;
  1213. break;}
  1214. } // extended=0
  1215. #endif
  1216. decLnOp(res, rhs, set, &status);
  1217. } while(0); // end protected
  1218. #if DECSUBSET
  1219. if (allocrhs !=NULL) free(allocrhs); // drop any storage used
  1220. #endif
  1221. // apply significant status
  1222. if (status!=0) decStatus(res, status, set);
  1223. #if DECCHECK
  1224. decCheckInexact(res, set);
  1225. #endif
  1226. return res;
  1227. } // decNumberLn
  1228. /* ------------------------------------------------------------------ */
  1229. /* decNumberLogB - get adjusted exponent, by 754 rules */
  1230. /* */
  1231. /* This computes C = adjustedexponent(A) */
  1232. /* */
  1233. /* res is C, the result. C may be A */
  1234. /* rhs is A */
  1235. /* set is the context, used only for digits and status */
  1236. /* */
  1237. /* For an unrounded result, digits may need to be 10 (A might have */
  1238. /* 10**9 digits and an exponent of +999999999, or one digit and an */
  1239. /* exponent of -1999999999). */
  1240. /* */
  1241. /* This returns the adjusted exponent of A after (in theory) padding */
  1242. /* with zeros on the right to set->digits digits while keeping the */
  1243. /* same value. The exponent is not limited by emin/emax. */
  1244. /* */
  1245. /* Notable cases: */
  1246. /* A<0 -> Use |A| */
  1247. /* A=0 -> -Infinity (Division by zero) */
  1248. /* A=Infinite -> +Infinity (Exact) */
  1249. /* A=1 exactly -> 0 (Exact) */
  1250. /* NaNs are propagated as usual */
  1251. /* ------------------------------------------------------------------ */
  1252. decNumber * decNumberLogB(decNumber *res, const decNumber *rhs,
  1253. decContext *set) {
  1254. uInt status=0; // accumulator
  1255. #if DECCHECK
  1256. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  1257. #endif
  1258. // NaNs as usual; Infinities return +Infinity; 0->oops
  1259. if (decNumberIsNaN(rhs)) decNaNs(res, rhs, NULL, set, &status);
  1260. else if (decNumberIsInfinite(rhs)) decNumberCopyAbs(res, rhs);
  1261. else if (decNumberIsZero(rhs)) {
  1262. decNumberZero(res); // prepare for Infinity
  1263. res->bits=DECNEG|DECINF; // -Infinity
  1264. status|=DEC_Division_by_zero; // as per 754
  1265. }
  1266. else { // finite non-zero
  1267. Int ae=rhs->exponent+rhs->digits-1; // adjusted exponent
  1268. if (set->digits>=10) decNumberFromInt32(res, ae); // lay it out
  1269. else {
  1270. decNumber buft[D2N(10)]; // temporary number
  1271. decNumber *t=buft; // ..
  1272. decNumberFromInt32(t, ae); // lay it out
  1273. decNumberPlus(res, t, set); // round as necessary
  1274. }
  1275. }
  1276. if (status!=0) decStatus(res, status, set);
  1277. return res;
  1278. } // decNumberLogB
  1279. /* ------------------------------------------------------------------ */
  1280. /* decNumberLog10 -- logarithm in base 10 */
  1281. /* */
  1282. /* This computes C = log10(A) */
  1283. /* */
  1284. /* res is C, the result. C may be A */
  1285. /* rhs is A */
  1286. /* set is the context; note that rounding mode has no effect */
  1287. /* */
  1288. /* C must have space for set->digits digits. */
  1289. /* */
  1290. /* Notable cases: */
  1291. /* A<0 -> Invalid */
  1292. /* A=0 -> -Infinity (Exact) */
  1293. /* A=+Infinity -> +Infinity (Exact) */
  1294. /* A=10**n (if n is an integer) -> n (Exact) */
  1295. /* */
  1296. /* Mathematical function restrictions apply (see above); a NaN is */
  1297. /* returned with Invalid_operation if a restriction is violated. */
  1298. /* */
  1299. /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */
  1300. /* almost always be correctly rounded, but may be up to 1 ulp in */
  1301. /* error in rare cases. */
  1302. /* ------------------------------------------------------------------ */
  1303. /* This calculates ln(A)/ln(10) using appropriate precision. For */
  1304. /* ln(A) this is the max(p, rhs->digits + t) + 3, where p is the */
  1305. /* requested digits and t is the number of digits in the exponent */
  1306. /* (maximum 6). For ln(10) it is p + 3; this is often handled by the */
  1307. /* fastpath in decLnOp. The final division is done to the requested */
  1308. /* precision. */
  1309. /* ------------------------------------------------------------------ */
  1310. decNumber * decNumberLog10(decNumber *res, const decNumber *rhs,
  1311. decContext *set) {
  1312. uInt status=0, ignore=0; // status accumulators
  1313. uInt needbytes; // for space calculations
  1314. Int p; // working precision
  1315. Int t; // digits in exponent of A
  1316. // buffers for a and b working decimals
  1317. // (adjustment calculator, same size)
  1318. decNumber bufa[D2N(DECBUFFER+2)];
  1319. decNumber *allocbufa=NULL; // -> allocated bufa, iff allocated
  1320. decNumber *a=bufa; // temporary a
  1321. decNumber bufb[D2N(DECBUFFER+2)];
  1322. decNumber *allocbufb=NULL; // -> allocated bufb, iff allocated
  1323. decNumber *b=bufb; // temporary b
  1324. decNumber bufw[D2N(10)]; // working 2-10 digit number
  1325. decNumber *w=bufw; // ..
  1326. #if DECSUBSET
  1327. decNumber *allocrhs=NULL; // non-NULL if rounded rhs allocated
  1328. #endif
  1329. decContext aset; // working context
  1330. #if DECCHECK
  1331. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  1332. #endif
  1333. // Check restrictions; this is a math function; if not violated
  1334. // then carry out the operation.
  1335. if (!decCheckMath(rhs, set, &status)) do { // protect malloc
  1336. #if DECSUBSET
  1337. if (!set->extended) {
  1338. // reduce operand and set lostDigits status, as needed
  1339. if (rhs->digits>set->digits) {
  1340. allocrhs=decRoundOperand(rhs, set, &status);
  1341. if (allocrhs==NULL) break;
  1342. rhs=allocrhs;
  1343. }
  1344. // special check in subset for rhs=0
  1345. if (ISZERO(rhs)) { // +/- zeros -> error
  1346. status|=DEC_Invalid_operation;
  1347. break;}
  1348. } // extended=0
  1349. #endif
  1350. decContextDefault(&aset, DEC_INIT_DECIMAL64); // clean context
  1351. // handle exact powers of 10; only check if +ve finite
  1352. if (!(rhs->bits&(DECNEG|DECSPECIAL)) && !ISZERO(rhs)) {
  1353. Int residue=0; // (no residue)
  1354. uInt copystat=0; // clean status
  1355. // round to a single digit...
  1356. aset.digits=1;
  1357. decCopyFit(w, rhs, &aset, &residue, &copystat); // copy & shorten
  1358. // if exact and the digit is 1, rhs is a power of 10
  1359. if (!(copystat&DEC_Inexact) && w->lsu[0]==1) {
  1360. // the exponent, conveniently, is the power of 10; making
  1361. // this the result needs a little care as it might not fit,
  1362. // so first convert it into the working number, and then move
  1363. // to res
  1364. decNumberFromInt32(w, w->exponent);
  1365. residue=0;
  1366. decCopyFit(res, w, set, &residue, &status); // copy & round
  1367. decFinish(res, set, &residue, &status); // cleanup/set flags
  1368. break;
  1369. } // not a power of 10
  1370. } // not a candidate for exact
  1371. // simplify the information-content calculation to use 'total
  1372. // number of digits in a, including exponent' as compared to the
  1373. // requested digits, as increasing this will only rarely cost an
  1374. // iteration in ln(a) anyway
  1375. t=6; // it can never be >6
  1376. // allocate space when needed...
  1377. p=(rhs->digits+t>set->digits?rhs->digits+t:set->digits)+3;
  1378. needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
  1379. if (needbytes>sizeof(bufa)) { // need malloc space
  1380. allocbufa=(decNumber *)malloc(needbytes);
  1381. if (allocbufa==NULL) { // hopeless -- abandon
  1382. status|=DEC_Insufficient_storage;
  1383. break;}
  1384. a=allocbufa; // use the allocated space
  1385. }
  1386. aset.digits=p; // as calculated
  1387. aset.emax=DEC_MAX_MATH; // usual bounds
  1388. aset.emin=-DEC_MAX_MATH; // ..
  1389. aset.clamp=0; // and no concrete format
  1390. decLnOp(a, rhs, &aset, &status); // a=ln(rhs)
  1391. // skip the division if the result so far is infinite, NaN, or
  1392. // zero, or there was an error; note NaN from sNaN needs copy
  1393. if (status&DEC_NaNs && !(status&DEC_sNaN)) break;
  1394. if (a->bits&DECSPECIAL || ISZERO(a)) {
  1395. decNumberCopy(res, a); // [will fit]
  1396. break;}
  1397. // for ln(10) an extra 3 digits of precision are needed
  1398. p=set->digits+3;
  1399. needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
  1400. if (needbytes>sizeof(bufb)) { // need malloc space
  1401. allocbufb=(decNumber *)malloc(needbytes);
  1402. if (allocbufb==NULL) { // hopeless -- abandon
  1403. status|=DEC_Insufficient_storage;
  1404. break;}
  1405. b=allocbufb; // use the allocated space
  1406. }
  1407. decNumberZero(w); // set up 10...
  1408. #if DECDPUN==1
  1409. w->lsu[1]=1; w->lsu[0]=0; // ..
  1410. #else
  1411. w->lsu[0]=10; // ..
  1412. #endif
  1413. w->digits=2; // ..
  1414. aset.digits=p;
  1415. decLnOp(b, w, &aset, &ignore); // b=ln(10)
  1416. aset.digits=set->digits; // for final divide
  1417. decDivideOp(res, a, b, &aset, DIVIDE, &status); // into result
  1418. } while(0); // [for break]
  1419. if (allocbufa!=NULL) free(allocbufa); // drop any storage used
  1420. if (allocbufb!=NULL) free(allocbufb); // ..
  1421. #if DECSUBSET
  1422. if (allocrhs !=NULL) free(allocrhs); // ..
  1423. #endif
  1424. // apply significant status
  1425. if (status!=0) decStatus(res, status, set);
  1426. #if DECCHECK
  1427. decCheckInexact(res, set);
  1428. #endif
  1429. return res;
  1430. } // decNumberLog10
  1431. /* ------------------------------------------------------------------ */
  1432. /* decNumberMax -- compare two Numbers and return the maximum */
  1433. /* */
  1434. /* This computes C = A ? B, returning the maximum by 754 rules */
  1435. /* */
  1436. /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
  1437. /* lhs is A */
  1438. /* rhs is B */
  1439. /* set is the context */
  1440. /* */
  1441. /* C must have space for set->digits digits. */
  1442. /* ------------------------------------------------------------------ */
  1443. decNumber * decNumberMax(decNumber *res, const decNumber *lhs,
  1444. const decNumber *rhs, decContext *set) {
  1445. uInt status=0; // accumulator
  1446. decCompareOp(res, lhs, rhs, set, COMPMAX, &status);
  1447. if (status!=0) decStatus(res, status, set);
  1448. #if DECCHECK
  1449. decCheckInexact(res, set);
  1450. #endif
  1451. return res;
  1452. } // decNumberMax
  1453. /* ------------------------------------------------------------------ */
  1454. /* decNumberMaxMag -- compare and return the maximum by magnitude */
  1455. /* */
  1456. /* This computes C = A ? B, returning the maximum by 754 rules */
  1457. /* */
  1458. /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
  1459. /* lhs is A */
  1460. /* rhs is B */
  1461. /* set is the context */
  1462. /* */
  1463. /* C must have space for set->digits digits. */
  1464. /* ------------------------------------------------------------------ */
  1465. decNumber * decNumberMaxMag(decNumber *res, const decNumber *lhs,
  1466. const decNumber *rhs, decContext *set) {
  1467. uInt status=0; // accumulator
  1468. decCompareOp(res, lhs, rhs, set, COMPMAXMAG, &status);
  1469. if (status!=0) decStatus(res, status, set);
  1470. #if DECCHECK
  1471. decCheckInexact(res, set);
  1472. #endif
  1473. return res;
  1474. } // decNumberMaxMag
  1475. /* ------------------------------------------------------------------ */
  1476. /* decNumberMin -- compare two Numbers and return the minimum */
  1477. /* */
  1478. /* This computes C = A ? B, returning the minimum by 754 rules */
  1479. /* */
  1480. /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
  1481. /* lhs is A */
  1482. /* rhs is B */
  1483. /* set is the context */
  1484. /* */
  1485. /* C must have space for set->digits digits. */
  1486. /* ------------------------------------------------------------------ */
  1487. decNumber * decNumberMin(decNumber *res, const decNumber *lhs,
  1488. const decNumber *rhs, decContext *set) {
  1489. uInt status=0; // accumulator
  1490. decCompareOp(res, lhs, rhs, set, COMPMIN, &status);
  1491. if (status!=0) decStatus(res, status, set);
  1492. #if DECCHECK
  1493. decCheckInexact(res, set);
  1494. #endif
  1495. return res;
  1496. } // decNumberMin
  1497. /* ------------------------------------------------------------------ */
  1498. /* decNumberMinMag -- compare and return the minimum by magnitude */
  1499. /* */
  1500. /* This computes C = A ? B, returning the minimum by 754 rules */
  1501. /* */
  1502. /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
  1503. /* lhs is A */
  1504. /* rhs is B */
  1505. /* set is the context */
  1506. /* */
  1507. /* C must have space for set->digits digits. */
  1508. /* ------------------------------------------------------------------ */
  1509. decNumber * decNumberMinMag(decNumber *res, const decNumber *lhs,
  1510. const decNumber *rhs, decContext *set) {
  1511. uInt status=0; // accumulator
  1512. decCompareOp(res, lhs, rhs, set, COMPMINMAG, &status);
  1513. if (status!=0) decStatus(res, status, set);
  1514. #if DECCHECK
  1515. decCheckInexact(res, set);
  1516. #endif
  1517. return res;
  1518. } // decNumberMinMag
  1519. /* ------------------------------------------------------------------ */
  1520. /* decNumberMinus -- prefix minus operator */
  1521. /* */
  1522. /* This computes C = 0 - A */
  1523. /* */
  1524. /* res is C, the result. C may be A */
  1525. /* rhs is A */
  1526. /* set is the context */
  1527. /* */
  1528. /* See also decNumberCopyNegate for a quiet bitwise version of this. */
  1529. /* C must have space for set->digits digits. */
  1530. /* ------------------------------------------------------------------ */
  1531. /* Simply use AddOp for the subtract, which will do the necessary. */
  1532. /* ------------------------------------------------------------------ */
  1533. decNumber * decNumberMinus(decNumber *res, const decNumber *rhs,
  1534. decContext *set) {
  1535. decNumber dzero;
  1536. uInt status=0; // accumulator
  1537. #if DECCHECK
  1538. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  1539. #endif
  1540. decNumberZero(&dzero); // make 0
  1541. dzero.exponent=rhs->exponent; // [no coefficient expansion]
  1542. decAddOp(res, &dzero, rhs, set, DECNEG, &status);
  1543. if (status!=0) decStatus(res, status, set);
  1544. #if DECCHECK
  1545. decCheckInexact(res, set);
  1546. #endif
  1547. return res;
  1548. } // decNumberMinus
  1549. /* ------------------------------------------------------------------ */
  1550. /* decNumberNextMinus -- next towards -Infinity */
  1551. /* */
  1552. /* This computes C = A - infinitesimal, rounded towards -Infinity */
  1553. /* */
  1554. /* res is C, the result. C may be A */
  1555. /* rhs is A */
  1556. /* set is the context */
  1557. /* */
  1558. /* This is a generalization of 754 NextDown. */
  1559. /* ------------------------------------------------------------------ */
  1560. decNumber * decNumberNextMinus(decNumber *res, const decNumber *rhs,
  1561. decContext *set) {
  1562. decNumber dtiny; // constant
  1563. decContext workset=*set; // work
  1564. uInt status=0; // accumulator
  1565. #if DECCHECK
  1566. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  1567. #endif
  1568. // +Infinity is the special case
  1569. if ((rhs->bits&(DECINF|DECNEG))==DECINF) {
  1570. decSetMaxValue(res, set); // is +ve
  1571. // there is no status to set
  1572. return res;
  1573. }
  1574. decNumberZero(&dtiny); // start with 0
  1575. dtiny.lsu[0]=1; // make number that is ..
  1576. dtiny.exponent=DEC_MIN_EMIN-1; // .. smaller than tiniest
  1577. workset.round=DEC_ROUND_FLOOR;
  1578. decAddOp(res, rhs, &dtiny, &workset, DECNEG, &status);
  1579. status&=DEC_Invalid_operation|DEC_sNaN; // only sNaN Invalid please
  1580. if (status!=0) decStatus(res, status, set);
  1581. return res;
  1582. } // decNumberNextMinus
  1583. /* ------------------------------------------------------------------ */
  1584. /* decNumberNextPlus -- next towards +Infinity */
  1585. /* */
  1586. /* This computes C = A + infinitesimal, rounded towards +Infinity */
  1587. /* */
  1588. /* res is C, the result. C may be A */
  1589. /* rhs is A */
  1590. /* set is the context */
  1591. /* */
  1592. /* This is a generalization of 754 NextUp. */
  1593. /* ------------------------------------------------------------------ */
  1594. decNumber * decNumberNextPlus(decNumber *res, const decNumber *rhs,
  1595. decContext *set) {
  1596. decNumber dtiny; // constant
  1597. decContext workset=*set; // work
  1598. uInt status=0; // accumulator
  1599. #if DECCHECK
  1600. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  1601. #endif
  1602. // -Infinity is the special case
  1603. if ((rhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
  1604. decSetMaxValue(res, set);
  1605. res->bits=DECNEG; // negative
  1606. // there is no status to set
  1607. return res;
  1608. }
  1609. decNumberZero(&dtiny); // start with 0
  1610. dtiny.lsu[0]=1; // make number that is ..
  1611. dtiny.exponent=DEC_MIN_EMIN-1; // .. smaller than tiniest
  1612. workset.round=DEC_ROUND_CEILING;
  1613. decAddOp(res, rhs, &dtiny, &workset, 0, &status);
  1614. status&=DEC_Invalid_operation|DEC_sNaN; // only sNaN Invalid please
  1615. if (status!=0) decStatus(res, status, set);
  1616. return res;
  1617. } // decNumberNextPlus
  1618. /* ------------------------------------------------------------------ */
  1619. /* decNumberNextToward -- next towards rhs */
  1620. /* */
  1621. /* This computes C = A +/- infinitesimal, rounded towards */
  1622. /* +/-Infinity in the direction of B, as per 754-1985 nextafter */
  1623. /* modified during revision but dropped from 754-2008. */
  1624. /* */
  1625. /* res is C, the result. C may be A or B. */
  1626. /* lhs is A */
  1627. /* rhs is B */
  1628. /* set is the context */
  1629. /* */
  1630. /* This is a generalization of 754-1985 NextAfter. */
  1631. /* ------------------------------------------------------------------ */
  1632. decNumber * decNumberNextToward(decNumber *res, const decNumber *lhs,
  1633. const decNumber *rhs, decContext *set) {
  1634. decNumber dtiny; // constant
  1635. decContext workset=*set; // work
  1636. Int result; // ..
  1637. uInt status=0; // accumulator
  1638. #if DECCHECK
  1639. if (decCheckOperands(res, lhs, rhs, set)) return res;
  1640. #endif
  1641. if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) {
  1642. decNaNs(res, lhs, rhs, set, &status);
  1643. }
  1644. else { // Is numeric, so no chance of sNaN Invalid, etc.
  1645. result=decCompare(lhs, rhs, 0); // sign matters
  1646. if (result==BADINT) status|=DEC_Insufficient_storage; // rare
  1647. else { // valid compare
  1648. if (result==0) decNumberCopySign(res, lhs, rhs); // easy
  1649. else { // differ: need NextPlus or NextMinus
  1650. uByte sub; // add or subtract
  1651. if (result<0) { // lhs<rhs, do nextplus
  1652. // -Infinity is the special case
  1653. if ((lhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
  1654. decSetMaxValue(res, set);
  1655. res->bits=DECNEG; // negative
  1656. return res; // there is no status to set
  1657. }
  1658. workset.round=DEC_ROUND_CEILING;
  1659. sub=0; // add, please
  1660. } // plus
  1661. else { // lhs>rhs, do nextminus
  1662. // +Infinity is the special case
  1663. if ((lhs->bits&(DECINF|DECNEG))==DECINF) {
  1664. decSetMaxValue(res, set);
  1665. return res; // there is no status to set
  1666. }
  1667. workset.round=DEC_ROUND_FLOOR;
  1668. sub=DECNEG; // subtract, please
  1669. } // minus
  1670. decNumberZero(&dtiny); // start with 0
  1671. dtiny.lsu[0]=1; // make number that is ..
  1672. dtiny.exponent=DEC_MIN_EMIN-1; // .. smaller than tiniest
  1673. decAddOp(res, lhs, &dtiny, &workset, sub, &status); // + or -
  1674. // turn off exceptions if the result is a normal number
  1675. // (including Nmin), otherwise let all status through
  1676. if (decNumberIsNormal(res, set)) status=0;
  1677. } // unequal
  1678. } // compare OK
  1679. } // numeric
  1680. if (status!=0) decStatus(res, status, set);
  1681. return res;
  1682. } // decNumberNextToward
  1683. /* ------------------------------------------------------------------ */
  1684. /* decNumberOr -- OR two Numbers, digitwise */
  1685. /* */
  1686. /* This computes C = A | B */
  1687. /* */
  1688. /* res is C, the result. C may be A and/or B (e.g., X=X|X) */
  1689. /* lhs is A */
  1690. /* rhs is B */
  1691. /* set is the context (used for result length and error report) */
  1692. /* */
  1693. /* C must have space for set->digits digits. */
  1694. /* */
  1695. /* Logical function restrictions apply (see above); a NaN is */
  1696. /* returned with Invalid_operation if a restriction is violated. */
  1697. /* ------------------------------------------------------------------ */
  1698. decNumber * decNumberOr(decNumber *res, const decNumber *lhs,
  1699. const decNumber *rhs, decContext *set) {
  1700. const Unit *ua, *ub; // -> operands
  1701. const Unit *msua, *msub; // -> operand msus
  1702. Unit *uc, *msuc; // -> result and its msu
  1703. Int msudigs; // digits in res msu
  1704. #if DECCHECK
  1705. if (decCheckOperands(res, lhs, rhs, set)) return res;
  1706. #endif
  1707. if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
  1708. || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
  1709. decStatus(res, DEC_Invalid_operation, set);
  1710. return res;
  1711. }
  1712. // operands are valid
  1713. ua=lhs->lsu; // bottom-up
  1714. ub=rhs->lsu; // ..
  1715. uc=res->lsu; // ..
  1716. msua=ua+D2U(lhs->digits)-1; // -> msu of lhs
  1717. msub=ub+D2U(rhs->digits)-1; // -> msu of rhs
  1718. msuc=uc+D2U(set->digits)-1; // -> msu of result
  1719. msudigs=MSUDIGITS(set->digits); // [faster than remainder]
  1720. for (; uc<=msuc; ua++, ub++, uc++) { // Unit loop
  1721. Unit a, b; // extract units
  1722. if (ua>msua) a=0;
  1723. else a=*ua;
  1724. if (ub>msub) b=0;
  1725. else b=*ub;
  1726. *uc=0; // can now write back
  1727. if (a|b) { // maybe 1 bits to examine
  1728. Int i, j;
  1729. // This loop could be unrolled and/or use BIN2BCD tables
  1730. for (i=0; i<DECDPUN; i++) {
  1731. if ((a|b)&1) *uc=*uc+(Unit)powers[i]; // effect OR
  1732. j=a%10;
  1733. a=a/10;
  1734. j|=b%10;
  1735. b=b/10;
  1736. if (j>1) {
  1737. decStatus(res, DEC_Invalid_operation, set);
  1738. return res;
  1739. }
  1740. if (uc==msuc && i==msudigs-1) break; // just did final digit
  1741. } // each digit
  1742. } // non-zero
  1743. } // each unit
  1744. // [here uc-1 is the msu of the result]
  1745. res->digits=decGetDigits(res->lsu, uc-res->lsu);
  1746. res->exponent=0; // integer
  1747. res->bits=0; // sign=0
  1748. return res; // [no status to set]
  1749. } // decNumberOr
  1750. /* ------------------------------------------------------------------ */
  1751. /* decNumberPlus -- prefix plus operator */
  1752. /* */
  1753. /* This computes C = 0 + A */
  1754. /* */
  1755. /* res is C, the result. C may be A */
  1756. /* rhs is A */
  1757. /* set is the context */
  1758. /* */
  1759. /* See also decNumberCopy for a quiet bitwise version of this. */
  1760. /* C must have space for set->digits digits. */
  1761. /* ------------------------------------------------------------------ */
  1762. /* This simply uses AddOp; Add will take fast path after preparing A. */
  1763. /* Performance is a concern here, as this routine is often used to */
  1764. /* check operands and apply rounding and overflow/underflow testing. */
  1765. /* ------------------------------------------------------------------ */
  1766. decNumber * decNumberPlus(decNumber *res, const decNumber *rhs,
  1767. decContext *set) {
  1768. decNumber dzero;
  1769. uInt status=0; // accumulator
  1770. #if DECCHECK
  1771. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  1772. #endif
  1773. decNumberZero(&dzero); // make 0
  1774. dzero.exponent=rhs->exponent; // [no coefficient expansion]
  1775. decAddOp(res, &dzero, rhs, set, 0, &status);
  1776. if (status!=0) decStatus(res, status, set);
  1777. #if DECCHECK
  1778. decCheckInexact(res, set);
  1779. #endif
  1780. return res;
  1781. } // decNumberPlus
  1782. /* ------------------------------------------------------------------ */
  1783. /* decNumberMultiply -- multiply two Numbers */
  1784. /* */
  1785. /* This computes C = A x B */
  1786. /* */
  1787. /* res is C, the result. C may be A and/or B (e.g., X=X+X) */
  1788. /* lhs is A */
  1789. /* rhs is B */
  1790. /* set is the context */
  1791. /* */
  1792. /* C must have space for set->digits digits. */
  1793. /* ------------------------------------------------------------------ */
  1794. decNumber * decNumberMultiply(decNumber *res, const decNumber *lhs,
  1795. const decNumber *rhs, decContext *set) {
  1796. uInt status=0; // accumulator
  1797. decMultiplyOp(res, lhs, rhs, set, &status);
  1798. if (status!=0) decStatus(res, status, set);
  1799. #if DECCHECK
  1800. decCheckInexact(res, set);
  1801. #endif
  1802. return res;
  1803. } // decNumberMultiply
  1804. /* ------------------------------------------------------------------ */
  1805. /* decNumberPower -- raise a number to a power */
  1806. /* */
  1807. /* This computes C = A ** B */
  1808. /* */
  1809. /* res is C, the result. C may be A and/or B (e.g., X=X**X) */
  1810. /* lhs is A */
  1811. /* rhs is B */
  1812. /* set is the context */
  1813. /* */
  1814. /* C must have space for set->digits digits. */
  1815. /* */
  1816. /* Mathematical function restrictions apply (see above); a NaN is */
  1817. /* returned with Invalid_operation if a restriction is violated. */
  1818. /* */
  1819. /* However, if 1999999997<=B<=999999999 and B is an integer then the */
  1820. /* restrictions on A and the context are relaxed to the usual bounds, */
  1821. /* for compatibility with the earlier (integer power only) version */
  1822. /* of this function. */
  1823. /* */
  1824. /* When B is an integer, the result may be exact, even if rounded. */
  1825. /* */
  1826. /* The final result is rounded according to the context; it will */
  1827. /* almost always be correctly rounded, but may be up to 1 ulp in */
  1828. /* error in rare cases. */
  1829. /* ------------------------------------------------------------------ */
  1830. decNumber * decNumberPower(decNumber *res, const decNumber *lhs,
  1831. const decNumber *rhs, decContext *set) {
  1832. #if DECSUBSET
  1833. decNumber *alloclhs=NULL; // non-NULL if rounded lhs allocated
  1834. decNumber *allocrhs=NULL; // .., rhs
  1835. #endif
  1836. decNumber *allocdac=NULL; // -> allocated acc buffer, iff used
  1837. decNumber *allocinv=NULL; // -> allocated 1/x buffer, iff used
  1838. Int reqdigits=set->digits; // requested DIGITS
  1839. Int n; // rhs in binary
  1840. Flag rhsint=0; // 1 if rhs is an integer
  1841. Flag useint=0; // 1 if can use integer calculation
  1842. Flag isoddint=0; // 1 if rhs is an integer and odd
  1843. Int i; // work
  1844. #if DECSUBSET
  1845. Int dropped; // ..
  1846. #endif
  1847. uInt needbytes; // buffer size needed
  1848. Flag seenbit; // seen a bit while powering
  1849. Int residue=0; // rounding residue
  1850. uInt status=0; // accumulators
  1851. uByte bits=0; // result sign if errors
  1852. decContext aset; // working context
  1853. decNumber dnOne; // work value 1...
  1854. // local accumulator buffer [a decNumber, with digits+elength+1 digits]
  1855. decNumber dacbuff[D2N(DECBUFFER+9)];
  1856. decNumber *dac=dacbuff; // -> result accumulator
  1857. // same again for possible 1/lhs calculation
  1858. decNumber invbuff[D2N(DECBUFFER+9)];
  1859. #if DECCHECK
  1860. if (decCheckOperands(res, lhs, rhs, set)) return res;
  1861. #endif
  1862. do { // protect allocated storage
  1863. #if DECSUBSET
  1864. if (!set->extended) { // reduce operands and set status, as needed
  1865. if (lhs->digits>reqdigits) {
  1866. alloclhs=decRoundOperand(lhs, set, &status);
  1867. if (alloclhs==NULL) break;
  1868. lhs=alloclhs;
  1869. }
  1870. if (rhs->digits>reqdigits) {
  1871. allocrhs=decRoundOperand(rhs, set, &status);
  1872. if (allocrhs==NULL) break;
  1873. rhs=allocrhs;
  1874. }
  1875. }
  1876. #endif
  1877. // [following code does not require input rounding]
  1878. // handle NaNs and rhs Infinity (lhs infinity is harder)
  1879. if (SPECIALARGS) {
  1880. if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) { // NaNs
  1881. decNaNs(res, lhs, rhs, set, &status);
  1882. break;}
  1883. if (decNumberIsInfinite(rhs)) { // rhs Infinity
  1884. Flag rhsneg=rhs->bits&DECNEG; // save rhs sign
  1885. if (decNumberIsNegative(lhs) // lhs<0
  1886. && !decNumberIsZero(lhs)) // ..
  1887. status|=DEC_Invalid_operation;
  1888. else { // lhs >=0
  1889. decNumberZero(&dnOne); // set up 1
  1890. dnOne.lsu[0]=1;
  1891. decNumberCompare(dac, lhs, &dnOne, set); // lhs ? 1
  1892. decNumberZero(res); // prepare for 0/1/Infinity
  1893. if (decNumberIsNegative(dac)) { // lhs<1
  1894. if (rhsneg) res->bits|=DECINF; // +Infinity [else is +0]
  1895. }
  1896. else if (dac->lsu[0]==0) { // lhs=1
  1897. // 1**Infinity is inexact, so return fully-padded 1.0000
  1898. Int shift=set->digits-1;
  1899. *res->lsu=1; // was 0, make int 1
  1900. res->digits=decShiftToMost(res->lsu, 1, shift);
  1901. res->exponent=-shift; // make 1.0000...
  1902. status|=DEC_Inexact|DEC_Rounded; // deemed inexact
  1903. }
  1904. else { // lhs>1
  1905. if (!rhsneg) res->bits|=DECINF; // +Infinity [else is +0]
  1906. }
  1907. } // lhs>=0
  1908. break;}
  1909. // [lhs infinity drops through]
  1910. } // specials
  1911. // Original rhs may be an integer that fits and is in range
  1912. n=decGetInt(rhs);
  1913. if (n!=BADINT) { // it is an integer
  1914. rhsint=1; // record the fact for 1**n
  1915. isoddint=(Flag)n&1; // [works even if big]
  1916. if (n!=BIGEVEN && n!=BIGODD) // can use integer path?
  1917. useint=1; // looks good
  1918. }
  1919. if (decNumberIsNegative(lhs) // -x ..
  1920. && isoddint) bits=DECNEG; // .. to an odd power
  1921. // handle LHS infinity
  1922. if (decNumberIsInfinite(lhs)) { // [NaNs already handled]
  1923. uByte rbits=rhs->bits; // save
  1924. decNumberZero(res); // prepare
  1925. if (n==0) *res->lsu=1; // [-]Inf**0 => 1
  1926. else {
  1927. // -Inf**nonint -> error
  1928. if (!rhsint && decNumberIsNegative(lhs)) {
  1929. status|=DEC_Invalid_operation; // -Inf**nonint is error
  1930. break;}
  1931. if (!(rbits & DECNEG)) bits|=DECINF; // was not a **-n
  1932. // [otherwise will be 0 or -0]
  1933. res->bits=bits;
  1934. }
  1935. break;}
  1936. // similarly handle LHS zero
  1937. if (decNumberIsZero(lhs)) {
  1938. if (n==0) { // 0**0 => Error
  1939. #if DECSUBSET
  1940. if (!set->extended) { // [unless subset]
  1941. decNumberZero(res);
  1942. *res->lsu=1; // return 1
  1943. break;}
  1944. #endif
  1945. status|=DEC_Invalid_operation;
  1946. }
  1947. else { // 0**x
  1948. uByte rbits=rhs->bits; // save
  1949. if (rbits & DECNEG) { // was a 0**(-n)
  1950. #if DECSUBSET
  1951. if (!set->extended) { // [bad if subset]
  1952. status|=DEC_Invalid_operation;
  1953. break;}
  1954. #endif
  1955. bits|=DECINF;
  1956. }
  1957. decNumberZero(res); // prepare
  1958. // [otherwise will be 0 or -0]
  1959. res->bits=bits;
  1960. }
  1961. break;}
  1962. // here both lhs and rhs are finite; rhs==0 is handled in the
  1963. // integer path. Next handle the non-integer cases
  1964. if (!useint) { // non-integral rhs
  1965. // any -ve lhs is bad, as is either operand or context out of
  1966. // bounds
  1967. if (decNumberIsNegative(lhs)) {
  1968. status|=DEC_Invalid_operation;
  1969. break;}
  1970. if (decCheckMath(lhs, set, &status)
  1971. || decCheckMath(rhs, set, &status)) break; // variable status
  1972. decContextDefault(&aset, DEC_INIT_DECIMAL64); // clean context
  1973. aset.emax=DEC_MAX_MATH; // usual bounds
  1974. aset.emin=-DEC_MAX_MATH; // ..
  1975. aset.clamp=0; // and no concrete format
  1976. // calculate the result using exp(ln(lhs)*rhs), which can
  1977. // all be done into the accumulator, dac. The precision needed
  1978. // is enough to contain the full information in the lhs (which
  1979. // is the total digits, including exponent), or the requested
  1980. // precision, if larger, + 4; 6 is used for the exponent
  1981. // maximum length, and this is also used when it is shorter
  1982. // than the requested digits as it greatly reduces the >0.5 ulp
  1983. // cases at little cost (because Ln doubles digits each
  1984. // iteration so a few extra digits rarely causes an extra
  1985. // iteration)
  1986. aset.digits=MAXI(lhs->digits, set->digits)+6+4;
  1987. } // non-integer rhs
  1988. else { // rhs is in-range integer
  1989. if (n==0) { // x**0 = 1
  1990. // (0**0 was handled above)
  1991. decNumberZero(res); // result=1
  1992. *res->lsu=1; // ..
  1993. break;}
  1994. // rhs is a non-zero integer
  1995. if (n<0) n=-n; // use abs(n)
  1996. aset=*set; // clone the context
  1997. aset.round=DEC_ROUND_HALF_EVEN; // internally use balanced
  1998. // calculate the working DIGITS
  1999. aset.digits=reqdigits+(rhs->digits+rhs->exponent)+2;
  2000. #if DECSUBSET
  2001. if (!set->extended) aset.digits--; // use classic precision
  2002. #endif
  2003. // it's an error if this is more than can be handled
  2004. if (aset.digits>DECNUMMAXP) {status|=DEC_Invalid_operation; break;}
  2005. } // integer path
  2006. // aset.digits is the count of digits for the accumulator needed
  2007. // if accumulator is too long for local storage, then allocate
  2008. needbytes=sizeof(decNumber)+(D2U(aset.digits)-1)*sizeof(Unit);
  2009. // [needbytes also used below if 1/lhs needed]
  2010. if (needbytes>sizeof(dacbuff)) {
  2011. allocdac=(decNumber *)malloc(needbytes);
  2012. if (allocdac==NULL) { // hopeless -- abandon
  2013. status|=DEC_Insufficient_storage;
  2014. break;}
  2015. dac=allocdac; // use the allocated space
  2016. }
  2017. // here, aset is set up and accumulator is ready for use
  2018. if (!useint) { // non-integral rhs
  2019. // x ** y; special-case x=1 here as it will otherwise always
  2020. // reduce to integer 1; decLnOp has a fastpath which detects
  2021. // the case of x=1
  2022. decLnOp(dac, lhs, &aset, &status); // dac=ln(lhs)
  2023. // [no error possible, as lhs 0 already handled]
  2024. if (ISZERO(dac)) { // x==1, 1.0, etc.
  2025. // need to return fully-padded 1.0000 etc., but rhsint->1
  2026. *dac->lsu=1; // was 0, make int 1
  2027. if (!rhsint) { // add padding
  2028. Int shift=set->digits-1;
  2029. dac->digits=decShiftToMost(dac->lsu, 1, shift);
  2030. dac->exponent=-shift; // make 1.0000...
  2031. status|=DEC_Inexact|DEC_Rounded; // deemed inexact
  2032. }
  2033. }
  2034. else {
  2035. decMultiplyOp(dac, dac, rhs, &aset, &status); // dac=dac*rhs
  2036. decExpOp(dac, dac, &aset, &status); // dac=exp(dac)
  2037. }
  2038. // and drop through for final rounding
  2039. } // non-integer rhs
  2040. else { // carry on with integer
  2041. decNumberZero(dac); // acc=1
  2042. *dac->lsu=1; // ..
  2043. // if a negative power the constant 1 is needed, and if not subset
  2044. // invert the lhs now rather than inverting the result later
  2045. if (decNumberIsNegative(rhs)) { // was a **-n [hence digits>0]
  2046. decNumber *inv=invbuff; // asssume use fixed buffer
  2047. decNumberCopy(&dnOne, dac); // dnOne=1; [needed now or later]
  2048. #if DECSUBSET
  2049. if (set->extended) { // need to calculate 1/lhs
  2050. #endif
  2051. // divide lhs into 1, putting result in dac [dac=1/dac]
  2052. decDivideOp(dac, &dnOne, lhs, &aset, DIVIDE, &status);
  2053. // now locate or allocate space for the inverted lhs
  2054. if (needbytes>sizeof(invbuff)) {
  2055. allocinv=(decNumber *)malloc(needbytes);
  2056. if (allocinv==NULL) { // hopeless -- abandon
  2057. status|=DEC_Insufficient_storage;
  2058. break;}
  2059. inv=allocinv; // use the allocated space
  2060. }
  2061. // [inv now points to big-enough buffer or allocated storage]
  2062. decNumberCopy(inv, dac); // copy the 1/lhs
  2063. decNumberCopy(dac, &dnOne); // restore acc=1
  2064. lhs=inv; // .. and go forward with new lhs
  2065. #if DECSUBSET
  2066. }
  2067. #endif
  2068. }
  2069. // Raise-to-the-power loop...
  2070. seenbit=0; // set once a 1-bit is encountered
  2071. for (i=1;;i++){ // for each bit [top bit ignored]
  2072. // abandon if had overflow or terminal underflow
  2073. if (status & (DEC_Overflow|DEC_Underflow)) { // interesting?
  2074. if (status&DEC_Overflow || ISZERO(dac)) break;
  2075. }
  2076. // [the following two lines revealed an optimizer bug in a C++
  2077. // compiler, with symptom: 5**3 -> 25, when n=n+n was used]
  2078. n=n<<1; // move next bit to testable position
  2079. if (n<0) { // top bit is set
  2080. seenbit=1; // OK, significant bit seen
  2081. decMultiplyOp(dac, dac, lhs, &aset, &status); // dac=dac*x
  2082. }
  2083. if (i==31) break; // that was the last bit
  2084. if (!seenbit) continue; // no need to square 1
  2085. decMultiplyOp(dac, dac, dac, &aset, &status); // dac=dac*dac [square]
  2086. } /*i*/ // 32 bits
  2087. // complete internal overflow or underflow processing
  2088. if (status & (DEC_Overflow|DEC_Underflow)) {
  2089. #if DECSUBSET
  2090. // If subset, and power was negative, reverse the kind of -erflow
  2091. // [1/x not yet done]
  2092. if (!set->extended && decNumberIsNegative(rhs)) {
  2093. if (status & DEC_Overflow)
  2094. status^=DEC_Overflow | DEC_Underflow | DEC_Subnormal;
  2095. else { // trickier -- Underflow may or may not be set
  2096. status&=~(DEC_Underflow | DEC_Subnormal); // [one or both]
  2097. status|=DEC_Overflow;
  2098. }
  2099. }
  2100. #endif
  2101. dac->bits=(dac->bits & ~DECNEG) | bits; // force correct sign
  2102. // round subnormals [to set.digits rather than aset.digits]
  2103. // or set overflow result similarly as required
  2104. decFinalize(dac, set, &residue, &status);
  2105. decNumberCopy(res, dac); // copy to result (is now OK length)
  2106. break;
  2107. }
  2108. #if DECSUBSET
  2109. if (!set->extended && // subset math
  2110. decNumberIsNegative(rhs)) { // was a **-n [hence digits>0]
  2111. // so divide result into 1 [dac=1/dac]
  2112. decDivideOp(dac, &dnOne, dac, &aset, DIVIDE, &status);
  2113. }
  2114. #endif
  2115. } // rhs integer path
  2116. // reduce result to the requested length and copy to result
  2117. decCopyFit(res, dac, set, &residue, &status);
  2118. decFinish(res, set, &residue, &status); // final cleanup
  2119. #if DECSUBSET
  2120. if (!set->extended) decTrim(res, set, 0, 1, &dropped); // trailing zeros
  2121. #endif
  2122. } while(0); // end protected
  2123. if (allocdac!=NULL) free(allocdac); // drop any storage used
  2124. if (allocinv!=NULL) free(allocinv); // ..
  2125. #if DECSUBSET
  2126. if (alloclhs!=NULL) free(alloclhs); // ..
  2127. if (allocrhs!=NULL) free(allocrhs); // ..
  2128. #endif
  2129. if (status!=0) decStatus(res, status, set);
  2130. #if DECCHECK
  2131. decCheckInexact(res, set);
  2132. #endif
  2133. return res;
  2134. } // decNumberPower
  2135. /* ------------------------------------------------------------------ */
  2136. /* decNumberQuantize -- force exponent to requested value */
  2137. /* */
  2138. /* This computes C = op(A, B), where op adjusts the coefficient */
  2139. /* of C (by rounding or shifting) such that the exponent (-scale) */
  2140. /* of C has exponent of B. The numerical value of C will equal A, */
  2141. /* except for the effects of any rounding that occurred. */
  2142. /* */
  2143. /* res is C, the result. C may be A or B */
  2144. /* lhs is A, the number to adjust */
  2145. /* rhs is B, the number with exponent to match */
  2146. /* set is the context */
  2147. /* */
  2148. /* C must have space for set->digits digits. */
  2149. /* */
  2150. /* Unless there is an error or the result is infinite, the exponent */
  2151. /* after the operation is guaranteed to be equal to that of B. */
  2152. /* ------------------------------------------------------------------ */
  2153. decNumber * decNumberQuantize(decNumber *res, const decNumber *lhs,
  2154. const decNumber *rhs, decContext *set) {
  2155. uInt status=0; // accumulator
  2156. decQuantizeOp(res, lhs, rhs, set, 1, &status);
  2157. if (status!=0) decStatus(res, status, set);
  2158. return res;
  2159. } // decNumberQuantize
  2160. /* ------------------------------------------------------------------ */
  2161. /* decNumberReduce -- remove trailing zeros */
  2162. /* */
  2163. /* This computes C = 0 + A, and normalizes the result */
  2164. /* */
  2165. /* res is C, the result. C may be A */
  2166. /* rhs is A */
  2167. /* set is the context */
  2168. /* */
  2169. /* C must have space for set->digits digits. */
  2170. /* ------------------------------------------------------------------ */
  2171. // Previously known as Normalize
  2172. decNumber * decNumberNormalize(decNumber *res, const decNumber *rhs,
  2173. decContext *set) {
  2174. return decNumberReduce(res, rhs, set);
  2175. } // decNumberNormalize
  2176. decNumber * decNumberReduce(decNumber *res, const decNumber *rhs,
  2177. decContext *set) {
  2178. #if DECSUBSET
  2179. decNumber *allocrhs=NULL; // non-NULL if rounded rhs allocated
  2180. #endif
  2181. uInt status=0; // as usual
  2182. Int residue=0; // as usual
  2183. Int dropped; // work
  2184. #if DECCHECK
  2185. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  2186. #endif
  2187. do { // protect allocated storage
  2188. #if DECSUBSET
  2189. if (!set->extended) {
  2190. // reduce operand and set lostDigits status, as needed
  2191. if (rhs->digits>set->digits) {
  2192. allocrhs=decRoundOperand(rhs, set, &status);
  2193. if (allocrhs==NULL) break;
  2194. rhs=allocrhs;
  2195. }
  2196. }
  2197. #endif
  2198. // [following code does not require input rounding]
  2199. // Infinities copy through; NaNs need usual treatment
  2200. if (decNumberIsNaN(rhs)) {
  2201. decNaNs(res, rhs, NULL, set, &status);
  2202. break;
  2203. }
  2204. // reduce result to the requested length and copy to result
  2205. decCopyFit(res, rhs, set, &residue, &status); // copy & round
  2206. decFinish(res, set, &residue, &status); // cleanup/set flags
  2207. decTrim(res, set, 1, 0, &dropped); // normalize in place
  2208. // [may clamp]
  2209. } while(0); // end protected
  2210. #if DECSUBSET
  2211. if (allocrhs !=NULL) free(allocrhs); // ..
  2212. #endif
  2213. if (status!=0) decStatus(res, status, set);// then report status
  2214. return res;
  2215. } // decNumberReduce
  2216. /* ------------------------------------------------------------------ */
  2217. /* decNumberRescale -- force exponent to requested value */
  2218. /* */
  2219. /* This computes C = op(A, B), where op adjusts the coefficient */
  2220. /* of C (by rounding or shifting) such that the exponent (-scale) */
  2221. /* of C has the value B. The numerical value of C will equal A, */
  2222. /* except for the effects of any rounding that occurred. */
  2223. /* */
  2224. /* res is C, the result. C may be A or B */
  2225. /* lhs is A, the number to adjust */
  2226. /* rhs is B, the requested exponent */
  2227. /* set is the context */
  2228. /* */
  2229. /* C must have space for set->digits digits. */
  2230. /* */
  2231. /* Unless there is an error or the result is infinite, the exponent */
  2232. /* after the operation is guaranteed to be equal to B. */
  2233. /* ------------------------------------------------------------------ */
  2234. decNumber * decNumberRescale(decNumber *res, const decNumber *lhs,
  2235. const decNumber *rhs, decContext *set) {
  2236. uInt status=0; // accumulator
  2237. decQuantizeOp(res, lhs, rhs, set, 0, &status);
  2238. if (status!=0) decStatus(res, status, set);
  2239. return res;
  2240. } // decNumberRescale
  2241. /* ------------------------------------------------------------------ */
  2242. /* decNumberRemainder -- divide and return remainder */
  2243. /* */
  2244. /* This computes C = A % B */
  2245. /* */
  2246. /* res is C, the result. C may be A and/or B (e.g., X=X%X) */
  2247. /* lhs is A */
  2248. /* rhs is B */
  2249. /* set is the context */
  2250. /* */
  2251. /* C must have space for set->digits digits. */
  2252. /* ------------------------------------------------------------------ */
  2253. decNumber * decNumberRemainder(decNumber *res, const decNumber *lhs,
  2254. const decNumber *rhs, decContext *set) {
  2255. uInt status=0; // accumulator
  2256. decDivideOp(res, lhs, rhs, set, REMAINDER, &status);
  2257. if (status!=0) decStatus(res, status, set);
  2258. #if DECCHECK
  2259. decCheckInexact(res, set);
  2260. #endif
  2261. return res;
  2262. } // decNumberRemainder
  2263. /* ------------------------------------------------------------------ */
  2264. /* decNumberRemainderNear -- divide and return remainder from nearest */
  2265. /* */
  2266. /* This computes C = A % B, where % is the IEEE remainder operator */
  2267. /* */
  2268. /* res is C, the result. C may be A and/or B (e.g., X=X%X) */
  2269. /* lhs is A */
  2270. /* rhs is B */
  2271. /* set is the context */
  2272. /* */
  2273. /* C must have space for set->digits digits. */
  2274. /* ------------------------------------------------------------------ */
  2275. decNumber * decNumberRemainderNear(decNumber *res, const decNumber *lhs,
  2276. const decNumber *rhs, decContext *set) {
  2277. uInt status=0; // accumulator
  2278. decDivideOp(res, lhs, rhs, set, REMNEAR, &status);
  2279. if (status!=0) decStatus(res, status, set);
  2280. #if DECCHECK
  2281. decCheckInexact(res, set);
  2282. #endif
  2283. return res;
  2284. } // decNumberRemainderNear
  2285. /* ------------------------------------------------------------------ */
  2286. /* decNumberRotate -- rotate the coefficient of a Number left/right */
  2287. /* */
  2288. /* This computes C = A rot B (in base ten and rotating set->digits */
  2289. /* digits). */
  2290. /* */
  2291. /* res is C, the result. C may be A and/or B (e.g., X=XrotX) */
  2292. /* lhs is A */
  2293. /* rhs is B, the number of digits to rotate (-ve to right) */
  2294. /* set is the context */
  2295. /* */
  2296. /* The digits of the coefficient of A are rotated to the left (if B */
  2297. /* is positive) or to the right (if B is negative) without adjusting */
  2298. /* the exponent or the sign of A. If lhs->digits is less than */
  2299. /* set->digits the coefficient is padded with zeros on the left */
  2300. /* before the rotate. Any leading zeros in the result are removed */
  2301. /* as usual. */
  2302. /* */
  2303. /* B must be an integer (q=0) and in the range -set->digits through */
  2304. /* +set->digits. */
  2305. /* C must have space for set->digits digits. */
  2306. /* NaNs are propagated as usual. Infinities are unaffected (but */
  2307. /* B must be valid). No status is set unless B is invalid or an */
  2308. /* operand is an sNaN. */
  2309. /* ------------------------------------------------------------------ */
  2310. decNumber * decNumberRotate(decNumber *res, const decNumber *lhs,
  2311. const decNumber *rhs, decContext *set) {
  2312. uInt status=0; // accumulator
  2313. Int rotate; // rhs as an Int
  2314. #if DECCHECK
  2315. if (decCheckOperands(res, lhs, rhs, set)) return res;
  2316. #endif
  2317. // NaNs propagate as normal
  2318. if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
  2319. decNaNs(res, lhs, rhs, set, &status);
  2320. // rhs must be an integer
  2321. else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
  2322. status=DEC_Invalid_operation;
  2323. else { // both numeric, rhs is an integer
  2324. rotate=decGetInt(rhs); // [cannot fail]
  2325. if (rotate==BADINT // something bad ..
  2326. || rotate==BIGODD || rotate==BIGEVEN // .. very big ..
  2327. || abs(rotate)>set->digits) // .. or out of range
  2328. status=DEC_Invalid_operation;
  2329. else { // rhs is OK
  2330. decNumberCopy(res, lhs);
  2331. // convert -ve rotate to equivalent positive rotation
  2332. if (rotate<0) rotate=set->digits+rotate;
  2333. if (rotate!=0 && rotate!=set->digits // zero or full rotation
  2334. && !decNumberIsInfinite(res)) { // lhs was infinite
  2335. // left-rotate to do; 0 < rotate < set->digits
  2336. uInt units, shift; // work
  2337. uInt msudigits; // digits in result msu
  2338. Unit *msu=res->lsu+D2U(res->digits)-1; // current msu
  2339. Unit *msumax=res->lsu+D2U(set->digits)-1; // rotation msu
  2340. for (msu++; msu<=msumax; msu++) *msu=0; // ensure high units=0
  2341. res->digits=set->digits; // now full-length
  2342. msudigits=MSUDIGITS(res->digits); // actual digits in msu
  2343. // rotation here is done in-place, in three steps
  2344. // 1. shift all to least up to one unit to unit-align final
  2345. // lsd [any digits shifted out are rotated to the left,
  2346. // abutted to the original msd (which may require split)]
  2347. //
  2348. // [if there are no whole units left to rotate, the
  2349. // rotation is now complete]
  2350. //
  2351. // 2. shift to least, from below the split point only, so that
  2352. // the final msd is in the right place in its Unit [any
  2353. // digits shifted out will fit exactly in the current msu,
  2354. // left aligned, no split required]
  2355. //
  2356. // 3. rotate all the units by reversing left part, right
  2357. // part, and then whole
  2358. //
  2359. // example: rotate right 8 digits (2 units + 2), DECDPUN=3.
  2360. //
  2361. // start: 00a bcd efg hij klm npq
  2362. //
  2363. // 1a 000 0ab cde fgh|ijk lmn [pq saved]
  2364. // 1b 00p qab cde fgh|ijk lmn
  2365. //
  2366. // 2a 00p qab cde fgh|00i jkl [mn saved]
  2367. // 2b mnp qab cde fgh|00i jkl
  2368. //
  2369. // 3a fgh cde qab mnp|00i jkl
  2370. // 3b fgh cde qab mnp|jkl 00i
  2371. // 3c 00i jkl mnp qab cde fgh
  2372. // Step 1: amount to shift is the partial right-rotate count
  2373. rotate=set->digits-rotate; // make it right-rotate
  2374. units=rotate/DECDPUN; // whole units to rotate
  2375. shift=rotate%DECDPUN; // left-over digits count
  2376. if (shift>0) { // not an exact number of units
  2377. uInt save=res->lsu[0]%powers[shift]; // save low digit(s)
  2378. decShiftToLeast(res->lsu, D2U(res->digits), shift);
  2379. if (shift>msudigits) { // msumax-1 needs >0 digits
  2380. uInt rem=save%powers[shift-msudigits];// split save
  2381. *msumax=(Unit)(save/powers[shift-msudigits]); // and insert
  2382. *(msumax-1)=*(msumax-1)
  2383. +(Unit)(rem*powers[DECDPUN-(shift-msudigits)]); // ..
  2384. }
  2385. else { // all fits in msumax
  2386. *msumax=*msumax+(Unit)(save*powers[msudigits-shift]); // [maybe *1]
  2387. }
  2388. } // digits shift needed
  2389. // If whole units to rotate...
  2390. if (units>0) { // some to do
  2391. // Step 2: the units to touch are the whole ones in rotate,
  2392. // if any, and the shift is DECDPUN-msudigits (which may be
  2393. // 0, again)
  2394. shift=DECDPUN-msudigits;
  2395. if (shift>0) { // not an exact number of units
  2396. uInt save=res->lsu[0]%powers[shift]; // save low digit(s)
  2397. decShiftToLeast(res->lsu, units, shift);
  2398. *msumax=*msumax+(Unit)(save*powers[msudigits]);
  2399. } // partial shift needed
  2400. // Step 3: rotate the units array using triple reverse
  2401. // (reversing is easy and fast)
  2402. decReverse(res->lsu+units, msumax); // left part
  2403. decReverse(res->lsu, res->lsu+units-1); // right part
  2404. decReverse(res->lsu, msumax); // whole
  2405. } // whole units to rotate
  2406. // the rotation may have left an undetermined number of zeros
  2407. // on the left, so true length needs to be calculated
  2408. res->digits=decGetDigits(res->lsu, msumax-res->lsu+1);
  2409. } // rotate needed
  2410. } // rhs OK
  2411. } // numerics
  2412. if (status!=0) decStatus(res, status, set);
  2413. return res;
  2414. } // decNumberRotate
  2415. /* ------------------------------------------------------------------ */
  2416. /* decNumberSameQuantum -- test for equal exponents */
  2417. /* */
  2418. /* res is the result number, which will contain either 0 or 1 */
  2419. /* lhs is a number to test */
  2420. /* rhs is the second (usually a pattern) */
  2421. /* */
  2422. /* No errors are possible and no context is needed. */
  2423. /* ------------------------------------------------------------------ */
  2424. decNumber * decNumberSameQuantum(decNumber *res, const decNumber *lhs,
  2425. const decNumber *rhs) {
  2426. Unit ret=0; // return value
  2427. #if DECCHECK
  2428. if (decCheckOperands(res, lhs, rhs, DECUNCONT)) return res;
  2429. #endif
  2430. if (SPECIALARGS) {
  2431. if (decNumberIsNaN(lhs) && decNumberIsNaN(rhs)) ret=1;
  2432. else if (decNumberIsInfinite(lhs) && decNumberIsInfinite(rhs)) ret=1;
  2433. // [anything else with a special gives 0]
  2434. }
  2435. else if (lhs->exponent==rhs->exponent) ret=1;
  2436. decNumberZero(res); // OK to overwrite an operand now
  2437. *res->lsu=ret;
  2438. return res;
  2439. } // decNumberSameQuantum
  2440. /* ------------------------------------------------------------------ */
  2441. /* decNumberScaleB -- multiply by a power of 10 */
  2442. /* */
  2443. /* This computes C = A x 10**B where B is an integer (q=0) with */
  2444. /* maximum magnitude 2*(emax+digits) */
  2445. /* */
  2446. /* res is C, the result. C may be A or B */
  2447. /* lhs is A, the number to adjust */
  2448. /* rhs is B, the requested power of ten to use */
  2449. /* set is the context */
  2450. /* */
  2451. /* C must have space for set->digits digits. */
  2452. /* */
  2453. /* The result may underflow or overflow. */
  2454. /* ------------------------------------------------------------------ */
  2455. decNumber * decNumberScaleB(decNumber *res, const decNumber *lhs,
  2456. const decNumber *rhs, decContext *set) {
  2457. Int reqexp; // requested exponent change [B]
  2458. uInt status=0; // accumulator
  2459. Int residue; // work
  2460. #if DECCHECK
  2461. if (decCheckOperands(res, lhs, rhs, set)) return res;
  2462. #endif
  2463. // Handle special values except lhs infinite
  2464. if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
  2465. decNaNs(res, lhs, rhs, set, &status);
  2466. // rhs must be an integer
  2467. else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
  2468. status=DEC_Invalid_operation;
  2469. else {
  2470. // lhs is a number; rhs is a finite with q==0
  2471. reqexp=decGetInt(rhs); // [cannot fail]
  2472. // maximum range is larger than getInt can handle, so this is
  2473. // more restrictive than the specification
  2474. if (reqexp==BADINT // something bad ..
  2475. || reqexp==BIGODD || reqexp==BIGEVEN // it was huge
  2476. || (abs(reqexp)+1)/2>(set->digits+set->emax)) // .. or out of range
  2477. status=DEC_Invalid_operation;
  2478. else { // rhs is OK
  2479. decNumberCopy(res, lhs); // all done if infinite lhs
  2480. if (!decNumberIsInfinite(res)) { // prepare to scale
  2481. Int exp=res->exponent; // save for overflow test
  2482. res->exponent+=reqexp; // adjust the exponent
  2483. if (((exp^reqexp)>=0) // same sign ...
  2484. && ((exp^res->exponent)<0)) { // .. but result had different
  2485. // the calculation overflowed, so force right treatment
  2486. if (exp<0) res->exponent=DEC_MIN_EMIN-DEC_MAX_DIGITS;
  2487. else res->exponent=DEC_MAX_EMAX+1;
  2488. }
  2489. residue=0;
  2490. decFinalize(res, set, &residue, &status); // final check
  2491. } // finite LHS
  2492. } // rhs OK
  2493. } // rhs finite
  2494. if (status!=0) decStatus(res, status, set);
  2495. return res;
  2496. } // decNumberScaleB
  2497. /* ------------------------------------------------------------------ */
  2498. /* decNumberShift -- shift the coefficient of a Number left or right */
  2499. /* */
  2500. /* This computes C = A << B or C = A >> -B (in base ten). */
  2501. /* */
  2502. /* res is C, the result. C may be A and/or B (e.g., X=X<<X) */
  2503. /* lhs is A */
  2504. /* rhs is B, the number of digits to shift (-ve to right) */
  2505. /* set is the context */
  2506. /* */
  2507. /* The digits of the coefficient of A are shifted to the left (if B */
  2508. /* is positive) or to the right (if B is negative) without adjusting */
  2509. /* the exponent or the sign of A. */
  2510. /* */
  2511. /* B must be an integer (q=0) and in the range -set->digits through */
  2512. /* +set->digits. */
  2513. /* C must have space for set->digits digits. */
  2514. /* NaNs are propagated as usual. Infinities are unaffected (but */
  2515. /* B must be valid). No status is set unless B is invalid or an */
  2516. /* operand is an sNaN. */
  2517. /* ------------------------------------------------------------------ */
  2518. decNumber * decNumberShift(decNumber *res, const decNumber *lhs,
  2519. const decNumber *rhs, decContext *set) {
  2520. uInt status=0; // accumulator
  2521. Int shift; // rhs as an Int
  2522. #if DECCHECK
  2523. if (decCheckOperands(res, lhs, rhs, set)) return res;
  2524. #endif
  2525. // NaNs propagate as normal
  2526. if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
  2527. decNaNs(res, lhs, rhs, set, &status);
  2528. // rhs must be an integer
  2529. else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
  2530. status=DEC_Invalid_operation;
  2531. else { // both numeric, rhs is an integer
  2532. shift=decGetInt(rhs); // [cannot fail]
  2533. if (shift==BADINT // something bad ..
  2534. || shift==BIGODD || shift==BIGEVEN // .. very big ..
  2535. || abs(shift)>set->digits) // .. or out of range
  2536. status=DEC_Invalid_operation;
  2537. else { // rhs is OK
  2538. decNumberCopy(res, lhs);
  2539. if (shift!=0 && !decNumberIsInfinite(res)) { // something to do
  2540. if (shift>0) { // to left
  2541. if (shift==set->digits) { // removing all
  2542. *res->lsu=0; // so place 0
  2543. res->digits=1; // ..
  2544. }
  2545. else { //
  2546. // first remove leading digits if necessary
  2547. if (res->digits+shift>set->digits) {
  2548. decDecap(res, res->digits+shift-set->digits);
  2549. // that updated res->digits; may have gone to 1 (for a
  2550. // single digit or for zero
  2551. }
  2552. if (res->digits>1 || *res->lsu) // if non-zero..
  2553. res->digits=decShiftToMost(res->lsu, res->digits, shift);
  2554. } // partial left
  2555. } // left
  2556. else { // to right
  2557. if (-shift>=res->digits) { // discarding all
  2558. *res->lsu=0; // so place 0
  2559. res->digits=1; // ..
  2560. }
  2561. else {
  2562. decShiftToLeast(res->lsu, D2U(res->digits), -shift);
  2563. res->digits-=(-shift);
  2564. }
  2565. } // to right
  2566. } // non-0 non-Inf shift
  2567. } // rhs OK
  2568. } // numerics
  2569. if (status!=0) decStatus(res, status, set);
  2570. return res;
  2571. } // decNumberShift
  2572. /* ------------------------------------------------------------------ */
  2573. /* decNumberSquareRoot -- square root operator */
  2574. /* */
  2575. /* This computes C = squareroot(A) */
  2576. /* */
  2577. /* res is C, the result. C may be A */
  2578. /* rhs is A */
  2579. /* set is the context; note that rounding mode has no effect */
  2580. /* */
  2581. /* C must have space for set->digits digits. */
  2582. /* ------------------------------------------------------------------ */
  2583. /* This uses the following varying-precision algorithm in: */
  2584. /* */
  2585. /* Properly Rounded Variable Precision Square Root, T. E. Hull and */
  2586. /* A. Abrham, ACM Transactions on Mathematical Software, Vol 11 #3, */
  2587. /* pp229-237, ACM, September 1985. */
  2588. /* */
  2589. /* The square-root is calculated using Newton's method, after which */
  2590. /* a check is made to ensure the result is correctly rounded. */
  2591. /* */
  2592. /* % [Reformatted original Numerical Turing source code follows.] */
  2593. /* function sqrt(x : real) : real */
  2594. /* % sqrt(x) returns the properly rounded approximation to the square */
  2595. /* % root of x, in the precision of the calling environment, or it */
  2596. /* % fails if x < 0. */
  2597. /* % t e hull and a abrham, august, 1984 */
  2598. /* if x <= 0 then */
  2599. /* if x < 0 then */
  2600. /* assert false */
  2601. /* else */
  2602. /* result 0 */
  2603. /* end if */
  2604. /* end if */
  2605. /* var f := setexp(x, 0) % fraction part of x [0.1 <= x < 1] */
  2606. /* var e := getexp(x) % exponent part of x */
  2607. /* var approx : real */
  2608. /* if e mod 2 = 0 then */
  2609. /* approx := .259 + .819 * f % approx to root of f */
  2610. /* else */
  2611. /* f := f/l0 % adjustments */
  2612. /* e := e + 1 % for odd */
  2613. /* approx := .0819 + 2.59 * f % exponent */
  2614. /* end if */
  2615. /* */
  2616. /* var p:= 3 */
  2617. /* const maxp := currentprecision + 2 */
  2618. /* loop */
  2619. /* p := min(2*p - 2, maxp) % p = 4,6,10, . . . , maxp */
  2620. /* precision p */
  2621. /* approx := .5 * (approx + f/approx) */
  2622. /* exit when p = maxp */
  2623. /* end loop */
  2624. /* */
  2625. /* % approx is now within 1 ulp of the properly rounded square root */
  2626. /* % of f; to ensure proper rounding, compare squares of (approx - */
  2627. /* % l/2 ulp) and (approx + l/2 ulp) with f. */
  2628. /* p := currentprecision */
  2629. /* begin */
  2630. /* precision p + 2 */
  2631. /* const approxsubhalf := approx - setexp(.5, -p) */
  2632. /* if mulru(approxsubhalf, approxsubhalf) > f then */
  2633. /* approx := approx - setexp(.l, -p + 1) */
  2634. /* else */
  2635. /* const approxaddhalf := approx + setexp(.5, -p) */
  2636. /* if mulrd(approxaddhalf, approxaddhalf) < f then */
  2637. /* approx := approx + setexp(.l, -p + 1) */
  2638. /* end if */
  2639. /* end if */
  2640. /* end */
  2641. /* result setexp(approx, e div 2) % fix exponent */
  2642. /* end sqrt */
  2643. /* ------------------------------------------------------------------ */
  2644. decNumber * decNumberSquareRoot(decNumber *res, const decNumber *rhs,
  2645. decContext *set) {
  2646. decContext workset, approxset; // work contexts
  2647. decNumber dzero; // used for constant zero
  2648. Int maxp; // largest working precision
  2649. Int workp; // working precision
  2650. Int residue=0; // rounding residue
  2651. uInt status=0, ignore=0; // status accumulators
  2652. uInt rstatus; // ..
  2653. Int exp; // working exponent
  2654. Int ideal; // ideal (preferred) exponent
  2655. Int needbytes; // work
  2656. Int dropped; // ..
  2657. #if DECSUBSET
  2658. decNumber *allocrhs=NULL; // non-NULL if rounded rhs allocated
  2659. #endif
  2660. // buffer for f [needs +1 in case DECBUFFER 0]
  2661. decNumber buff[D2N(DECBUFFER+1)];
  2662. // buffer for a [needs +2 to match likely maxp]
  2663. decNumber bufa[D2N(DECBUFFER+2)];
  2664. // buffer for temporary, b [must be same size as a]
  2665. decNumber bufb[D2N(DECBUFFER+2)];
  2666. decNumber *allocbuff=NULL; // -> allocated buff, iff allocated
  2667. decNumber *allocbufa=NULL; // -> allocated bufa, iff allocated
  2668. decNumber *allocbufb=NULL; // -> allocated bufb, iff allocated
  2669. decNumber *f=buff; // reduced fraction
  2670. decNumber *a=bufa; // approximation to result
  2671. decNumber *b=bufb; // intermediate result
  2672. // buffer for temporary variable, up to 3 digits
  2673. decNumber buft[D2N(3)];
  2674. decNumber *t=buft; // up-to-3-digit constant or work
  2675. #if DECCHECK
  2676. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  2677. #endif
  2678. do { // protect allocated storage
  2679. #if DECSUBSET
  2680. if (!set->extended) {
  2681. // reduce operand and set lostDigits status, as needed
  2682. if (rhs->digits>set->digits) {
  2683. allocrhs=decRoundOperand(rhs, set, &status);
  2684. if (allocrhs==NULL) break;
  2685. // [Note: 'f' allocation below could reuse this buffer if
  2686. // used, but as this is rare they are kept separate for clarity.]
  2687. rhs=allocrhs;
  2688. }
  2689. }
  2690. #endif
  2691. // [following code does not require input rounding]
  2692. // handle infinities and NaNs
  2693. if (SPECIALARG) {
  2694. if (decNumberIsInfinite(rhs)) { // an infinity
  2695. if (decNumberIsNegative(rhs)) status|=DEC_Invalid_operation;
  2696. else decNumberCopy(res, rhs); // +Infinity
  2697. }
  2698. else decNaNs(res, rhs, NULL, set, &status); // a NaN
  2699. break;
  2700. }
  2701. // calculate the ideal (preferred) exponent [floor(exp/2)]
  2702. // [It would be nicer to write: ideal=rhs->exponent>>1, but this
  2703. // generates a compiler warning. Generated code is the same.]
  2704. ideal=(rhs->exponent&~1)/2; // target
  2705. // handle zeros
  2706. if (ISZERO(rhs)) {
  2707. decNumberCopy(res, rhs); // could be 0 or -0
  2708. res->exponent=ideal; // use the ideal [safe]
  2709. // use decFinish to clamp any out-of-range exponent, etc.
  2710. decFinish(res, set, &residue, &status);
  2711. break;
  2712. }
  2713. // any other -x is an oops
  2714. if (decNumberIsNegative(rhs)) {
  2715. status|=DEC_Invalid_operation;
  2716. break;
  2717. }
  2718. // space is needed for three working variables
  2719. // f -- the same precision as the RHS, reduced to 0.01->0.99...
  2720. // a -- Hull's approximation -- precision, when assigned, is
  2721. // currentprecision+1 or the input argument precision,
  2722. // whichever is larger (+2 for use as temporary)
  2723. // b -- intermediate temporary result (same size as a)
  2724. // if any is too long for local storage, then allocate
  2725. workp=MAXI(set->digits+1, rhs->digits); // actual rounding precision
  2726. workp=MAXI(workp, 7); // at least 7 for low cases
  2727. maxp=workp+2; // largest working precision
  2728. needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
  2729. if (needbytes>(Int)sizeof(buff)) {
  2730. allocbuff=(decNumber *)malloc(needbytes);
  2731. if (allocbuff==NULL) { // hopeless -- abandon
  2732. status|=DEC_Insufficient_storage;
  2733. break;}
  2734. f=allocbuff; // use the allocated space
  2735. }
  2736. // a and b both need to be able to hold a maxp-length number
  2737. needbytes=sizeof(decNumber)+(D2U(maxp)-1)*sizeof(Unit);
  2738. if (needbytes>(Int)sizeof(bufa)) { // [same applies to b]
  2739. allocbufa=(decNumber *)malloc(needbytes);
  2740. allocbufb=(decNumber *)malloc(needbytes);
  2741. if (allocbufa==NULL || allocbufb==NULL) { // hopeless
  2742. status|=DEC_Insufficient_storage;
  2743. break;}
  2744. a=allocbufa; // use the allocated spaces
  2745. b=allocbufb; // ..
  2746. }
  2747. // copy rhs -> f, save exponent, and reduce so 0.1 <= f < 1
  2748. decNumberCopy(f, rhs);
  2749. exp=f->exponent+f->digits; // adjusted to Hull rules
  2750. f->exponent=-(f->digits); // to range
  2751. // set up working context
  2752. decContextDefault(&workset, DEC_INIT_DECIMAL64);
  2753. workset.emax=DEC_MAX_EMAX;
  2754. workset.emin=DEC_MIN_EMIN;
  2755. // [Until further notice, no error is possible and status bits
  2756. // (Rounded, etc.) should be ignored, not accumulated.]
  2757. // Calculate initial approximation, and allow for odd exponent
  2758. workset.digits=workp; // p for initial calculation
  2759. t->bits=0; t->digits=3;
  2760. a->bits=0; a->digits=3;
  2761. if ((exp & 1)==0) { // even exponent
  2762. // Set t=0.259, a=0.819
  2763. t->exponent=-3;
  2764. a->exponent=-3;
  2765. #if DECDPUN>=3
  2766. t->lsu[0]=259;
  2767. a->lsu[0]=819;
  2768. #elif DECDPUN==2
  2769. t->lsu[0]=59; t->lsu[1]=2;
  2770. a->lsu[0]=19; a->lsu[1]=8;
  2771. #else
  2772. t->lsu[0]=9; t->lsu[1]=5; t->lsu[2]=2;
  2773. a->lsu[0]=9; a->lsu[1]=1; a->lsu[2]=8;
  2774. #endif
  2775. }
  2776. else { // odd exponent
  2777. // Set t=0.0819, a=2.59
  2778. f->exponent--; // f=f/10
  2779. exp++; // e=e+1
  2780. t->exponent=-4;
  2781. a->exponent=-2;
  2782. #if DECDPUN>=3
  2783. t->lsu[0]=819;
  2784. a->lsu[0]=259;
  2785. #elif DECDPUN==2
  2786. t->lsu[0]=19; t->lsu[1]=8;
  2787. a->lsu[0]=59; a->lsu[1]=2;
  2788. #else
  2789. t->lsu[0]=9; t->lsu[1]=1; t->lsu[2]=8;
  2790. a->lsu[0]=9; a->lsu[1]=5; a->lsu[2]=2;
  2791. #endif
  2792. }
  2793. decMultiplyOp(a, a, f, &workset, &ignore); // a=a*f
  2794. decAddOp(a, a, t, &workset, 0, &ignore); // ..+t
  2795. // [a is now the initial approximation for sqrt(f), calculated with
  2796. // currentprecision, which is also a's precision.]
  2797. // the main calculation loop
  2798. decNumberZero(&dzero); // make 0
  2799. decNumberZero(t); // set t = 0.5
  2800. t->lsu[0]=5; // ..
  2801. t->exponent=-1; // ..
  2802. workset.digits=3; // initial p
  2803. for (; workset.digits<maxp;) {
  2804. // set p to min(2*p - 2, maxp) [hence 3; or: 4, 6, 10, ... , maxp]
  2805. workset.digits=MINI(workset.digits*2-2, maxp);
  2806. // a = 0.5 * (a + f/a)
  2807. // [calculated at p then rounded to currentprecision]
  2808. decDivideOp(b, f, a, &workset, DIVIDE, &ignore); // b=f/a
  2809. decAddOp(b, b, a, &workset, 0, &ignore); // b=b+a
  2810. decMultiplyOp(a, b, t, &workset, &ignore); // a=b*0.5
  2811. } // loop
  2812. // Here, 0.1 <= a < 1 [Hull], and a has maxp digits
  2813. // now reduce to length, etc.; this needs to be done with a
  2814. // having the correct exponent so as to handle subnormals
  2815. // correctly
  2816. approxset=*set; // get emin, emax, etc.
  2817. approxset.round=DEC_ROUND_HALF_EVEN;
  2818. a->exponent+=exp/2; // set correct exponent
  2819. rstatus=0; // clear status
  2820. residue=0; // .. and accumulator
  2821. decCopyFit(a, a, &approxset, &residue, &rstatus); // reduce (if needed)
  2822. decFinish(a, &approxset, &residue, &rstatus); // clean and finalize
  2823. // Overflow was possible if the input exponent was out-of-range,
  2824. // in which case quit
  2825. if (rstatus&DEC_Overflow) {
  2826. status=rstatus; // use the status as-is
  2827. decNumberCopy(res, a); // copy to result
  2828. break;
  2829. }
  2830. // Preserve status except Inexact/Rounded
  2831. status|=(rstatus & ~(DEC_Rounded|DEC_Inexact));
  2832. // Carry out the Hull correction
  2833. a->exponent-=exp/2; // back to 0.1->1
  2834. // a is now at final precision and within 1 ulp of the properly
  2835. // rounded square root of f; to ensure proper rounding, compare
  2836. // squares of (a - l/2 ulp) and (a + l/2 ulp) with f.
  2837. // Here workset.digits=maxp and t=0.5, and a->digits determines
  2838. // the ulp
  2839. workset.digits--; // maxp-1 is OK now
  2840. t->exponent=-a->digits-1; // make 0.5 ulp
  2841. decAddOp(b, a, t, &workset, DECNEG, &ignore); // b = a - 0.5 ulp
  2842. workset.round=DEC_ROUND_UP;
  2843. decMultiplyOp(b, b, b, &workset, &ignore); // b = mulru(b, b)
  2844. decCompareOp(b, f, b, &workset, COMPARE, &ignore); // b ? f, reversed
  2845. if (decNumberIsNegative(b)) { // f < b [i.e., b > f]
  2846. // this is the more common adjustment, though both are rare
  2847. t->exponent++; // make 1.0 ulp
  2848. t->lsu[0]=1; // ..
  2849. decAddOp(a, a, t, &workset, DECNEG, &ignore); // a = a - 1 ulp
  2850. // assign to approx [round to length]
  2851. approxset.emin-=exp/2; // adjust to match a
  2852. approxset.emax-=exp/2;
  2853. decAddOp(a, &dzero, a, &approxset, 0, &ignore);
  2854. }
  2855. else {
  2856. decAddOp(b, a, t, &workset, 0, &ignore); // b = a + 0.5 ulp
  2857. workset.round=DEC_ROUND_DOWN;
  2858. decMultiplyOp(b, b, b, &workset, &ignore); // b = mulrd(b, b)
  2859. decCompareOp(b, b, f, &workset, COMPARE, &ignore); // b ? f
  2860. if (decNumberIsNegative(b)) { // b < f
  2861. t->exponent++; // make 1.0 ulp
  2862. t->lsu[0]=1; // ..
  2863. decAddOp(a, a, t, &workset, 0, &ignore); // a = a + 1 ulp
  2864. // assign to approx [round to length]
  2865. approxset.emin-=exp/2; // adjust to match a
  2866. approxset.emax-=exp/2;
  2867. decAddOp(a, &dzero, a, &approxset, 0, &ignore);
  2868. }
  2869. }
  2870. // [no errors are possible in the above, and rounding/inexact during
  2871. // estimation are irrelevant, so status was not accumulated]
  2872. // Here, 0.1 <= a < 1 (still), so adjust back
  2873. a->exponent+=exp/2; // set correct exponent
  2874. // count droppable zeros [after any subnormal rounding] by
  2875. // trimming a copy
  2876. decNumberCopy(b, a);
  2877. decTrim(b, set, 1, 1, &dropped); // [drops trailing zeros]
  2878. // Set Inexact and Rounded. The answer can only be exact if
  2879. // it is short enough so that squaring it could fit in workp
  2880. // digits, so this is the only (relatively rare) condition that
  2881. // a careful check is needed
  2882. if (b->digits*2-1 > workp) { // cannot fit
  2883. status|=DEC_Inexact|DEC_Rounded;
  2884. }
  2885. else { // could be exact/unrounded
  2886. uInt mstatus=0; // local status
  2887. decMultiplyOp(b, b, b, &workset, &mstatus); // try the multiply
  2888. if (mstatus&DEC_Overflow) { // result just won't fit
  2889. status|=DEC_Inexact|DEC_Rounded;
  2890. }
  2891. else { // plausible
  2892. decCompareOp(t, b, rhs, &workset, COMPARE, &mstatus); // b ? rhs
  2893. if (!ISZERO(t)) status|=DEC_Inexact|DEC_Rounded; // not equal
  2894. else { // is Exact
  2895. // here, dropped is the count of trailing zeros in 'a'
  2896. // use closest exponent to ideal...
  2897. Int todrop=ideal-a->exponent; // most that can be dropped
  2898. if (todrop<0) status|=DEC_Rounded; // ideally would add 0s
  2899. else { // unrounded
  2900. // there are some to drop, but emax may not allow all
  2901. Int maxexp=set->emax-set->digits+1;
  2902. Int maxdrop=maxexp-a->exponent;
  2903. if (todrop>maxdrop && set->clamp) { // apply clamping
  2904. todrop=maxdrop;
  2905. status|=DEC_Clamped;
  2906. }
  2907. if (dropped<todrop) { // clamp to those available
  2908. todrop=dropped;
  2909. status|=DEC_Clamped;
  2910. }
  2911. if (todrop>0) { // have some to drop
  2912. decShiftToLeast(a->lsu, D2U(a->digits), todrop);
  2913. a->exponent+=todrop; // maintain numerical value
  2914. a->digits-=todrop; // new length
  2915. }
  2916. }
  2917. }
  2918. }
  2919. }
  2920. // double-check Underflow, as perhaps the result could not have
  2921. // been subnormal (initial argument too big), or it is now Exact
  2922. if (status&DEC_Underflow) {
  2923. Int ae=rhs->exponent+rhs->digits-1; // adjusted exponent
  2924. // check if truly subnormal
  2925. #if DECEXTFLAG // DEC_Subnormal too
  2926. if (ae>=set->emin*2) status&=~(DEC_Subnormal|DEC_Underflow);
  2927. #else
  2928. if (ae>=set->emin*2) status&=~DEC_Underflow;
  2929. #endif
  2930. // check if truly inexact
  2931. if (!(status&DEC_Inexact)) status&=~DEC_Underflow;
  2932. }
  2933. decNumberCopy(res, a); // a is now the result
  2934. } while(0); // end protected
  2935. if (allocbuff!=NULL) free(allocbuff); // drop any storage used
  2936. if (allocbufa!=NULL) free(allocbufa); // ..
  2937. if (allocbufb!=NULL) free(allocbufb); // ..
  2938. #if DECSUBSET
  2939. if (allocrhs !=NULL) free(allocrhs); // ..
  2940. #endif
  2941. if (status!=0) decStatus(res, status, set);// then report status
  2942. #if DECCHECK
  2943. decCheckInexact(res, set);
  2944. #endif
  2945. return res;
  2946. } // decNumberSquareRoot
  2947. /* ------------------------------------------------------------------ */
  2948. /* decNumberSubtract -- subtract two Numbers */
  2949. /* */
  2950. /* This computes C = A - B */
  2951. /* */
  2952. /* res is C, the result. C may be A and/or B (e.g., X=X-X) */
  2953. /* lhs is A */
  2954. /* rhs is B */
  2955. /* set is the context */
  2956. /* */
  2957. /* C must have space for set->digits digits. */
  2958. /* ------------------------------------------------------------------ */
  2959. decNumber * decNumberSubtract(decNumber *res, const decNumber *lhs,
  2960. const decNumber *rhs, decContext *set) {
  2961. uInt status=0; // accumulator
  2962. decAddOp(res, lhs, rhs, set, DECNEG, &status);
  2963. if (status!=0) decStatus(res, status, set);
  2964. #if DECCHECK
  2965. decCheckInexact(res, set);
  2966. #endif
  2967. return res;
  2968. } // decNumberSubtract
  2969. /* ------------------------------------------------------------------ */
  2970. /* decNumberToIntegralExact -- round-to-integral-value with InExact */
  2971. /* decNumberToIntegralValue -- round-to-integral-value */
  2972. /* */
  2973. /* res is the result */
  2974. /* rhs is input number */
  2975. /* set is the context */
  2976. /* */
  2977. /* res must have space for any value of rhs. */
  2978. /* */
  2979. /* This implements the IEEE special operators and therefore treats */
  2980. /* special values as valid. For finite numbers it returns */
  2981. /* rescale(rhs, 0) if rhs->exponent is <0. */
  2982. /* Otherwise the result is rhs (so no error is possible, except for */
  2983. /* sNaN). */
  2984. /* */
  2985. /* The context is used for rounding mode and status after sNaN, but */
  2986. /* the digits setting is ignored. The Exact version will signal */
  2987. /* Inexact if the result differs numerically from rhs; the other */
  2988. /* never signals Inexact. */
  2989. /* ------------------------------------------------------------------ */
  2990. decNumber * decNumberToIntegralExact(decNumber *res, const decNumber *rhs,
  2991. decContext *set) {
  2992. decNumber dn;
  2993. decContext workset; // working context
  2994. uInt status=0; // accumulator
  2995. #if DECCHECK
  2996. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  2997. #endif
  2998. // handle infinities and NaNs
  2999. if (SPECIALARG) {
  3000. if (decNumberIsInfinite(rhs)) decNumberCopy(res, rhs); // an Infinity
  3001. else decNaNs(res, rhs, NULL, set, &status); // a NaN
  3002. }
  3003. else { // finite
  3004. // have a finite number; no error possible (res must be big enough)
  3005. if (rhs->exponent>=0) return decNumberCopy(res, rhs);
  3006. // that was easy, but if negative exponent there is work to do...
  3007. workset=*set; // clone rounding, etc.
  3008. workset.digits=rhs->digits; // no length rounding
  3009. workset.traps=0; // no traps
  3010. decNumberZero(&dn); // make a number with exponent 0
  3011. decNumberQuantize(res, rhs, &dn, &workset);
  3012. status|=workset.status;
  3013. }
  3014. if (status!=0) decStatus(res, status, set);
  3015. return res;
  3016. } // decNumberToIntegralExact
  3017. decNumber * decNumberToIntegralValue(decNumber *res, const decNumber *rhs,
  3018. decContext *set) {
  3019. decContext workset=*set; // working context
  3020. workset.traps=0; // no traps
  3021. decNumberToIntegralExact(res, rhs, &workset);
  3022. // this never affects set, except for sNaNs; NaN will have been set
  3023. // or propagated already, so no need to call decStatus
  3024. set->status|=workset.status&DEC_Invalid_operation;
  3025. return res;
  3026. } // decNumberToIntegralValue
  3027. /* ------------------------------------------------------------------ */
  3028. /* decNumberXor -- XOR two Numbers, digitwise */
  3029. /* */
  3030. /* This computes C = A ^ B */
  3031. /* */
  3032. /* res is C, the result. C may be A and/or B (e.g., X=X^X) */
  3033. /* lhs is A */
  3034. /* rhs is B */
  3035. /* set is the context (used for result length and error report) */
  3036. /* */
  3037. /* C must have space for set->digits digits. */
  3038. /* */
  3039. /* Logical function restrictions apply (see above); a NaN is */
  3040. /* returned with Invalid_operation if a restriction is violated. */
  3041. /* ------------------------------------------------------------------ */
  3042. decNumber * decNumberXor(decNumber *res, const decNumber *lhs,
  3043. const decNumber *rhs, decContext *set) {
  3044. const Unit *ua, *ub; // -> operands
  3045. const Unit *msua, *msub; // -> operand msus
  3046. Unit *uc, *msuc; // -> result and its msu
  3047. Int msudigs; // digits in res msu
  3048. #if DECCHECK
  3049. if (decCheckOperands(res, lhs, rhs, set)) return res;
  3050. #endif
  3051. if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
  3052. || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
  3053. decStatus(res, DEC_Invalid_operation, set);
  3054. return res;
  3055. }
  3056. // operands are valid
  3057. ua=lhs->lsu; // bottom-up
  3058. ub=rhs->lsu; // ..
  3059. uc=res->lsu; // ..
  3060. msua=ua+D2U(lhs->digits)-1; // -> msu of lhs
  3061. msub=ub+D2U(rhs->digits)-1; // -> msu of rhs
  3062. msuc=uc+D2U(set->digits)-1; // -> msu of result
  3063. msudigs=MSUDIGITS(set->digits); // [faster than remainder]
  3064. for (; uc<=msuc; ua++, ub++, uc++) { // Unit loop
  3065. Unit a, b; // extract units
  3066. if (ua>msua) a=0;
  3067. else a=*ua;
  3068. if (ub>msub) b=0;
  3069. else b=*ub;
  3070. *uc=0; // can now write back
  3071. if (a|b) { // maybe 1 bits to examine
  3072. Int i, j;
  3073. // This loop could be unrolled and/or use BIN2BCD tables
  3074. for (i=0; i<DECDPUN; i++) {
  3075. if ((a^b)&1) *uc=*uc+(Unit)powers[i]; // effect XOR
  3076. j=a%10;
  3077. a=a/10;
  3078. j|=b%10;
  3079. b=b/10;
  3080. if (j>1) {
  3081. decStatus(res, DEC_Invalid_operation, set);
  3082. return res;
  3083. }
  3084. if (uc==msuc && i==msudigs-1) break; // just did final digit
  3085. } // each digit
  3086. } // non-zero
  3087. } // each unit
  3088. // [here uc-1 is the msu of the result]
  3089. res->digits=decGetDigits(res->lsu, uc-res->lsu);
  3090. res->exponent=0; // integer
  3091. res->bits=0; // sign=0
  3092. return res; // [no status to set]
  3093. } // decNumberXor
  3094. /* ================================================================== */
  3095. /* Utility routines */
  3096. /* ================================================================== */
  3097. /* ------------------------------------------------------------------ */
  3098. /* decNumberClass -- return the decClass of a decNumber */
  3099. /* dn -- the decNumber to test */
  3100. /* set -- the context to use for Emin */
  3101. /* returns the decClass enum */
  3102. /* ------------------------------------------------------------------ */
  3103. enum decClass decNumberClass(const decNumber *dn, decContext *set) {
  3104. if (decNumberIsSpecial(dn)) {
  3105. if (decNumberIsQNaN(dn)) return DEC_CLASS_QNAN;
  3106. if (decNumberIsSNaN(dn)) return DEC_CLASS_SNAN;
  3107. // must be an infinity
  3108. if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_INF;
  3109. return DEC_CLASS_POS_INF;
  3110. }
  3111. // is finite
  3112. if (decNumberIsNormal(dn, set)) { // most common
  3113. if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_NORMAL;
  3114. return DEC_CLASS_POS_NORMAL;
  3115. }
  3116. // is subnormal or zero
  3117. if (decNumberIsZero(dn)) { // most common
  3118. if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_ZERO;
  3119. return DEC_CLASS_POS_ZERO;
  3120. }
  3121. if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_SUBNORMAL;
  3122. return DEC_CLASS_POS_SUBNORMAL;
  3123. } // decNumberClass
  3124. /* ------------------------------------------------------------------ */
  3125. /* decNumberClassToString -- convert decClass to a string */
  3126. /* */
  3127. /* eclass is a valid decClass */
  3128. /* returns a constant string describing the class (max 13+1 chars) */
  3129. /* ------------------------------------------------------------------ */
  3130. const char *decNumberClassToString(enum decClass eclass) {
  3131. if (eclass==DEC_CLASS_POS_NORMAL) return DEC_ClassString_PN;
  3132. if (eclass==DEC_CLASS_NEG_NORMAL) return DEC_ClassString_NN;
  3133. if (eclass==DEC_CLASS_POS_ZERO) return DEC_ClassString_PZ;
  3134. if (eclass==DEC_CLASS_NEG_ZERO) return DEC_ClassString_NZ;
  3135. if (eclass==DEC_CLASS_POS_SUBNORMAL) return DEC_ClassString_PS;
  3136. if (eclass==DEC_CLASS_NEG_SUBNORMAL) return DEC_ClassString_NS;
  3137. if (eclass==DEC_CLASS_POS_INF) return DEC_ClassString_PI;
  3138. if (eclass==DEC_CLASS_NEG_INF) return DEC_ClassString_NI;
  3139. if (eclass==DEC_CLASS_QNAN) return DEC_ClassString_QN;
  3140. if (eclass==DEC_CLASS_SNAN) return DEC_ClassString_SN;
  3141. return DEC_ClassString_UN; // Unknown
  3142. } // decNumberClassToString
  3143. /* ------------------------------------------------------------------ */
  3144. /* decNumberCopy -- copy a number */
  3145. /* */
  3146. /* dest is the target decNumber */
  3147. /* src is the source decNumber */
  3148. /* returns dest */
  3149. /* */
  3150. /* (dest==src is allowed and is a no-op) */
  3151. /* All fields are updated as required. This is a utility operation, */
  3152. /* so special values are unchanged and no error is possible. */
  3153. /* ------------------------------------------------------------------ */
  3154. decNumber * decNumberCopy(decNumber *dest, const decNumber *src) {
  3155. #if DECCHECK
  3156. if (src==NULL) return decNumberZero(dest);
  3157. #endif
  3158. if (dest==src) return dest; // no copy required
  3159. // Use explicit assignments here as structure assignment could copy
  3160. // more than just the lsu (for small DECDPUN). This would not affect
  3161. // the value of the results, but could disturb test harness spill
  3162. // checking.
  3163. dest->bits=src->bits;
  3164. dest->exponent=src->exponent;
  3165. dest->digits=src->digits;
  3166. dest->lsu[0]=src->lsu[0];
  3167. if (src->digits>DECDPUN) { // more Units to come
  3168. const Unit *smsup, *s; // work
  3169. Unit *d; // ..
  3170. // memcpy for the remaining Units would be safe as they cannot
  3171. // overlap. However, this explicit loop is faster in short cases.
  3172. d=dest->lsu+1; // -> first destination
  3173. smsup=src->lsu+D2U(src->digits); // -> source msu+1
  3174. for (s=src->lsu+1; s<smsup; s++, d++) *d=*s;
  3175. }
  3176. return dest;
  3177. } // decNumberCopy
  3178. /* ------------------------------------------------------------------ */
  3179. /* decNumberCopyAbs -- quiet absolute value operator */
  3180. /* */
  3181. /* This sets C = abs(A) */
  3182. /* */
  3183. /* res is C, the result. C may be A */
  3184. /* rhs is A */
  3185. /* */
  3186. /* C must have space for set->digits digits. */
  3187. /* No exception or error can occur; this is a quiet bitwise operation.*/
  3188. /* See also decNumberAbs for a checking version of this. */
  3189. /* ------------------------------------------------------------------ */
  3190. decNumber * decNumberCopyAbs(decNumber *res, const decNumber *rhs) {
  3191. #if DECCHECK
  3192. if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
  3193. #endif
  3194. decNumberCopy(res, rhs);
  3195. res->bits&=~DECNEG; // turn off sign
  3196. return res;
  3197. } // decNumberCopyAbs
  3198. /* ------------------------------------------------------------------ */
  3199. /* decNumberCopyNegate -- quiet negate value operator */
  3200. /* */
  3201. /* This sets C = negate(A) */
  3202. /* */
  3203. /* res is C, the result. C may be A */
  3204. /* rhs is A */
  3205. /* */
  3206. /* C must have space for set->digits digits. */
  3207. /* No exception or error can occur; this is a quiet bitwise operation.*/
  3208. /* See also decNumberMinus for a checking version of this. */
  3209. /* ------------------------------------------------------------------ */
  3210. decNumber * decNumberCopyNegate(decNumber *res, const decNumber *rhs) {
  3211. #if DECCHECK
  3212. if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
  3213. #endif
  3214. decNumberCopy(res, rhs);
  3215. res->bits^=DECNEG; // invert the sign
  3216. return res;
  3217. } // decNumberCopyNegate
  3218. /* ------------------------------------------------------------------ */
  3219. /* decNumberCopySign -- quiet copy and set sign operator */
  3220. /* */
  3221. /* This sets C = A with the sign of B */
  3222. /* */
  3223. /* res is C, the result. C may be A */
  3224. /* lhs is A */
  3225. /* rhs is B */
  3226. /* */
  3227. /* C must have space for set->digits digits. */
  3228. /* No exception or error can occur; this is a quiet bitwise operation.*/
  3229. /* ------------------------------------------------------------------ */
  3230. decNumber * decNumberCopySign(decNumber *res, const decNumber *lhs,
  3231. const decNumber *rhs) {
  3232. uByte sign; // rhs sign
  3233. #if DECCHECK
  3234. if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
  3235. #endif
  3236. sign=rhs->bits & DECNEG; // save sign bit
  3237. decNumberCopy(res, lhs);
  3238. res->bits&=~DECNEG; // clear the sign
  3239. res->bits|=sign; // set from rhs
  3240. return res;
  3241. } // decNumberCopySign
  3242. /* ------------------------------------------------------------------ */
  3243. /* decNumberGetBCD -- get the coefficient in BCD8 */
  3244. /* dn is the source decNumber */
  3245. /* bcd is the uInt array that will receive dn->digits BCD bytes, */
  3246. /* most-significant at offset 0 */
  3247. /* returns bcd */
  3248. /* */
  3249. /* bcd must have at least dn->digits bytes. No error is possible; if */
  3250. /* dn is a NaN or Infinite, digits must be 1 and the coefficient 0. */
  3251. /* ------------------------------------------------------------------ */
  3252. uByte * decNumberGetBCD(const decNumber *dn, uByte *bcd) {
  3253. uByte *ub=bcd+dn->digits-1; // -> lsd
  3254. const Unit *up=dn->lsu; // Unit pointer, -> lsu
  3255. #if DECDPUN==1 // trivial simple copy
  3256. for (; ub>=bcd; ub--, up++) *ub=*up;
  3257. #else // chopping needed
  3258. uInt u=*up; // work
  3259. uInt cut=DECDPUN; // downcounter through unit
  3260. for (; ub>=bcd; ub--) {
  3261. *ub=(uByte)(u%10); // [*6554 trick inhibits, here]
  3262. u=u/10;
  3263. cut--;
  3264. if (cut>0) continue; // more in this unit
  3265. up++;
  3266. u=*up;
  3267. cut=DECDPUN;
  3268. }
  3269. #endif
  3270. return bcd;
  3271. } // decNumberGetBCD
  3272. /* ------------------------------------------------------------------ */
  3273. /* decNumberSetBCD -- set (replace) the coefficient from BCD8 */
  3274. /* dn is the target decNumber */
  3275. /* bcd is the uInt array that will source n BCD bytes, most- */
  3276. /* significant at offset 0 */
  3277. /* n is the number of digits in the source BCD array (bcd) */
  3278. /* returns dn */
  3279. /* */
  3280. /* dn must have space for at least n digits. No error is possible; */
  3281. /* if dn is a NaN, or Infinite, or is to become a zero, n must be 1 */
  3282. /* and bcd[0] zero. */
  3283. /* ------------------------------------------------------------------ */
  3284. decNumber * decNumberSetBCD(decNumber *dn, const uByte *bcd, uInt n) {
  3285. Unit *up=dn->lsu+D2U(dn->digits)-1; // -> msu [target pointer]
  3286. const uByte *ub=bcd; // -> source msd
  3287. #if DECDPUN==1 // trivial simple copy
  3288. for (; ub<bcd+n; ub++, up--) *up=*ub;
  3289. #else // some assembly needed
  3290. // calculate how many digits in msu, and hence first cut
  3291. Int cut=MSUDIGITS(n); // [faster than remainder]
  3292. for (;up>=dn->lsu; up--) { // each Unit from msu
  3293. *up=0; // will take <=DECDPUN digits
  3294. for (; cut>0; ub++, cut--) *up=X10(*up)+*ub;
  3295. cut=DECDPUN; // next Unit has all digits
  3296. }
  3297. #endif
  3298. dn->digits=n; // set digit count
  3299. return dn;
  3300. } // decNumberSetBCD
  3301. /* ------------------------------------------------------------------ */
  3302. /* decNumberIsNormal -- test normality of a decNumber */
  3303. /* dn is the decNumber to test */
  3304. /* set is the context to use for Emin */
  3305. /* returns 1 if |dn| is finite and >=Nmin, 0 otherwise */
  3306. /* ------------------------------------------------------------------ */
  3307. Int decNumberIsNormal(const decNumber *dn, decContext *set) {
  3308. Int ae; // adjusted exponent
  3309. #if DECCHECK
  3310. if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
  3311. #endif
  3312. if (decNumberIsSpecial(dn)) return 0; // not finite
  3313. if (decNumberIsZero(dn)) return 0; // not non-zero
  3314. ae=dn->exponent+dn->digits-1; // adjusted exponent
  3315. if (ae<set->emin) return 0; // is subnormal
  3316. return 1;
  3317. } // decNumberIsNormal
  3318. /* ------------------------------------------------------------------ */
  3319. /* decNumberIsSubnormal -- test subnormality of a decNumber */
  3320. /* dn is the decNumber to test */
  3321. /* set is the context to use for Emin */
  3322. /* returns 1 if |dn| is finite, non-zero, and <Nmin, 0 otherwise */
  3323. /* ------------------------------------------------------------------ */
  3324. Int decNumberIsSubnormal(const decNumber *dn, decContext *set) {
  3325. Int ae; // adjusted exponent
  3326. #if DECCHECK
  3327. if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
  3328. #endif
  3329. if (decNumberIsSpecial(dn)) return 0; // not finite
  3330. if (decNumberIsZero(dn)) return 0; // not non-zero
  3331. ae=dn->exponent+dn->digits-1; // adjusted exponent
  3332. if (ae<set->emin) return 1; // is subnormal
  3333. return 0;
  3334. } // decNumberIsSubnormal
  3335. /* ------------------------------------------------------------------ */
  3336. /* decNumberTrim -- remove insignificant zeros */
  3337. /* */
  3338. /* dn is the number to trim */
  3339. /* returns dn */
  3340. /* */
  3341. /* All fields are updated as required. This is a utility operation, */
  3342. /* so special values are unchanged and no error is possible. The */
  3343. /* zeros are removed unconditionally. */
  3344. /* ------------------------------------------------------------------ */
  3345. decNumber * decNumberTrim(decNumber *dn) {
  3346. Int dropped; // work
  3347. decContext set; // ..
  3348. #if DECCHECK
  3349. if (decCheckOperands(DECUNRESU, DECUNUSED, dn, DECUNCONT)) return dn;
  3350. #endif
  3351. decContextDefault(&set, DEC_INIT_BASE); // clamp=0
  3352. return decTrim(dn, &set, 0, 1, &dropped);
  3353. } // decNumberTrim
  3354. /* ------------------------------------------------------------------ */
  3355. /* decNumberVersion -- return the name and version of this module */
  3356. /* */
  3357. /* No error is possible. */
  3358. /* ------------------------------------------------------------------ */
  3359. const char * decNumberVersion(void) {
  3360. return DECVERSION;
  3361. } // decNumberVersion
  3362. /* ------------------------------------------------------------------ */
  3363. /* decNumberZero -- set a number to 0 */
  3364. /* */
  3365. /* dn is the number to set, with space for one digit */
  3366. /* returns dn */
  3367. /* */
  3368. /* No error is possible. */
  3369. /* ------------------------------------------------------------------ */
  3370. // Memset is not used as it is much slower in some environments.
  3371. decNumber * decNumberZero(decNumber *dn) {
  3372. #if DECCHECK
  3373. if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
  3374. #endif
  3375. dn->bits=0;
  3376. dn->exponent=0;
  3377. dn->digits=1;
  3378. dn->lsu[0]=0;
  3379. return dn;
  3380. } // decNumberZero
  3381. /* ================================================================== */
  3382. /* Local routines */
  3383. /* ================================================================== */
  3384. /* ------------------------------------------------------------------ */
  3385. /* decToString -- lay out a number into a string */
  3386. /* */
  3387. /* dn is the number to lay out */
  3388. /* string is where to lay out the number */
  3389. /* eng is 1 if Engineering, 0 if Scientific */
  3390. /* */
  3391. /* string must be at least dn->digits+14 characters long */
  3392. /* No error is possible. */
  3393. /* */
  3394. /* Note that this routine can generate a -0 or 0.000. These are */
  3395. /* never generated in subset to-number or arithmetic, but can occur */
  3396. /* in non-subset arithmetic (e.g., -1*0 or 1.234-1.234). */
  3397. /* ------------------------------------------------------------------ */
  3398. // If DECCHECK is enabled the string "?" is returned if a number is
  3399. // invalid.
  3400. static void decToString(const decNumber *dn, char *string, Flag eng) {
  3401. Int exp=dn->exponent; // local copy
  3402. Int e; // E-part value
  3403. Int pre; // digits before the '.'
  3404. Int cut; // for counting digits in a Unit
  3405. char *c=string; // work [output pointer]
  3406. const Unit *up=dn->lsu+D2U(dn->digits)-1; // -> msu [input pointer]
  3407. uInt u, pow; // work
  3408. #if DECCHECK
  3409. if (decCheckOperands(DECUNRESU, dn, DECUNUSED, DECUNCONT)) {
  3410. strcpy(string, "?");
  3411. return;}
  3412. #endif
  3413. if (decNumberIsNegative(dn)) { // Negatives get a minus
  3414. *c='-';
  3415. c++;
  3416. }
  3417. if (dn->bits&DECSPECIAL) { // Is a special value
  3418. if (decNumberIsInfinite(dn)) {
  3419. strcpy(c, "Inf");
  3420. strcpy(c+3, "inity");
  3421. return;}
  3422. // a NaN
  3423. if (dn->bits&DECSNAN) { // signalling NaN
  3424. *c='s';
  3425. c++;
  3426. }
  3427. strcpy(c, "NaN");
  3428. c+=3; // step past
  3429. // if not a clean non-zero coefficient, that's all there is in a
  3430. // NaN string
  3431. if (exp!=0 || (*dn->lsu==0 && dn->digits==1)) return;
  3432. // [drop through to add integer]
  3433. }
  3434. // calculate how many digits in msu, and hence first cut
  3435. cut=MSUDIGITS(dn->digits); // [faster than remainder]
  3436. cut--; // power of ten for digit
  3437. if (exp==0) { // simple integer [common fastpath]
  3438. for (;up>=dn->lsu; up--) { // each Unit from msu
  3439. u=*up; // contains DECDPUN digits to lay out
  3440. for (; cut>=0; c++, cut--) TODIGIT(u, cut, c, pow);
  3441. cut=DECDPUN-1; // next Unit has all digits
  3442. }
  3443. *c='\0'; // terminate the string
  3444. return;}
  3445. /* non-0 exponent -- assume plain form */
  3446. pre=dn->digits+exp; // digits before '.'
  3447. e=0; // no E
  3448. if ((exp>0) || (pre<-5)) { // need exponential form
  3449. e=exp+dn->digits-1; // calculate E value
  3450. pre=1; // assume one digit before '.'
  3451. if (eng && (e!=0)) { // engineering: may need to adjust
  3452. Int adj; // adjustment
  3453. // The C remainder operator is undefined for negative numbers, so
  3454. // a positive remainder calculation must be used here
  3455. if (e<0) {
  3456. adj=(-e)%3;
  3457. if (adj!=0) adj=3-adj;
  3458. }
  3459. else { // e>0
  3460. adj=e%3;
  3461. }
  3462. e=e-adj;
  3463. // if dealing with zero still produce an exponent which is a
  3464. // multiple of three, as expected, but there will only be the
  3465. // one zero before the E, still. Otherwise note the padding.
  3466. if (!ISZERO(dn)) pre+=adj;
  3467. else { // is zero
  3468. if (adj!=0) { // 0.00Esnn needed
  3469. e=e+3;
  3470. pre=-(2-adj);
  3471. }
  3472. } // zero
  3473. } // eng
  3474. } // need exponent
  3475. /* lay out the digits of the coefficient, adding 0s and . as needed */
  3476. u=*up;
  3477. if (pre>0) { // xxx.xxx or xx00 (engineering) form
  3478. Int n=pre;
  3479. for (; pre>0; pre--, c++, cut--) {
  3480. if (cut<0) { // need new Unit
  3481. if (up==dn->lsu) break; // out of input digits (pre>digits)
  3482. up--;
  3483. cut=DECDPUN-1;
  3484. u=*up;
  3485. }
  3486. TODIGIT(u, cut, c, pow);
  3487. }
  3488. if (n<dn->digits) { // more to come, after '.'
  3489. *c='.'; c++;
  3490. for (;; c++, cut--) {
  3491. if (cut<0) { // need new Unit
  3492. if (up==dn->lsu) break; // out of input digits
  3493. up--;
  3494. cut=DECDPUN-1;
  3495. u=*up;
  3496. }
  3497. TODIGIT(u, cut, c, pow);
  3498. }
  3499. }
  3500. else for (; pre>0; pre--, c++) *c='0'; // 0 padding (for engineering) needed
  3501. }
  3502. else { // 0.xxx or 0.000xxx form
  3503. *c='0'; c++;
  3504. *c='.'; c++;
  3505. for (; pre<0; pre++, c++) *c='0'; // add any 0's after '.'
  3506. for (; ; c++, cut--) {
  3507. if (cut<0) { // need new Unit
  3508. if (up==dn->lsu) break; // out of input digits
  3509. up--;
  3510. cut=DECDPUN-1;
  3511. u=*up;
  3512. }
  3513. TODIGIT(u, cut, c, pow);
  3514. }
  3515. }
  3516. /* Finally add the E-part, if needed. It will never be 0, has a
  3517. base maximum and minimum of +999999999 through -999999999, but
  3518. could range down to -1999999998 for anormal numbers */
  3519. if (e!=0) {
  3520. Flag had=0; // 1=had non-zero
  3521. *c='E'; c++;
  3522. *c='+'; c++; // assume positive
  3523. u=e; // ..
  3524. if (e<0) {
  3525. *(c-1)='-'; // oops, need -
  3526. u=-e; // uInt, please
  3527. }
  3528. // lay out the exponent [_itoa or equivalent is not ANSI C]
  3529. for (cut=9; cut>=0; cut--) {
  3530. TODIGIT(u, cut, c, pow);
  3531. if (*c=='0' && !had) continue; // skip leading zeros
  3532. had=1; // had non-0
  3533. c++; // step for next
  3534. } // cut
  3535. }
  3536. *c='\0'; // terminate the string (all paths)
  3537. return;
  3538. } // decToString
  3539. /* ------------------------------------------------------------------ */
  3540. /* decAddOp -- add/subtract operation */
  3541. /* */
  3542. /* This computes C = A + B */
  3543. /* */
  3544. /* res is C, the result. C may be A and/or B (e.g., X=X+X) */
  3545. /* lhs is A */
  3546. /* rhs is B */
  3547. /* set is the context */
  3548. /* negate is DECNEG if rhs should be negated, or 0 otherwise */
  3549. /* status accumulates status for the caller */
  3550. /* */
  3551. /* C must have space for set->digits digits. */
  3552. /* Inexact in status must be 0 for correct Exact zero sign in result */
  3553. /* ------------------------------------------------------------------ */
  3554. /* If possible, the coefficient is calculated directly into C. */
  3555. /* However, if: */
  3556. /* -- a digits+1 calculation is needed because the numbers are */
  3557. /* unaligned and span more than set->digits digits */
  3558. /* -- a carry to digits+1 digits looks possible */
  3559. /* -- C is the same as A or B, and the result would destructively */
  3560. /* overlap the A or B coefficient */
  3561. /* then the result must be calculated into a temporary buffer. In */
  3562. /* this case a local (stack) buffer is used if possible, and only if */
  3563. /* too long for that does malloc become the final resort. */
  3564. /* */
  3565. /* Misalignment is handled as follows: */
  3566. /* Apad: (AExp>BExp) Swap operands and proceed as for BExp>AExp. */
  3567. /* BPad: Apply the padding by a combination of shifting (whole */
  3568. /* units) and multiplication (part units). */
  3569. /* */
  3570. /* Addition, especially x=x+1, is speed-critical. */
  3571. /* The static buffer is larger than might be expected to allow for */
  3572. /* calls from higher-level funtions (notable exp). */
  3573. /* ------------------------------------------------------------------ */
  3574. static decNumber * decAddOp(decNumber *res, const decNumber *lhs,
  3575. const decNumber *rhs, decContext *set,
  3576. uByte negate, uInt *status) {
  3577. #if DECSUBSET
  3578. decNumber *alloclhs=NULL; // non-NULL if rounded lhs allocated
  3579. decNumber *allocrhs=NULL; // .., rhs
  3580. #endif
  3581. Int rhsshift; // working shift (in Units)
  3582. Int maxdigits; // longest logical length
  3583. Int mult; // multiplier
  3584. Int residue; // rounding accumulator
  3585. uByte bits; // result bits
  3586. Flag diffsign; // non-0 if arguments have different sign
  3587. Unit *acc; // accumulator for result
  3588. Unit accbuff[SD2U(DECBUFFER*2+20)]; // local buffer [*2+20 reduces many
  3589. // allocations when called from
  3590. // other operations, notable exp]
  3591. Unit *allocacc=NULL; // -> allocated acc buffer, iff allocated
  3592. Int reqdigits=set->digits; // local copy; requested DIGITS
  3593. Int padding; // work
  3594. #if DECCHECK
  3595. if (decCheckOperands(res, lhs, rhs, set)) return res;
  3596. #endif
  3597. do { // protect allocated storage
  3598. #if DECSUBSET
  3599. if (!set->extended) {
  3600. // reduce operands and set lostDigits status, as needed
  3601. if (lhs->digits>reqdigits) {
  3602. alloclhs=decRoundOperand(lhs, set, status);
  3603. if (alloclhs==NULL) break;
  3604. lhs=alloclhs;
  3605. }
  3606. if (rhs->digits>reqdigits) {
  3607. allocrhs=decRoundOperand(rhs, set, status);
  3608. if (allocrhs==NULL) break;
  3609. rhs=allocrhs;
  3610. }
  3611. }
  3612. #endif
  3613. // [following code does not require input rounding]
  3614. // note whether signs differ [used all paths]
  3615. diffsign=(Flag)((lhs->bits^rhs->bits^negate)&DECNEG);
  3616. // handle infinities and NaNs
  3617. if (SPECIALARGS) { // a special bit set
  3618. if (SPECIALARGS & (DECSNAN | DECNAN)) // a NaN
  3619. decNaNs(res, lhs, rhs, set, status);
  3620. else { // one or two infinities
  3621. if (decNumberIsInfinite(lhs)) { // LHS is infinity
  3622. // two infinities with different signs is invalid
  3623. if (decNumberIsInfinite(rhs) && diffsign) {
  3624. *status|=DEC_Invalid_operation;
  3625. break;
  3626. }
  3627. bits=lhs->bits & DECNEG; // get sign from LHS
  3628. }
  3629. else bits=(rhs->bits^negate) & DECNEG;// RHS must be Infinity
  3630. bits|=DECINF;
  3631. decNumberZero(res);
  3632. res->bits=bits; // set +/- infinity
  3633. } // an infinity
  3634. break;
  3635. }
  3636. // Quick exit for add 0s; return the non-0, modified as need be
  3637. if (ISZERO(lhs)) {
  3638. Int adjust; // work
  3639. Int lexp=lhs->exponent; // save in case LHS==RES
  3640. bits=lhs->bits; // ..
  3641. residue=0; // clear accumulator
  3642. decCopyFit(res, rhs, set, &residue, status); // copy (as needed)
  3643. res->bits^=negate; // flip if rhs was negated
  3644. #if DECSUBSET
  3645. if (set->extended) { // exponents on zeros count
  3646. #endif
  3647. // exponent will be the lower of the two
  3648. adjust=lexp-res->exponent; // adjustment needed [if -ve]
  3649. if (ISZERO(res)) { // both 0: special IEEE 754 rules
  3650. if (adjust<0) res->exponent=lexp; // set exponent
  3651. // 0-0 gives +0 unless rounding to -infinity, and -0-0 gives -0
  3652. if (diffsign) {
  3653. if (set->round!=DEC_ROUND_FLOOR) res->bits=0;
  3654. else res->bits=DECNEG; // preserve 0 sign
  3655. }
  3656. }
  3657. else { // non-0 res
  3658. if (adjust<0) { // 0-padding needed
  3659. if ((res->digits-adjust)>set->digits) {
  3660. adjust=res->digits-set->digits; // to fit exactly
  3661. *status|=DEC_Rounded; // [but exact]
  3662. }
  3663. res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
  3664. res->exponent+=adjust; // set the exponent.
  3665. }
  3666. } // non-0 res
  3667. #if DECSUBSET
  3668. } // extended
  3669. #endif
  3670. decFinish(res, set, &residue, status); // clean and finalize
  3671. break;}
  3672. if (ISZERO(rhs)) { // [lhs is non-zero]
  3673. Int adjust; // work
  3674. Int rexp=rhs->exponent; // save in case RHS==RES
  3675. bits=rhs->bits; // be clean
  3676. residue=0; // clear accumulator
  3677. decCopyFit(res, lhs, set, &residue, status); // copy (as needed)
  3678. #if DECSUBSET
  3679. if (set->extended) { // exponents on zeros count
  3680. #endif
  3681. // exponent will be the lower of the two
  3682. // [0-0 case handled above]
  3683. adjust=rexp-res->exponent; // adjustment needed [if -ve]
  3684. if (adjust<0) { // 0-padding needed
  3685. if ((res->digits-adjust)>set->digits) {
  3686. adjust=res->digits-set->digits; // to fit exactly
  3687. *status|=DEC_Rounded; // [but exact]
  3688. }
  3689. res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
  3690. res->exponent+=adjust; // set the exponent.
  3691. }
  3692. #if DECSUBSET
  3693. } // extended
  3694. #endif
  3695. decFinish(res, set, &residue, status); // clean and finalize
  3696. break;}
  3697. // [NB: both fastpath and mainpath code below assume these cases
  3698. // (notably 0-0) have already been handled]
  3699. // calculate the padding needed to align the operands
  3700. padding=rhs->exponent-lhs->exponent;
  3701. // Fastpath cases where the numbers are aligned and normal, the RHS
  3702. // is all in one unit, no operand rounding is needed, and no carry,
  3703. // lengthening, or borrow is needed
  3704. if (padding==0
  3705. && rhs->digits<=DECDPUN
  3706. && rhs->exponent>=set->emin // [some normals drop through]
  3707. && rhs->exponent<=set->emax-set->digits+1 // [could clamp]
  3708. && rhs->digits<=reqdigits
  3709. && lhs->digits<=reqdigits) {
  3710. Int partial=*lhs->lsu;
  3711. if (!diffsign) { // adding
  3712. partial+=*rhs->lsu;
  3713. if ((partial<=DECDPUNMAX) // result fits in unit
  3714. && (lhs->digits>=DECDPUN || // .. and no digits-count change
  3715. partial<(Int)powers[lhs->digits])) { // ..
  3716. if (res!=lhs) decNumberCopy(res, lhs); // not in place
  3717. *res->lsu=(Unit)partial; // [copy could have overwritten RHS]
  3718. break;
  3719. }
  3720. // else drop out for careful add
  3721. }
  3722. else { // signs differ
  3723. partial-=*rhs->lsu;
  3724. if (partial>0) { // no borrow needed, and non-0 result
  3725. if (res!=lhs) decNumberCopy(res, lhs); // not in place
  3726. *res->lsu=(Unit)partial;
  3727. // this could have reduced digits [but result>0]
  3728. res->digits=decGetDigits(res->lsu, D2U(res->digits));
  3729. break;
  3730. }
  3731. // else drop out for careful subtract
  3732. }
  3733. }
  3734. // Now align (pad) the lhs or rhs so they can be added or
  3735. // subtracted, as necessary. If one number is much larger than
  3736. // the other (that is, if in plain form there is a least one
  3737. // digit between the lowest digit of one and the highest of the
  3738. // other) padding with up to DIGITS-1 trailing zeros may be
  3739. // needed; then apply rounding (as exotic rounding modes may be
  3740. // affected by the residue).
  3741. rhsshift=0; // rhs shift to left (padding) in Units
  3742. bits=lhs->bits; // assume sign is that of LHS
  3743. mult=1; // likely multiplier
  3744. // [if padding==0 the operands are aligned; no padding is needed]
  3745. if (padding!=0) {
  3746. // some padding needed; always pad the RHS, as any required
  3747. // padding can then be effected by a simple combination of
  3748. // shifts and a multiply
  3749. Flag swapped=0;
  3750. if (padding<0) { // LHS needs the padding
  3751. const decNumber *t;
  3752. padding=-padding; // will be +ve
  3753. bits=(uByte)(rhs->bits^negate); // assumed sign is now that of RHS
  3754. t=lhs; lhs=rhs; rhs=t;
  3755. swapped=1;
  3756. }
  3757. // If, after pad, rhs would be longer than lhs by digits+1 or
  3758. // more then lhs cannot affect the answer, except as a residue,
  3759. // so only need to pad up to a length of DIGITS+1.
  3760. if (rhs->digits+padding > lhs->digits+reqdigits+1) {
  3761. // The RHS is sufficient
  3762. // for residue use the relative sign indication...
  3763. Int shift=reqdigits-rhs->digits; // left shift needed
  3764. residue=1; // residue for rounding
  3765. if (diffsign) residue=-residue; // signs differ
  3766. // copy, shortening if necessary
  3767. decCopyFit(res, rhs, set, &residue, status);
  3768. // if it was already shorter, then need to pad with zeros
  3769. if (shift>0) {
  3770. res->digits=decShiftToMost(res->lsu, res->digits, shift);
  3771. res->exponent-=shift; // adjust the exponent.
  3772. }
  3773. // flip the result sign if unswapped and rhs was negated
  3774. if (!swapped) res->bits^=negate;
  3775. decFinish(res, set, &residue, status); // done
  3776. break;}
  3777. // LHS digits may affect result
  3778. rhsshift=D2U(padding+1)-1; // this much by Unit shift ..
  3779. mult=powers[padding-(rhsshift*DECDPUN)]; // .. this by multiplication
  3780. } // padding needed
  3781. if (diffsign) mult=-mult; // signs differ
  3782. // determine the longer operand
  3783. maxdigits=rhs->digits+padding; // virtual length of RHS
  3784. if (lhs->digits>maxdigits) maxdigits=lhs->digits;
  3785. // Decide on the result buffer to use; if possible place directly
  3786. // into result.
  3787. acc=res->lsu; // assume add direct to result
  3788. // If destructive overlap, or the number is too long, or a carry or
  3789. // borrow to DIGITS+1 might be possible, a buffer must be used.
  3790. // [Might be worth more sophisticated tests when maxdigits==reqdigits]
  3791. if ((maxdigits>=reqdigits) // is, or could be, too large
  3792. || (res==rhs && rhsshift>0)) { // destructive overlap
  3793. // buffer needed, choose it; units for maxdigits digits will be
  3794. // needed, +1 Unit for carry or borrow
  3795. Int need=D2U(maxdigits)+1;
  3796. acc=accbuff; // assume use local buffer
  3797. if (need*sizeof(Unit)>sizeof(accbuff)) {
  3798. // printf("malloc add %ld %ld\n", need, sizeof(accbuff));
  3799. allocacc=(Unit *)malloc(need*sizeof(Unit));
  3800. if (allocacc==NULL) { // hopeless -- abandon
  3801. *status|=DEC_Insufficient_storage;
  3802. break;}
  3803. acc=allocacc;
  3804. }
  3805. }
  3806. res->bits=(uByte)(bits&DECNEG); // it's now safe to overwrite..
  3807. res->exponent=lhs->exponent; // .. operands (even if aliased)
  3808. #if DECTRACE
  3809. decDumpAr('A', lhs->lsu, D2U(lhs->digits));
  3810. decDumpAr('B', rhs->lsu, D2U(rhs->digits));
  3811. printf(" :h: %ld %ld\n", rhsshift, mult);
  3812. #endif
  3813. // add [A+B*m] or subtract [A+B*(-m)]
  3814. res->digits=decUnitAddSub(lhs->lsu, D2U(lhs->digits),
  3815. rhs->lsu, D2U(rhs->digits),
  3816. rhsshift, acc, mult)
  3817. *DECDPUN; // [units -> digits]
  3818. if (res->digits<0) { // borrowed...
  3819. res->digits=-res->digits;
  3820. res->bits^=DECNEG; // flip the sign
  3821. }
  3822. #if DECTRACE
  3823. decDumpAr('+', acc, D2U(res->digits));
  3824. #endif
  3825. // If a buffer was used the result must be copied back, possibly
  3826. // shortening. (If no buffer was used then the result must have
  3827. // fit, so can't need rounding and residue must be 0.)
  3828. residue=0; // clear accumulator
  3829. if (acc!=res->lsu) {
  3830. #if DECSUBSET
  3831. if (set->extended) { // round from first significant digit
  3832. #endif
  3833. // remove leading zeros that were added due to rounding up to
  3834. // integral Units -- before the test for rounding.
  3835. if (res->digits>reqdigits)
  3836. res->digits=decGetDigits(acc, D2U(res->digits));
  3837. decSetCoeff(res, set, acc, res->digits, &residue, status);
  3838. #if DECSUBSET
  3839. }
  3840. else { // subset arithmetic rounds from original significant digit
  3841. // May have an underestimate. This only occurs when both
  3842. // numbers fit in DECDPUN digits and are padding with a
  3843. // negative multiple (-10, -100...) and the top digit(s) become
  3844. // 0. (This only matters when using X3.274 rules where the
  3845. // leading zero could be included in the rounding.)
  3846. if (res->digits<maxdigits) {
  3847. *(acc+D2U(res->digits))=0; // ensure leading 0 is there
  3848. res->digits=maxdigits;
  3849. }
  3850. else {
  3851. // remove leading zeros that added due to rounding up to
  3852. // integral Units (but only those in excess of the original
  3853. // maxdigits length, unless extended) before test for rounding.
  3854. if (res->digits>reqdigits) {
  3855. res->digits=decGetDigits(acc, D2U(res->digits));
  3856. if (res->digits<maxdigits) res->digits=maxdigits;
  3857. }
  3858. }
  3859. decSetCoeff(res, set, acc, res->digits, &residue, status);
  3860. // Now apply rounding if needed before removing leading zeros.
  3861. // This is safe because subnormals are not a possibility
  3862. if (residue!=0) {
  3863. decApplyRound(res, set, residue, status);
  3864. residue=0; // did what needed to be done
  3865. }
  3866. } // subset
  3867. #endif
  3868. } // used buffer
  3869. // strip leading zeros [these were left on in case of subset subtract]
  3870. res->digits=decGetDigits(res->lsu, D2U(res->digits));
  3871. // apply checks and rounding
  3872. decFinish(res, set, &residue, status);
  3873. // "When the sum of two operands with opposite signs is exactly
  3874. // zero, the sign of that sum shall be '+' in all rounding modes
  3875. // except round toward -Infinity, in which mode that sign shall be
  3876. // '-'." [Subset zeros also never have '-', set by decFinish.]
  3877. if (ISZERO(res) && diffsign
  3878. #if DECSUBSET
  3879. && set->extended
  3880. #endif
  3881. && (*status&DEC_Inexact)==0) {
  3882. if (set->round==DEC_ROUND_FLOOR) res->bits|=DECNEG; // sign -
  3883. else res->bits&=~DECNEG; // sign +
  3884. }
  3885. } while(0); // end protected
  3886. if (allocacc!=NULL) free(allocacc); // drop any storage used
  3887. #if DECSUBSET
  3888. if (allocrhs!=NULL) free(allocrhs); // ..
  3889. if (alloclhs!=NULL) free(alloclhs); // ..
  3890. #endif
  3891. return res;
  3892. } // decAddOp
  3893. /* ------------------------------------------------------------------ */
  3894. /* decDivideOp -- division operation */
  3895. /* */
  3896. /* This routine performs the calculations for all four division */
  3897. /* operators (divide, divideInteger, remainder, remainderNear). */
  3898. /* */
  3899. /* C=A op B */
  3900. /* */
  3901. /* res is C, the result. C may be A and/or B (e.g., X=X/X) */
  3902. /* lhs is A */
  3903. /* rhs is B */
  3904. /* set is the context */
  3905. /* op is DIVIDE, DIVIDEINT, REMAINDER, or REMNEAR respectively. */
  3906. /* status is the usual accumulator */
  3907. /* */
  3908. /* C must have space for set->digits digits. */
  3909. /* */
  3910. /* ------------------------------------------------------------------ */
  3911. /* The underlying algorithm of this routine is the same as in the */
  3912. /* 1981 S/370 implementation, that is, non-restoring long division */
  3913. /* with bi-unit (rather than bi-digit) estimation for each unit */
  3914. /* multiplier. In this pseudocode overview, complications for the */
  3915. /* Remainder operators and division residues for exact rounding are */
  3916. /* omitted for clarity. */
  3917. /* */
  3918. /* Prepare operands and handle special values */
  3919. /* Test for x/0 and then 0/x */
  3920. /* Exp =Exp1 - Exp2 */
  3921. /* Exp =Exp +len(var1) -len(var2) */
  3922. /* Sign=Sign1 * Sign2 */
  3923. /* Pad accumulator (Var1) to double-length with 0's (pad1) */
  3924. /* Pad Var2 to same length as Var1 */
  3925. /* msu2pair/plus=1st 2 or 1 units of var2, +1 to allow for round */
  3926. /* have=0 */
  3927. /* Do until (have=digits+1 OR residue=0) */
  3928. /* if exp<0 then if integer divide/residue then leave */
  3929. /* this_unit=0 */
  3930. /* Do forever */
  3931. /* compare numbers */
  3932. /* if <0 then leave inner_loop */
  3933. /* if =0 then (* quick exit without subtract *) do */
  3934. /* this_unit=this_unit+1; output this_unit */
  3935. /* leave outer_loop; end */
  3936. /* Compare lengths of numbers (mantissae): */
  3937. /* If same then tops2=msu2pair -- {units 1&2 of var2} */
  3938. /* else tops2=msu2plus -- {0, unit 1 of var2} */
  3939. /* tops1=first_unit_of_Var1*10**DECDPUN +second_unit_of_var1 */
  3940. /* mult=tops1/tops2 -- Good and safe guess at divisor */
  3941. /* if mult=0 then mult=1 */
  3942. /* this_unit=this_unit+mult */
  3943. /* subtract */
  3944. /* end inner_loop */
  3945. /* if have\=0 | this_unit\=0 then do */
  3946. /* output this_unit */
  3947. /* have=have+1; end */
  3948. /* var2=var2/10 */
  3949. /* exp=exp-1 */
  3950. /* end outer_loop */
  3951. /* exp=exp+1 -- set the proper exponent */
  3952. /* if have=0 then generate answer=0 */
  3953. /* Return (Result is defined by Var1) */
  3954. /* */
  3955. /* ------------------------------------------------------------------ */
  3956. /* Two working buffers are needed during the division; one (digits+ */
  3957. /* 1) to accumulate the result, and the other (up to 2*digits+1) for */
  3958. /* long subtractions. These are acc and var1 respectively. */
  3959. /* var1 is a copy of the lhs coefficient, var2 is the rhs coefficient.*/
  3960. /* The static buffers may be larger than might be expected to allow */
  3961. /* for calls from higher-level funtions (notable exp). */
  3962. /* ------------------------------------------------------------------ */
  3963. static decNumber * decDivideOp(decNumber *res,
  3964. const decNumber *lhs, const decNumber *rhs,
  3965. decContext *set, Flag op, uInt *status) {
  3966. #if DECSUBSET
  3967. decNumber *alloclhs=NULL; // non-NULL if rounded lhs allocated
  3968. decNumber *allocrhs=NULL; // .., rhs
  3969. #endif
  3970. Unit accbuff[SD2U(DECBUFFER+DECDPUN+10)]; // local buffer
  3971. Unit *acc=accbuff; // -> accumulator array for result
  3972. Unit *allocacc=NULL; // -> allocated buffer, iff allocated
  3973. Unit *accnext; // -> where next digit will go
  3974. Int acclength; // length of acc needed [Units]
  3975. Int accunits; // count of units accumulated
  3976. Int accdigits; // count of digits accumulated
  3977. Unit varbuff[SD2U(DECBUFFER*2+DECDPUN)]; // buffer for var1
  3978. Unit *var1=varbuff; // -> var1 array for long subtraction
  3979. Unit *varalloc=NULL; // -> allocated buffer, iff used
  3980. Unit *msu1; // -> msu of var1
  3981. const Unit *var2; // -> var2 array
  3982. const Unit *msu2; // -> msu of var2
  3983. Int msu2plus; // msu2 plus one [does not vary]
  3984. eInt msu2pair; // msu2 pair plus one [does not vary]
  3985. Int var1units, var2units; // actual lengths
  3986. Int var2ulen; // logical length (units)
  3987. Int var1initpad=0; // var1 initial padding (digits)
  3988. Int maxdigits; // longest LHS or required acc length
  3989. Int mult; // multiplier for subtraction
  3990. Unit thisunit; // current unit being accumulated
  3991. Int residue; // for rounding
  3992. Int reqdigits=set->digits; // requested DIGITS
  3993. Int exponent; // working exponent
  3994. Int maxexponent=0; // DIVIDE maximum exponent if unrounded
  3995. uByte bits; // working sign
  3996. Unit *target; // work
  3997. const Unit *source; // ..
  3998. uInt const *pow; // ..
  3999. Int shift, cut; // ..
  4000. #if DECSUBSET
  4001. Int dropped; // work
  4002. #endif
  4003. #if DECCHECK
  4004. if (decCheckOperands(res, lhs, rhs, set)) return res;
  4005. #endif
  4006. do { // protect allocated storage
  4007. #if DECSUBSET
  4008. if (!set->extended) {
  4009. // reduce operands and set lostDigits status, as needed
  4010. if (lhs->digits>reqdigits) {
  4011. alloclhs=decRoundOperand(lhs, set, status);
  4012. if (alloclhs==NULL) break;
  4013. lhs=alloclhs;
  4014. }
  4015. if (rhs->digits>reqdigits) {
  4016. allocrhs=decRoundOperand(rhs, set, status);
  4017. if (allocrhs==NULL) break;
  4018. rhs=allocrhs;
  4019. }
  4020. }
  4021. #endif
  4022. // [following code does not require input rounding]
  4023. bits=(lhs->bits^rhs->bits)&DECNEG; // assumed sign for divisions
  4024. // handle infinities and NaNs
  4025. if (SPECIALARGS) { // a special bit set
  4026. if (SPECIALARGS & (DECSNAN | DECNAN)) { // one or two NaNs
  4027. decNaNs(res, lhs, rhs, set, status);
  4028. break;
  4029. }
  4030. // one or two infinities
  4031. if (decNumberIsInfinite(lhs)) { // LHS (dividend) is infinite
  4032. if (decNumberIsInfinite(rhs) || // two infinities are invalid ..
  4033. op & (REMAINDER | REMNEAR)) { // as is remainder of infinity
  4034. *status|=DEC_Invalid_operation;
  4035. break;
  4036. }
  4037. // [Note that infinity/0 raises no exceptions]
  4038. decNumberZero(res);
  4039. res->bits=bits|DECINF; // set +/- infinity
  4040. break;
  4041. }
  4042. else { // RHS (divisor) is infinite
  4043. residue=0;
  4044. if (op&(REMAINDER|REMNEAR)) {
  4045. // result is [finished clone of] lhs
  4046. decCopyFit(res, lhs, set, &residue, status);
  4047. }
  4048. else { // a division
  4049. decNumberZero(res);
  4050. res->bits=bits; // set +/- zero
  4051. // for DIVIDEINT the exponent is always 0. For DIVIDE, result
  4052. // is a 0 with infinitely negative exponent, clamped to minimum
  4053. if (op&DIVIDE) {
  4054. res->exponent=set->emin-set->digits+1;
  4055. *status|=DEC_Clamped;
  4056. }
  4057. }
  4058. decFinish(res, set, &residue, status);
  4059. break;
  4060. }
  4061. }
  4062. // handle 0 rhs (x/0)
  4063. if (ISZERO(rhs)) { // x/0 is always exceptional
  4064. if (ISZERO(lhs)) {
  4065. decNumberZero(res); // [after lhs test]
  4066. *status|=DEC_Division_undefined;// 0/0 will become NaN
  4067. }
  4068. else {
  4069. decNumberZero(res);
  4070. if (op&(REMAINDER|REMNEAR)) *status|=DEC_Invalid_operation;
  4071. else {
  4072. *status|=DEC_Division_by_zero; // x/0
  4073. res->bits=bits|DECINF; // .. is +/- Infinity
  4074. }
  4075. }
  4076. break;}
  4077. // handle 0 lhs (0/x)
  4078. if (ISZERO(lhs)) { // 0/x [x!=0]
  4079. #if DECSUBSET
  4080. if (!set->extended) decNumberZero(res);
  4081. else {
  4082. #endif
  4083. if (op&DIVIDE) {
  4084. residue=0;
  4085. exponent=lhs->exponent-rhs->exponent; // ideal exponent
  4086. decNumberCopy(res, lhs); // [zeros always fit]
  4087. res->bits=bits; // sign as computed
  4088. res->exponent=exponent; // exponent, too
  4089. decFinalize(res, set, &residue, status); // check exponent
  4090. }
  4091. else if (op&DIVIDEINT) {
  4092. decNumberZero(res); // integer 0
  4093. res->bits=bits; // sign as computed
  4094. }
  4095. else { // a remainder
  4096. exponent=rhs->exponent; // [save in case overwrite]
  4097. decNumberCopy(res, lhs); // [zeros always fit]
  4098. if (exponent<res->exponent) res->exponent=exponent; // use lower
  4099. }
  4100. #if DECSUBSET
  4101. }
  4102. #endif
  4103. break;}
  4104. // Precalculate exponent. This starts off adjusted (and hence fits
  4105. // in 31 bits) and becomes the usual unadjusted exponent as the
  4106. // division proceeds. The order of evaluation is important, here,
  4107. // to avoid wrap.
  4108. exponent=(lhs->exponent+lhs->digits)-(rhs->exponent+rhs->digits);
  4109. // If the working exponent is -ve, then some quick exits are
  4110. // possible because the quotient is known to be <1
  4111. // [for REMNEAR, it needs to be < -1, as -0.5 could need work]
  4112. if (exponent<0 && !(op==DIVIDE)) {
  4113. if (op&DIVIDEINT) {
  4114. decNumberZero(res); // integer part is 0
  4115. #if DECSUBSET
  4116. if (set->extended)
  4117. #endif
  4118. res->bits=bits; // set +/- zero
  4119. break;}
  4120. // fastpath remainders so long as the lhs has the smaller
  4121. // (or equal) exponent
  4122. if (lhs->exponent<=rhs->exponent) {
  4123. if (op&REMAINDER || exponent<-1) {
  4124. // It is REMAINDER or safe REMNEAR; result is [finished
  4125. // clone of] lhs (r = x - 0*y)
  4126. residue=0;
  4127. decCopyFit(res, lhs, set, &residue, status);
  4128. decFinish(res, set, &residue, status);
  4129. break;
  4130. }
  4131. // [unsafe REMNEAR drops through]
  4132. }
  4133. } // fastpaths
  4134. /* Long (slow) division is needed; roll up the sleeves... */
  4135. // The accumulator will hold the quotient of the division.
  4136. // If it needs to be too long for stack storage, then allocate.
  4137. acclength=D2U(reqdigits+DECDPUN); // in Units
  4138. if (acclength*sizeof(Unit)>sizeof(accbuff)) {
  4139. // printf("malloc dvacc %ld units\n", acclength);
  4140. allocacc=(Unit *)malloc(acclength*sizeof(Unit));
  4141. if (allocacc==NULL) { // hopeless -- abandon
  4142. *status|=DEC_Insufficient_storage;
  4143. break;}
  4144. acc=allocacc; // use the allocated space
  4145. }
  4146. // var1 is the padded LHS ready for subtractions.
  4147. // If it needs to be too long for stack storage, then allocate.
  4148. // The maximum units needed for var1 (long subtraction) is:
  4149. // Enough for
  4150. // (rhs->digits+reqdigits-1) -- to allow full slide to right
  4151. // or (lhs->digits) -- to allow for long lhs
  4152. // whichever is larger
  4153. // +1 -- for rounding of slide to right
  4154. // +1 -- for leading 0s
  4155. // +1 -- for pre-adjust if a remainder or DIVIDEINT
  4156. // [Note: unused units do not participate in decUnitAddSub data]
  4157. maxdigits=rhs->digits+reqdigits-1;
  4158. if (lhs->digits>maxdigits) maxdigits=lhs->digits;
  4159. var1units=D2U(maxdigits)+2;
  4160. // allocate a guard unit above msu1 for REMAINDERNEAR
  4161. if (!(op&DIVIDE)) var1units++;
  4162. if ((var1units+1)*sizeof(Unit)>sizeof(varbuff)) {
  4163. // printf("malloc dvvar %ld units\n", var1units+1);
  4164. varalloc=(Unit *)malloc((var1units+1)*sizeof(Unit));
  4165. if (varalloc==NULL) { // hopeless -- abandon
  4166. *status|=DEC_Insufficient_storage;
  4167. break;}
  4168. var1=varalloc; // use the allocated space
  4169. }
  4170. // Extend the lhs and rhs to full long subtraction length. The lhs
  4171. // is truly extended into the var1 buffer, with 0 padding, so a
  4172. // subtract in place is always possible. The rhs (var2) has
  4173. // virtual padding (implemented by decUnitAddSub).
  4174. // One guard unit was allocated above msu1 for rem=rem+rem in
  4175. // REMAINDERNEAR.
  4176. msu1=var1+var1units-1; // msu of var1
  4177. source=lhs->lsu+D2U(lhs->digits)-1; // msu of input array
  4178. for (target=msu1; source>=lhs->lsu; source--, target--) *target=*source;
  4179. for (; target>=var1; target--) *target=0;
  4180. // rhs (var2) is left-aligned with var1 at the start
  4181. var2ulen=var1units; // rhs logical length (units)
  4182. var2units=D2U(rhs->digits); // rhs actual length (units)
  4183. var2=rhs->lsu; // -> rhs array
  4184. msu2=var2+var2units-1; // -> msu of var2 [never changes]
  4185. // now set up the variables which will be used for estimating the
  4186. // multiplication factor. If these variables are not exact, add
  4187. // 1 to make sure that the multiplier is never overestimated.
  4188. msu2plus=*msu2; // it's value ..
  4189. if (var2units>1) msu2plus++; // .. +1 if any more
  4190. msu2pair=(eInt)*msu2*(DECDPUNMAX+1);// top two pair ..
  4191. if (var2units>1) { // .. [else treat 2nd as 0]
  4192. msu2pair+=*(msu2-1); // ..
  4193. if (var2units>2) msu2pair++; // .. +1 if any more
  4194. }
  4195. // The calculation is working in units, which may have leading zeros,
  4196. // but the exponent was calculated on the assumption that they are
  4197. // both left-aligned. Adjust the exponent to compensate: add the
  4198. // number of leading zeros in var1 msu and subtract those in var2 msu.
  4199. // [This is actually done by counting the digits and negating, as
  4200. // lead1=DECDPUN-digits1, and similarly for lead2.]
  4201. for (pow=&powers[1]; *msu1>=*pow; pow++) exponent--;
  4202. for (pow=&powers[1]; *msu2>=*pow; pow++) exponent++;
  4203. // Now, if doing an integer divide or remainder, ensure that
  4204. // the result will be Unit-aligned. To do this, shift the var1
  4205. // accumulator towards least if need be. (It's much easier to
  4206. // do this now than to reassemble the residue afterwards, if
  4207. // doing a remainder.) Also ensure the exponent is not negative.
  4208. if (!(op&DIVIDE)) {
  4209. Unit *u; // work
  4210. // save the initial 'false' padding of var1, in digits
  4211. var1initpad=(var1units-D2U(lhs->digits))*DECDPUN;
  4212. // Determine the shift to do.
  4213. if (exponent<0) cut=-exponent;
  4214. else cut=DECDPUN-exponent%DECDPUN;
  4215. decShiftToLeast(var1, var1units, cut);
  4216. exponent+=cut; // maintain numerical value
  4217. var1initpad-=cut; // .. and reduce padding
  4218. // clean any most-significant units which were just emptied
  4219. for (u=msu1; cut>=DECDPUN; cut-=DECDPUN, u--) *u=0;
  4220. } // align
  4221. else { // is DIVIDE
  4222. maxexponent=lhs->exponent-rhs->exponent; // save
  4223. // optimization: if the first iteration will just produce 0,
  4224. // preadjust to skip it [valid for DIVIDE only]
  4225. if (*msu1<*msu2) {
  4226. var2ulen--; // shift down
  4227. exponent-=DECDPUN; // update the exponent
  4228. }
  4229. }
  4230. // ---- start the long-division loops ------------------------------
  4231. accunits=0; // no units accumulated yet
  4232. accdigits=0; // .. or digits
  4233. accnext=acc+acclength-1; // -> msu of acc [NB: allows digits+1]
  4234. for (;;) { // outer forever loop
  4235. thisunit=0; // current unit assumed 0
  4236. // find the next unit
  4237. for (;;) { // inner forever loop
  4238. // strip leading zero units [from either pre-adjust or from
  4239. // subtract last time around]. Leave at least one unit.
  4240. for (; *msu1==0 && msu1>var1; msu1--) var1units--;
  4241. if (var1units<var2ulen) break; // var1 too low for subtract
  4242. if (var1units==var2ulen) { // unit-by-unit compare needed
  4243. // compare the two numbers, from msu
  4244. const Unit *pv1, *pv2;
  4245. Unit v2; // units to compare
  4246. pv2=msu2; // -> msu
  4247. for (pv1=msu1; ; pv1--, pv2--) {
  4248. // v1=*pv1 -- always OK
  4249. v2=0; // assume in padding
  4250. if (pv2>=var2) v2=*pv2; // in range
  4251. if (*pv1!=v2) break; // no longer the same
  4252. if (pv1==var1) break; // done; leave pv1 as is
  4253. }
  4254. // here when all inspected or a difference seen
  4255. if (*pv1<v2) break; // var1 too low to subtract
  4256. if (*pv1==v2) { // var1 == var2
  4257. // reach here if var1 and var2 are identical; subtraction
  4258. // would increase digit by one, and the residue will be 0 so
  4259. // the calculation is done; leave the loop with residue=0.
  4260. thisunit++; // as though subtracted
  4261. *var1=0; // set var1 to 0
  4262. var1units=1; // ..
  4263. break; // from inner
  4264. } // var1 == var2
  4265. // *pv1>v2. Prepare for real subtraction; the lengths are equal
  4266. // Estimate the multiplier (there's always a msu1-1)...
  4267. // Bring in two units of var2 to provide a good estimate.
  4268. mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2pair);
  4269. } // lengths the same
  4270. else { // var1units > var2ulen, so subtraction is safe
  4271. // The var2 msu is one unit towards the lsu of the var1 msu,
  4272. // so only one unit for var2 can be used.
  4273. mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2plus);
  4274. }
  4275. if (mult==0) mult=1; // must always be at least 1
  4276. // subtraction needed; var1 is > var2
  4277. thisunit=(Unit)(thisunit+mult); // accumulate
  4278. // subtract var1-var2, into var1; only the overlap needs
  4279. // processing, as this is an in-place calculation
  4280. shift=var2ulen-var2units;
  4281. #if DECTRACE
  4282. decDumpAr('1', &var1[shift], var1units-shift);
  4283. decDumpAr('2', var2, var2units);
  4284. printf("m=%ld\n", -mult);
  4285. #endif
  4286. decUnitAddSub(&var1[shift], var1units-shift,
  4287. var2, var2units, 0,
  4288. &var1[shift], -mult);
  4289. #if DECTRACE
  4290. decDumpAr('#', &var1[shift], var1units-shift);
  4291. #endif
  4292. // var1 now probably has leading zeros; these are removed at the
  4293. // top of the inner loop.
  4294. } // inner loop
  4295. // The next unit has been calculated in full; unless it's a
  4296. // leading zero, add to acc
  4297. if (accunits!=0 || thisunit!=0) { // is first or non-zero
  4298. *accnext=thisunit; // store in accumulator
  4299. // account exactly for the new digits
  4300. if (accunits==0) {
  4301. accdigits++; // at least one
  4302. for (pow=&powers[1]; thisunit>=*pow; pow++) accdigits++;
  4303. }
  4304. else accdigits+=DECDPUN;
  4305. accunits++; // update count
  4306. accnext--; // ready for next
  4307. if (accdigits>reqdigits) break; // have enough digits
  4308. }
  4309. // if the residue is zero, the operation is done (unless divide
  4310. // or divideInteger and still not enough digits yet)
  4311. if (*var1==0 && var1units==1) { // residue is 0
  4312. if (op&(REMAINDER|REMNEAR)) break;
  4313. if ((op&DIVIDE) && (exponent<=maxexponent)) break;
  4314. // [drop through if divideInteger]
  4315. }
  4316. // also done enough if calculating remainder or integer
  4317. // divide and just did the last ('units') unit
  4318. if (exponent==0 && !(op&DIVIDE)) break;
  4319. // to get here, var1 is less than var2, so divide var2 by the per-
  4320. // Unit power of ten and go for the next digit
  4321. var2ulen--; // shift down
  4322. exponent-=DECDPUN; // update the exponent
  4323. } // outer loop
  4324. // ---- division is complete ---------------------------------------
  4325. // here: acc has at least reqdigits+1 of good results (or fewer
  4326. // if early stop), starting at accnext+1 (its lsu)
  4327. // var1 has any residue at the stopping point
  4328. // accunits is the number of digits collected in acc
  4329. if (accunits==0) { // acc is 0
  4330. accunits=1; // show have a unit ..
  4331. accdigits=1; // ..
  4332. *accnext=0; // .. whose value is 0
  4333. }
  4334. else accnext++; // back to last placed
  4335. // accnext now -> lowest unit of result
  4336. residue=0; // assume no residue
  4337. if (op&DIVIDE) {
  4338. // record the presence of any residue, for rounding
  4339. if (*var1!=0 || var1units>1) residue=1;
  4340. else { // no residue
  4341. // Had an exact division; clean up spurious trailing 0s.
  4342. // There will be at most DECDPUN-1, from the final multiply,
  4343. // and then only if the result is non-0 (and even) and the
  4344. // exponent is 'loose'.
  4345. #if DECDPUN>1
  4346. Unit lsu=*accnext;
  4347. if (!(lsu&0x01) && (lsu!=0)) {
  4348. // count the trailing zeros
  4349. Int drop=0;
  4350. for (;; drop++) { // [will terminate because lsu!=0]
  4351. if (exponent>=maxexponent) break; // don't chop real 0s
  4352. #if DECDPUN<=4
  4353. if ((lsu-QUOT10(lsu, drop+1)
  4354. *powers[drop+1])!=0) break; // found non-0 digit
  4355. #else
  4356. if (lsu%powers[drop+1]!=0) break; // found non-0 digit
  4357. #endif
  4358. exponent++;
  4359. }
  4360. if (drop>0) {
  4361. accunits=decShiftToLeast(accnext, accunits, drop);
  4362. accdigits=decGetDigits(accnext, accunits);
  4363. accunits=D2U(accdigits);
  4364. // [exponent was adjusted in the loop]
  4365. }
  4366. } // neither odd nor 0
  4367. #endif
  4368. } // exact divide
  4369. } // divide
  4370. else /* op!=DIVIDE */ {
  4371. // check for coefficient overflow
  4372. if (accdigits+exponent>reqdigits) {
  4373. *status|=DEC_Division_impossible;
  4374. break;
  4375. }
  4376. if (op & (REMAINDER|REMNEAR)) {
  4377. // [Here, the exponent will be 0, because var1 was adjusted
  4378. // appropriately.]
  4379. Int postshift; // work
  4380. Flag wasodd=0; // integer was odd
  4381. Unit *quotlsu; // for save
  4382. Int quotdigits; // ..
  4383. bits=lhs->bits; // remainder sign is always as lhs
  4384. // Fastpath when residue is truly 0 is worthwhile [and
  4385. // simplifies the code below]
  4386. if (*var1==0 && var1units==1) { // residue is 0
  4387. Int exp=lhs->exponent; // save min(exponents)
  4388. if (rhs->exponent<exp) exp=rhs->exponent;
  4389. decNumberZero(res); // 0 coefficient
  4390. #if DECSUBSET
  4391. if (set->extended)
  4392. #endif
  4393. res->exponent=exp; // .. with proper exponent
  4394. res->bits=(uByte)(bits&DECNEG); // [cleaned]
  4395. decFinish(res, set, &residue, status); // might clamp
  4396. break;
  4397. }
  4398. // note if the quotient was odd
  4399. if (*accnext & 0x01) wasodd=1; // acc is odd
  4400. quotlsu=accnext; // save in case need to reinspect
  4401. quotdigits=accdigits; // ..
  4402. // treat the residue, in var1, as the value to return, via acc
  4403. // calculate the unused zero digits. This is the smaller of:
  4404. // var1 initial padding (saved above)
  4405. // var2 residual padding, which happens to be given by:
  4406. postshift=var1initpad+exponent-lhs->exponent+rhs->exponent;
  4407. // [the 'exponent' term accounts for the shifts during divide]
  4408. if (var1initpad<postshift) postshift=var1initpad;
  4409. // shift var1 the requested amount, and adjust its digits
  4410. var1units=decShiftToLeast(var1, var1units, postshift);
  4411. accnext=var1;
  4412. accdigits=decGetDigits(var1, var1units);
  4413. accunits=D2U(accdigits);
  4414. exponent=lhs->exponent; // exponent is smaller of lhs & rhs
  4415. if (rhs->exponent<exponent) exponent=rhs->exponent;
  4416. // Now correct the result if doing remainderNear; if it
  4417. // (looking just at coefficients) is > rhs/2, or == rhs/2 and
  4418. // the integer was odd then the result should be rem-rhs.
  4419. if (op&REMNEAR) {
  4420. Int compare, tarunits; // work
  4421. Unit *up; // ..
  4422. // calculate remainder*2 into the var1 buffer (which has
  4423. // 'headroom' of an extra unit and hence enough space)
  4424. // [a dedicated 'double' loop would be faster, here]
  4425. tarunits=decUnitAddSub(accnext, accunits, accnext, accunits,
  4426. 0, accnext, 1);
  4427. // decDumpAr('r', accnext, tarunits);
  4428. // Here, accnext (var1) holds tarunits Units with twice the
  4429. // remainder's coefficient, which must now be compared to the
  4430. // RHS. The remainder's exponent may be smaller than the RHS's.
  4431. compare=decUnitCompare(accnext, tarunits, rhs->lsu, D2U(rhs->digits),
  4432. rhs->exponent-exponent);
  4433. if (compare==BADINT) { // deep trouble
  4434. *status|=DEC_Insufficient_storage;
  4435. break;}
  4436. // now restore the remainder by dividing by two; the lsu
  4437. // is known to be even.
  4438. for (up=accnext; up<accnext+tarunits; up++) {
  4439. Int half; // half to add to lower unit
  4440. half=*up & 0x01;
  4441. *up/=2; // [shift]
  4442. if (!half) continue;
  4443. *(up-1)+=(DECDPUNMAX+1)/2;
  4444. }
  4445. // [accunits still describes the original remainder length]
  4446. if (compare>0 || (compare==0 && wasodd)) { // adjustment needed
  4447. Int exp, expunits, exprem; // work
  4448. // This is effectively causing round-up of the quotient,
  4449. // so if it was the rare case where it was full and all
  4450. // nines, it would overflow and hence division-impossible
  4451. // should be raised
  4452. Flag allnines=0; // 1 if quotient all nines
  4453. if (quotdigits==reqdigits) { // could be borderline
  4454. for (up=quotlsu; ; up++) {
  4455. if (quotdigits>DECDPUN) {
  4456. if (*up!=DECDPUNMAX) break;// non-nines
  4457. }
  4458. else { // this is the last Unit
  4459. if (*up==powers[quotdigits]-1) allnines=1;
  4460. break;
  4461. }
  4462. quotdigits-=DECDPUN; // checked those digits
  4463. } // up
  4464. } // borderline check
  4465. if (allnines) {
  4466. *status|=DEC_Division_impossible;
  4467. break;}
  4468. // rem-rhs is needed; the sign will invert. Again, var1
  4469. // can safely be used for the working Units array.
  4470. exp=rhs->exponent-exponent; // RHS padding needed
  4471. // Calculate units and remainder from exponent.
  4472. expunits=exp/DECDPUN;
  4473. exprem=exp%DECDPUN;
  4474. // subtract [A+B*(-m)]; the result will always be negative
  4475. accunits=-decUnitAddSub(accnext, accunits,
  4476. rhs->lsu, D2U(rhs->digits),
  4477. expunits, accnext, -(Int)powers[exprem]);
  4478. accdigits=decGetDigits(accnext, accunits); // count digits exactly
  4479. accunits=D2U(accdigits); // and recalculate the units for copy
  4480. // [exponent is as for original remainder]
  4481. bits^=DECNEG; // flip the sign
  4482. }
  4483. } // REMNEAR
  4484. } // REMAINDER or REMNEAR
  4485. } // not DIVIDE
  4486. // Set exponent and bits
  4487. res->exponent=exponent;
  4488. res->bits=(uByte)(bits&DECNEG); // [cleaned]
  4489. // Now the coefficient.
  4490. decSetCoeff(res, set, accnext, accdigits, &residue, status);
  4491. decFinish(res, set, &residue, status); // final cleanup
  4492. #if DECSUBSET
  4493. // If a divide then strip trailing zeros if subset [after round]
  4494. if (!set->extended && (op==DIVIDE)) decTrim(res, set, 0, 1, &dropped);
  4495. #endif
  4496. } while(0); // end protected
  4497. if (varalloc!=NULL) free(varalloc); // drop any storage used
  4498. if (allocacc!=NULL) free(allocacc); // ..
  4499. #if DECSUBSET
  4500. if (allocrhs!=NULL) free(allocrhs); // ..
  4501. if (alloclhs!=NULL) free(alloclhs); // ..
  4502. #endif
  4503. return res;
  4504. } // decDivideOp
  4505. /* ------------------------------------------------------------------ */
  4506. /* decMultiplyOp -- multiplication operation */
  4507. /* */
  4508. /* This routine performs the multiplication C=A x B. */
  4509. /* */
  4510. /* res is C, the result. C may be A and/or B (e.g., X=X*X) */
  4511. /* lhs is A */
  4512. /* rhs is B */
  4513. /* set is the context */
  4514. /* status is the usual accumulator */
  4515. /* */
  4516. /* C must have space for set->digits digits. */
  4517. /* */
  4518. /* ------------------------------------------------------------------ */
  4519. /* 'Classic' multiplication is used rather than Karatsuba, as the */
  4520. /* latter would give only a minor improvement for the short numbers */
  4521. /* expected to be handled most (and uses much more memory). */
  4522. /* */
  4523. /* There are two major paths here: the general-purpose ('old code') */
  4524. /* path which handles all DECDPUN values, and a fastpath version */
  4525. /* which is used if 64-bit ints are available, DECDPUN<=4, and more */
  4526. /* than two calls to decUnitAddSub would be made. */
  4527. /* */
  4528. /* The fastpath version lumps units together into 8-digit or 9-digit */
  4529. /* chunks, and also uses a lazy carry strategy to minimise expensive */
  4530. /* 64-bit divisions. The chunks are then broken apart again into */
  4531. /* units for continuing processing. Despite this overhead, the */
  4532. /* fastpath can speed up some 16-digit operations by 10x (and much */
  4533. /* more for higher-precision calculations). */
  4534. /* */
  4535. /* A buffer always has to be used for the accumulator; in the */
  4536. /* fastpath, buffers are also always needed for the chunked copies of */
  4537. /* of the operand coefficients. */
  4538. /* Static buffers are larger than needed just for multiply, to allow */
  4539. /* for calls from other operations (notably exp). */
  4540. /* ------------------------------------------------------------------ */
  4541. #define FASTMUL (DECUSE64 && DECDPUN<5)
  4542. static decNumber * decMultiplyOp(decNumber *res, const decNumber *lhs,
  4543. const decNumber *rhs, decContext *set,
  4544. uInt *status) {
  4545. Int accunits; // Units of accumulator in use
  4546. Int exponent; // work
  4547. Int residue=0; // rounding residue
  4548. uByte bits; // result sign
  4549. Unit *acc; // -> accumulator Unit array
  4550. Int needbytes; // size calculator
  4551. void *allocacc=NULL; // -> allocated accumulator, iff allocated
  4552. Unit accbuff[SD2U(DECBUFFER*4+1)]; // buffer (+1 for DECBUFFER==0,
  4553. // *4 for calls from other operations)
  4554. const Unit *mer, *mermsup; // work
  4555. Int madlength; // Units in multiplicand
  4556. Int shift; // Units to shift multiplicand by
  4557. #if FASTMUL
  4558. // if DECDPUN is 1 or 3 work in base 10**9, otherwise
  4559. // (DECDPUN is 2 or 4) then work in base 10**8
  4560. #if DECDPUN & 1 // odd
  4561. #define FASTBASE 1000000000 // base
  4562. #define FASTDIGS 9 // digits in base
  4563. #define FASTLAZY 18 // carry resolution point [1->18]
  4564. #else
  4565. #define FASTBASE 100000000
  4566. #define FASTDIGS 8
  4567. #define FASTLAZY 1844 // carry resolution point [1->1844]
  4568. #endif
  4569. // three buffers are used, two for chunked copies of the operands
  4570. // (base 10**8 or base 10**9) and one base 2**64 accumulator with
  4571. // lazy carry evaluation
  4572. uInt zlhibuff[(DECBUFFER*2+1)/8+1]; // buffer (+1 for DECBUFFER==0)
  4573. uInt *zlhi=zlhibuff; // -> lhs array
  4574. uInt *alloclhi=NULL; // -> allocated buffer, iff allocated
  4575. uInt zrhibuff[(DECBUFFER*2+1)/8+1]; // buffer (+1 for DECBUFFER==0)
  4576. uInt *zrhi=zrhibuff; // -> rhs array
  4577. uInt *allocrhi=NULL; // -> allocated buffer, iff allocated
  4578. uLong zaccbuff[(DECBUFFER*2+1)/4+2]; // buffer (+1 for DECBUFFER==0)
  4579. // [allocacc is shared for both paths, as only one will run]
  4580. uLong *zacc=zaccbuff; // -> accumulator array for exact result
  4581. #if DECDPUN==1
  4582. Int zoff; // accumulator offset
  4583. #endif
  4584. uInt *lip, *rip; // item pointers
  4585. uInt *lmsi, *rmsi; // most significant items
  4586. Int ilhs, irhs, iacc; // item counts in the arrays
  4587. Int lazy; // lazy carry counter
  4588. uLong lcarry; // uLong carry
  4589. uInt carry; // carry (NB not uLong)
  4590. Int count; // work
  4591. const Unit *cup; // ..
  4592. Unit *up; // ..
  4593. uLong *lp; // ..
  4594. Int p; // ..
  4595. #endif
  4596. #if DECSUBSET
  4597. decNumber *alloclhs=NULL; // -> allocated buffer, iff allocated
  4598. decNumber *allocrhs=NULL; // -> allocated buffer, iff allocated
  4599. #endif
  4600. #if DECCHECK
  4601. if (decCheckOperands(res, lhs, rhs, set)) return res;
  4602. #endif
  4603. // precalculate result sign
  4604. bits=(uByte)((lhs->bits^rhs->bits)&DECNEG);
  4605. // handle infinities and NaNs
  4606. if (SPECIALARGS) { // a special bit set
  4607. if (SPECIALARGS & (DECSNAN | DECNAN)) { // one or two NaNs
  4608. decNaNs(res, lhs, rhs, set, status);
  4609. return res;}
  4610. // one or two infinities; Infinity * 0 is invalid
  4611. if (((lhs->bits & DECINF)==0 && ISZERO(lhs))
  4612. ||((rhs->bits & DECINF)==0 && ISZERO(rhs))) {
  4613. *status|=DEC_Invalid_operation;
  4614. return res;}
  4615. decNumberZero(res);
  4616. res->bits=bits|DECINF; // infinity
  4617. return res;}
  4618. // For best speed, as in DMSRCN [the original Rexx numerics
  4619. // module], use the shorter number as the multiplier (rhs) and
  4620. // the longer as the multiplicand (lhs) to minimise the number of
  4621. // adds (partial products)
  4622. if (lhs->digits<rhs->digits) { // swap...
  4623. const decNumber *hold=lhs;
  4624. lhs=rhs;
  4625. rhs=hold;
  4626. }
  4627. do { // protect allocated storage
  4628. #if DECSUBSET
  4629. if (!set->extended) {
  4630. // reduce operands and set lostDigits status, as needed
  4631. if (lhs->digits>set->digits) {
  4632. alloclhs=decRoundOperand(lhs, set, status);
  4633. if (alloclhs==NULL) break;
  4634. lhs=alloclhs;
  4635. }
  4636. if (rhs->digits>set->digits) {
  4637. allocrhs=decRoundOperand(rhs, set, status);
  4638. if (allocrhs==NULL) break;
  4639. rhs=allocrhs;
  4640. }
  4641. }
  4642. #endif
  4643. // [following code does not require input rounding]
  4644. #if FASTMUL // fastpath can be used
  4645. // use the fast path if there are enough digits in the shorter
  4646. // operand to make the setup and takedown worthwhile
  4647. #define NEEDTWO (DECDPUN*2) // within two decUnitAddSub calls
  4648. if (rhs->digits>NEEDTWO) { // use fastpath...
  4649. // calculate the number of elements in each array
  4650. ilhs=(lhs->digits+FASTDIGS-1)/FASTDIGS; // [ceiling]
  4651. irhs=(rhs->digits+FASTDIGS-1)/FASTDIGS; // ..
  4652. iacc=ilhs+irhs;
  4653. // allocate buffers if required, as usual
  4654. needbytes=ilhs*sizeof(uInt);
  4655. if (needbytes>(Int)sizeof(zlhibuff)) {
  4656. alloclhi=(uInt *)malloc(needbytes);
  4657. zlhi=alloclhi;}
  4658. needbytes=irhs*sizeof(uInt);
  4659. if (needbytes>(Int)sizeof(zrhibuff)) {
  4660. allocrhi=(uInt *)malloc(needbytes);
  4661. zrhi=allocrhi;}
  4662. // Allocating the accumulator space needs a special case when
  4663. // DECDPUN=1 because when converting the accumulator to Units
  4664. // after the multiplication each 8-byte item becomes 9 1-byte
  4665. // units. Therefore iacc extra bytes are needed at the front
  4666. // (rounded up to a multiple of 8 bytes), and the uLong
  4667. // accumulator starts offset the appropriate number of units
  4668. // to the right to avoid overwrite during the unchunking.
  4669. needbytes=iacc*sizeof(uLong);
  4670. #if DECDPUN==1
  4671. zoff=(iacc+7)/8; // items to offset by
  4672. needbytes+=zoff*8;
  4673. #endif
  4674. if (needbytes>(Int)sizeof(zaccbuff)) {
  4675. allocacc=(uLong *)malloc(needbytes);
  4676. zacc=(uLong *)allocacc;}
  4677. if (zlhi==NULL||zrhi==NULL||zacc==NULL) {
  4678. *status|=DEC_Insufficient_storage;
  4679. break;}
  4680. acc=(Unit *)zacc; // -> target Unit array
  4681. #if DECDPUN==1
  4682. zacc+=zoff; // start uLong accumulator to right
  4683. #endif
  4684. // assemble the chunked copies of the left and right sides
  4685. for (count=lhs->digits, cup=lhs->lsu, lip=zlhi; count>0; lip++)
  4686. for (p=0, *lip=0; p<FASTDIGS && count>0;
  4687. p+=DECDPUN, cup++, count-=DECDPUN)
  4688. *lip+=*cup*powers[p];
  4689. lmsi=lip-1; // save -> msi
  4690. for (count=rhs->digits, cup=rhs->lsu, rip=zrhi; count>0; rip++)
  4691. for (p=0, *rip=0; p<FASTDIGS && count>0;
  4692. p+=DECDPUN, cup++, count-=DECDPUN)
  4693. *rip+=*cup*powers[p];
  4694. rmsi=rip-1; // save -> msi
  4695. // zero the accumulator
  4696. for (lp=zacc; lp<zacc+iacc; lp++) *lp=0;
  4697. /* Start the multiplication */
  4698. // Resolving carries can dominate the cost of accumulating the
  4699. // partial products, so this is only done when necessary.
  4700. // Each uLong item in the accumulator can hold values up to
  4701. // 2**64-1, and each partial product can be as large as
  4702. // (10**FASTDIGS-1)**2. When FASTDIGS=9, this can be added to
  4703. // itself 18.4 times in a uLong without overflowing, so during
  4704. // the main calculation resolution is carried out every 18th
  4705. // add -- every 162 digits. Similarly, when FASTDIGS=8, the
  4706. // partial products can be added to themselves 1844.6 times in
  4707. // a uLong without overflowing, so intermediate carry
  4708. // resolution occurs only every 14752 digits. Hence for common
  4709. // short numbers usually only the one final carry resolution
  4710. // occurs.
  4711. // (The count is set via FASTLAZY to simplify experiments to
  4712. // measure the value of this approach: a 35% improvement on a
  4713. // [34x34] multiply.)
  4714. lazy=FASTLAZY; // carry delay count
  4715. for (rip=zrhi; rip<=rmsi; rip++) { // over each item in rhs
  4716. lp=zacc+(rip-zrhi); // where to add the lhs
  4717. for (lip=zlhi; lip<=lmsi; lip++, lp++) { // over each item in lhs
  4718. *lp+=(uLong)(*lip)*(*rip); // [this should in-line]
  4719. } // lip loop
  4720. lazy--;
  4721. if (lazy>0 && rip!=rmsi) continue;
  4722. lazy=FASTLAZY; // reset delay count
  4723. // spin up the accumulator resolving overflows
  4724. for (lp=zacc; lp<zacc+iacc; lp++) {
  4725. if (*lp<FASTBASE) continue; // it fits
  4726. lcarry=*lp/FASTBASE; // top part [slow divide]
  4727. // lcarry can exceed 2**32-1, so check again; this check
  4728. // and occasional extra divide (slow) is well worth it, as
  4729. // it allows FASTLAZY to be increased to 18 rather than 4
  4730. // in the FASTDIGS=9 case
  4731. if (lcarry<FASTBASE) carry=(uInt)lcarry; // [usual]
  4732. else { // two-place carry [fairly rare]
  4733. uInt carry2=(uInt)(lcarry/FASTBASE); // top top part
  4734. *(lp+2)+=carry2; // add to item+2
  4735. *lp-=((uLong)FASTBASE*FASTBASE*carry2); // [slow]
  4736. carry=(uInt)(lcarry-((uLong)FASTBASE*carry2)); // [inline]
  4737. }
  4738. *(lp+1)+=carry; // add to item above [inline]
  4739. *lp-=((uLong)FASTBASE*carry); // [inline]
  4740. } // carry resolution
  4741. } // rip loop
  4742. // The multiplication is complete; time to convert back into
  4743. // units. This can be done in-place in the accumulator and in
  4744. // 32-bit operations, because carries were resolved after the
  4745. // final add. This needs N-1 divides and multiplies for
  4746. // each item in the accumulator (which will become up to N
  4747. // units, where 2<=N<=9).
  4748. for (lp=zacc, up=acc; lp<zacc+iacc; lp++) {
  4749. uInt item=(uInt)*lp; // decapitate to uInt
  4750. for (p=0; p<FASTDIGS-DECDPUN; p+=DECDPUN, up++) {
  4751. uInt part=item/(DECDPUNMAX+1);
  4752. *up=(Unit)(item-(part*(DECDPUNMAX+1)));
  4753. item=part;
  4754. } // p
  4755. *up=(Unit)item; up++; // [final needs no division]
  4756. } // lp
  4757. accunits=up-acc; // count of units
  4758. }
  4759. else { // here to use units directly, without chunking ['old code']
  4760. #endif
  4761. // if accumulator will be too long for local storage, then allocate
  4762. acc=accbuff; // -> assume buffer for accumulator
  4763. needbytes=(D2U(lhs->digits)+D2U(rhs->digits))*sizeof(Unit);
  4764. if (needbytes>(Int)sizeof(accbuff)) {
  4765. allocacc=(Unit *)malloc(needbytes);
  4766. if (allocacc==NULL) {*status|=DEC_Insufficient_storage; break;}
  4767. acc=(Unit *)allocacc; // use the allocated space
  4768. }
  4769. /* Now the main long multiplication loop */
  4770. // Unlike the equivalent in the IBM Java implementation, there
  4771. // is no advantage in calculating from msu to lsu. So, do it
  4772. // by the book, as it were.
  4773. // Each iteration calculates ACC=ACC+MULTAND*MULT
  4774. accunits=1; // accumulator starts at '0'
  4775. *acc=0; // .. (lsu=0)
  4776. shift=0; // no multiplicand shift at first
  4777. madlength=D2U(lhs->digits); // this won't change
  4778. mermsup=rhs->lsu+D2U(rhs->digits); // -> msu+1 of multiplier
  4779. for (mer=rhs->lsu; mer<mermsup; mer++) {
  4780. // Here, *mer is the next Unit in the multiplier to use
  4781. // If non-zero [optimization] add it...
  4782. if (*mer!=0) accunits=decUnitAddSub(&acc[shift], accunits-shift,
  4783. lhs->lsu, madlength, 0,
  4784. &acc[shift], *mer)
  4785. + shift;
  4786. else { // extend acc with a 0; it will be used shortly
  4787. *(acc+accunits)=0; // [this avoids length of <=0 later]
  4788. accunits++;
  4789. }
  4790. // multiply multiplicand by 10**DECDPUN for next Unit to left
  4791. shift++; // add this for 'logical length'
  4792. } // n
  4793. #if FASTMUL
  4794. } // unchunked units
  4795. #endif
  4796. // common end-path
  4797. #if DECTRACE
  4798. decDumpAr('*', acc, accunits); // Show exact result
  4799. #endif
  4800. // acc now contains the exact result of the multiplication,
  4801. // possibly with a leading zero unit; build the decNumber from
  4802. // it, noting if any residue
  4803. res->bits=bits; // set sign
  4804. res->digits=decGetDigits(acc, accunits); // count digits exactly
  4805. // There can be a 31-bit wrap in calculating the exponent.
  4806. // This can only happen if both input exponents are negative and
  4807. // both their magnitudes are large. If there was a wrap, set a
  4808. // safe very negative exponent, from which decFinalize() will
  4809. // raise a hard underflow shortly.
  4810. exponent=lhs->exponent+rhs->exponent; // calculate exponent
  4811. if (lhs->exponent<0 && rhs->exponent<0 && exponent>0)
  4812. exponent=-2*DECNUMMAXE; // force underflow
  4813. res->exponent=exponent; // OK to overwrite now
  4814. // Set the coefficient. If any rounding, residue records
  4815. decSetCoeff(res, set, acc, res->digits, &residue, status);
  4816. decFinish(res, set, &residue, status); // final cleanup
  4817. } while(0); // end protected
  4818. if (allocacc!=NULL) free(allocacc); // drop any storage used
  4819. #if DECSUBSET
  4820. if (allocrhs!=NULL) free(allocrhs); // ..
  4821. if (alloclhs!=NULL) free(alloclhs); // ..
  4822. #endif
  4823. #if FASTMUL
  4824. if (allocrhi!=NULL) free(allocrhi); // ..
  4825. if (alloclhi!=NULL) free(alloclhi); // ..
  4826. #endif
  4827. return res;
  4828. } // decMultiplyOp
  4829. /* ------------------------------------------------------------------ */
  4830. /* decExpOp -- effect exponentiation */
  4831. /* */
  4832. /* This computes C = exp(A) */
  4833. /* */
  4834. /* res is C, the result. C may be A */
  4835. /* rhs is A */
  4836. /* set is the context; note that rounding mode has no effect */
  4837. /* */
  4838. /* C must have space for set->digits digits. status is updated but */
  4839. /* not set. */
  4840. /* */
  4841. /* Restrictions: */
  4842. /* */
  4843. /* digits, emax, and -emin in the context must be less than */
  4844. /* 2*DEC_MAX_MATH (1999998), and the rhs must be within these */
  4845. /* bounds or a zero. This is an internal routine, so these */
  4846. /* restrictions are contractual and not enforced. */
  4847. /* */
  4848. /* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will */
  4849. /* almost always be correctly rounded, but may be up to 1 ulp in */
  4850. /* error in rare cases. */
  4851. /* */
  4852. /* Finite results will always be full precision and Inexact, except */
  4853. /* when A is a zero or -Infinity (giving 1 or 0 respectively). */
  4854. /* ------------------------------------------------------------------ */
  4855. /* This approach used here is similar to the algorithm described in */
  4856. /* */
  4857. /* Variable Precision Exponential Function, T. E. Hull and */
  4858. /* A. Abrham, ACM Transactions on Mathematical Software, Vol 12 #2, */
  4859. /* pp79-91, ACM, June 1986. */
  4860. /* */
  4861. /* with the main difference being that the iterations in the series */
  4862. /* evaluation are terminated dynamically (which does not require the */
  4863. /* extra variable-precision variables which are expensive in this */
  4864. /* context). */
  4865. /* */
  4866. /* The error analysis in Hull & Abrham's paper applies except for the */
  4867. /* round-off error accumulation during the series evaluation. This */
  4868. /* code does not precalculate the number of iterations and so cannot */
  4869. /* use Horner's scheme. Instead, the accumulation is done at double- */
  4870. /* precision, which ensures that the additions of the terms are exact */
  4871. /* and do not accumulate round-off (and any round-off errors in the */
  4872. /* terms themselves move 'to the right' faster than they can */
  4873. /* accumulate). This code also extends the calculation by allowing, */
  4874. /* in the spirit of other decNumber operators, the input to be more */
  4875. /* precise than the result (the precision used is based on the more */
  4876. /* precise of the input or requested result). */
  4877. /* */
  4878. /* Implementation notes: */
  4879. /* */
  4880. /* 1. This is separated out as decExpOp so it can be called from */
  4881. /* other Mathematical functions (notably Ln) with a wider range */
  4882. /* than normal. In particular, it can handle the slightly wider */
  4883. /* (double) range needed by Ln (which has to be able to calculate */
  4884. /* exp(-x) where x can be the tiniest number (Ntiny). */
  4885. /* */
  4886. /* 2. Normalizing x to be <=0.1 (instead of <=1) reduces loop */
  4887. /* iterations by appoximately a third with additional (although */
  4888. /* diminishing) returns as the range is reduced to even smaller */
  4889. /* fractions. However, h (the power of 10 used to correct the */
  4890. /* result at the end, see below) must be kept <=8 as otherwise */
  4891. /* the final result cannot be computed. Hence the leverage is a */
  4892. /* sliding value (8-h), where potentially the range is reduced */
  4893. /* more for smaller values. */
  4894. /* */
  4895. /* The leverage that can be applied in this way is severely */
  4896. /* limited by the cost of the raise-to-the power at the end, */
  4897. /* which dominates when the number of iterations is small (less */
  4898. /* than ten) or when rhs is short. As an example, the adjustment */
  4899. /* x**10,000,000 needs 31 multiplications, all but one full-width. */
  4900. /* */
  4901. /* 3. The restrictions (especially precision) could be raised with */
  4902. /* care, but the full decNumber range seems very hard within the */
  4903. /* 32-bit limits. */
  4904. /* */
  4905. /* 4. The working precisions for the static buffers are twice the */
  4906. /* obvious size to allow for calls from decNumberPower. */
  4907. /* ------------------------------------------------------------------ */
  4908. decNumber * decExpOp(decNumber *res, const decNumber *rhs,
  4909. decContext *set, uInt *status) {
  4910. uInt ignore=0; // working status
  4911. Int h; // adjusted exponent for 0.xxxx
  4912. Int p; // working precision
  4913. Int residue; // rounding residue
  4914. uInt needbytes; // for space calculations
  4915. const decNumber *x=rhs; // (may point to safe copy later)
  4916. decContext aset, tset, dset; // working contexts
  4917. Int comp; // work
  4918. // the argument is often copied to normalize it, so (unusually) it
  4919. // is treated like other buffers, using DECBUFFER, +1 in case
  4920. // DECBUFFER is 0
  4921. decNumber bufr[D2N(DECBUFFER*2+1)];
  4922. decNumber *allocrhs=NULL; // non-NULL if rhs buffer allocated
  4923. // the working precision will be no more than set->digits+8+1
  4924. // so for on-stack buffers DECBUFFER+9 is used, +1 in case DECBUFFER
  4925. // is 0 (and twice that for the accumulator)
  4926. // buffer for t, term (working precision plus)
  4927. decNumber buft[D2N(DECBUFFER*2+9+1)];
  4928. decNumber *allocbuft=NULL; // -> allocated buft, iff allocated
  4929. decNumber *t=buft; // term
  4930. // buffer for a, accumulator (working precision * 2), at least 9
  4931. decNumber bufa[D2N(DECBUFFER*4+18+1)];
  4932. decNumber *allocbufa=NULL; // -> allocated bufa, iff allocated
  4933. decNumber *a=bufa; // accumulator
  4934. // decNumber for the divisor term; this needs at most 9 digits
  4935. // and so can be fixed size [16 so can use standard context]
  4936. decNumber bufd[D2N(16)];
  4937. decNumber *d=bufd; // divisor
  4938. decNumber numone; // constant 1
  4939. #if DECCHECK
  4940. Int iterations=0; // for later sanity check
  4941. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  4942. #endif
  4943. do { // protect allocated storage
  4944. if (SPECIALARG) { // handle infinities and NaNs
  4945. if (decNumberIsInfinite(rhs)) { // an infinity
  4946. if (decNumberIsNegative(rhs)) // -Infinity -> +0
  4947. decNumberZero(res);
  4948. else decNumberCopy(res, rhs); // +Infinity -> self
  4949. }
  4950. else decNaNs(res, rhs, NULL, set, status); // a NaN
  4951. break;}
  4952. if (ISZERO(rhs)) { // zeros -> exact 1
  4953. decNumberZero(res); // make clean 1
  4954. *res->lsu=1; // ..
  4955. break;} // [no status to set]
  4956. // e**x when 0 < x < 0.66 is < 1+3x/2, hence can fast-path
  4957. // positive and negative tiny cases which will result in inexact
  4958. // 1. This also allows the later add-accumulate to always be
  4959. // exact (because its length will never be more than twice the
  4960. // working precision).
  4961. // The comparator (tiny) needs just one digit, so use the
  4962. // decNumber d for it (reused as the divisor, etc., below); its
  4963. // exponent is such that if x is positive it will have
  4964. // set->digits-1 zeros between the decimal point and the digit,
  4965. // which is 4, and if x is negative one more zero there as the
  4966. // more precise result will be of the form 0.9999999 rather than
  4967. // 1.0000001. Hence, tiny will be 0.0000004 if digits=7 and x>0
  4968. // or 0.00000004 if digits=7 and x<0. If RHS not larger than
  4969. // this then the result will be 1.000000
  4970. decNumberZero(d); // clean
  4971. *d->lsu=4; // set 4 ..
  4972. d->exponent=-set->digits; // * 10**(-d)
  4973. if (decNumberIsNegative(rhs)) d->exponent--; // negative case
  4974. comp=decCompare(d, rhs, 1); // signless compare
  4975. if (comp==BADINT) {
  4976. *status|=DEC_Insufficient_storage;
  4977. break;}
  4978. if (comp>=0) { // rhs < d
  4979. Int shift=set->digits-1;
  4980. decNumberZero(res); // set 1
  4981. *res->lsu=1; // ..
  4982. res->digits=decShiftToMost(res->lsu, 1, shift);
  4983. res->exponent=-shift; // make 1.0000...
  4984. *status|=DEC_Inexact | DEC_Rounded; // .. inexactly
  4985. break;} // tiny
  4986. // set up the context to be used for calculating a, as this is
  4987. // used on both paths below
  4988. decContextDefault(&aset, DEC_INIT_DECIMAL64);
  4989. // accumulator bounds are as requested (could underflow)
  4990. aset.emax=set->emax; // usual bounds
  4991. aset.emin=set->emin; // ..
  4992. aset.clamp=0; // and no concrete format
  4993. // calculate the adjusted (Hull & Abrham) exponent (where the
  4994. // decimal point is just to the left of the coefficient msd)
  4995. h=rhs->exponent+rhs->digits;
  4996. // if h>8 then 10**h cannot be calculated safely; however, when
  4997. // h=8 then exp(|rhs|) will be at least exp(1E+7) which is at
  4998. // least 6.59E+4342944, so (due to the restriction on Emax/Emin)
  4999. // overflow (or underflow to 0) is guaranteed -- so this case can
  5000. // be handled by simply forcing the appropriate excess
  5001. if (h>8) { // overflow/underflow
  5002. // set up here so Power call below will over or underflow to
  5003. // zero; set accumulator to either 2 or 0.02
  5004. // [stack buffer for a is always big enough for this]
  5005. decNumberZero(a);
  5006. *a->lsu=2; // not 1 but < exp(1)
  5007. if (decNumberIsNegative(rhs)) a->exponent=-2; // make 0.02
  5008. h=8; // clamp so 10**h computable
  5009. p=9; // set a working precision
  5010. }
  5011. else { // h<=8
  5012. Int maxlever=(rhs->digits>8?1:0);
  5013. // [could/should increase this for precisions >40 or so, too]
  5014. // if h is 8, cannot normalize to a lower upper limit because
  5015. // the final result will not be computable (see notes above),
  5016. // but leverage can be applied whenever h is less than 8.
  5017. // Apply as much as possible, up to a MAXLEVER digits, which
  5018. // sets the tradeoff against the cost of the later a**(10**h).
  5019. // As h is increased, the working precision below also
  5020. // increases to compensate for the "constant digits at the
  5021. // front" effect.
  5022. Int lever=MINI(8-h, maxlever); // leverage attainable
  5023. Int use=-rhs->digits-lever; // exponent to use for RHS
  5024. h+=lever; // apply leverage selected
  5025. if (h<0) { // clamp
  5026. use+=h; // [may end up subnormal]
  5027. h=0;
  5028. }
  5029. // Take a copy of RHS if it needs normalization (true whenever x>=1)
  5030. if (rhs->exponent!=use) {
  5031. decNumber *newrhs=bufr; // assume will fit on stack
  5032. needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
  5033. if (needbytes>sizeof(bufr)) { // need malloc space
  5034. allocrhs=(decNumber *)malloc(needbytes);
  5035. if (allocrhs==NULL) { // hopeless -- abandon
  5036. *status|=DEC_Insufficient_storage;
  5037. break;}
  5038. newrhs=allocrhs; // use the allocated space
  5039. }
  5040. decNumberCopy(newrhs, rhs); // copy to safe space
  5041. newrhs->exponent=use; // normalize; now <1
  5042. x=newrhs; // ready for use
  5043. // decNumberShow(x);
  5044. }
  5045. // Now use the usual power series to evaluate exp(x). The
  5046. // series starts as 1 + x + x^2/2 ... so prime ready for the
  5047. // third term by setting the term variable t=x, the accumulator
  5048. // a=1, and the divisor d=2.
  5049. // First determine the working precision. From Hull & Abrham
  5050. // this is set->digits+h+2. However, if x is 'over-precise' we
  5051. // need to allow for all its digits to potentially participate
  5052. // (consider an x where all the excess digits are 9s) so in
  5053. // this case use x->digits+h+2
  5054. p=MAXI(x->digits, set->digits)+h+2; // [h<=8]
  5055. // a and t are variable precision, and depend on p, so space
  5056. // must be allocated for them if necessary
  5057. // the accumulator needs to be able to hold 2p digits so that
  5058. // the additions on the second and subsequent iterations are
  5059. // sufficiently exact.
  5060. needbytes=sizeof(decNumber)+(D2U(p*2)-1)*sizeof(Unit);
  5061. if (needbytes>sizeof(bufa)) { // need malloc space
  5062. allocbufa=(decNumber *)malloc(needbytes);
  5063. if (allocbufa==NULL) { // hopeless -- abandon
  5064. *status|=DEC_Insufficient_storage;
  5065. break;}
  5066. a=allocbufa; // use the allocated space
  5067. }
  5068. // the term needs to be able to hold p digits (which is
  5069. // guaranteed to be larger than x->digits, so the initial copy
  5070. // is safe); it may also be used for the raise-to-power
  5071. // calculation below, which needs an extra two digits
  5072. needbytes=sizeof(decNumber)+(D2U(p+2)-1)*sizeof(Unit);
  5073. if (needbytes>sizeof(buft)) { // need malloc space
  5074. allocbuft=(decNumber *)malloc(needbytes);
  5075. if (allocbuft==NULL) { // hopeless -- abandon
  5076. *status|=DEC_Insufficient_storage;
  5077. break;}
  5078. t=allocbuft; // use the allocated space
  5079. }
  5080. decNumberCopy(t, x); // term=x
  5081. decNumberZero(a); *a->lsu=1; // accumulator=1
  5082. decNumberZero(d); *d->lsu=2; // divisor=2
  5083. decNumberZero(&numone); *numone.lsu=1; // constant 1 for increment
  5084. // set up the contexts for calculating a, t, and d
  5085. decContextDefault(&tset, DEC_INIT_DECIMAL64);
  5086. dset=tset;
  5087. // accumulator bounds are set above, set precision now
  5088. aset.digits=p*2; // double
  5089. // term bounds avoid any underflow or overflow
  5090. tset.digits=p;
  5091. tset.emin=DEC_MIN_EMIN; // [emax is plenty]
  5092. // [dset.digits=16, etc., are sufficient]
  5093. // finally ready to roll
  5094. for (;;) {
  5095. #if DECCHECK
  5096. iterations++;
  5097. #endif
  5098. // only the status from the accumulation is interesting
  5099. // [but it should remain unchanged after first add]
  5100. decAddOp(a, a, t, &aset, 0, status); // a=a+t
  5101. decMultiplyOp(t, t, x, &tset, &ignore); // t=t*x
  5102. decDivideOp(t, t, d, &tset, DIVIDE, &ignore); // t=t/d
  5103. // the iteration ends when the term cannot affect the result,
  5104. // if rounded to p digits, which is when its value is smaller
  5105. // than the accumulator by p+1 digits. There must also be
  5106. // full precision in a.
  5107. if (((a->digits+a->exponent)>=(t->digits+t->exponent+p+1))
  5108. && (a->digits>=p)) break;
  5109. decAddOp(d, d, &numone, &dset, 0, &ignore); // d=d+1
  5110. } // iterate
  5111. #if DECCHECK
  5112. // just a sanity check; comment out test to show always
  5113. if (iterations>p+3)
  5114. printf("Exp iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
  5115. (LI)iterations, (LI)*status, (LI)p, (LI)x->digits);
  5116. #endif
  5117. } // h<=8
  5118. // apply postconditioning: a=a**(10**h) -- this is calculated
  5119. // at a slightly higher precision than Hull & Abrham suggest
  5120. if (h>0) {
  5121. Int seenbit=0; // set once a 1-bit is seen
  5122. Int i; // counter
  5123. Int n=powers[h]; // always positive
  5124. aset.digits=p+2; // sufficient precision
  5125. // avoid the overhead and many extra digits of decNumberPower
  5126. // as all that is needed is the short 'multipliers' loop; here
  5127. // accumulate the answer into t
  5128. decNumberZero(t); *t->lsu=1; // acc=1
  5129. for (i=1;;i++){ // for each bit [top bit ignored]
  5130. // abandon if have had overflow or terminal underflow
  5131. if (*status & (DEC_Overflow|DEC_Underflow)) { // interesting?
  5132. if (*status&DEC_Overflow || ISZERO(t)) break;}
  5133. n=n<<1; // move next bit to testable position
  5134. if (n<0) { // top bit is set
  5135. seenbit=1; // OK, have a significant bit
  5136. decMultiplyOp(t, t, a, &aset, status); // acc=acc*x
  5137. }
  5138. if (i==31) break; // that was the last bit
  5139. if (!seenbit) continue; // no need to square 1
  5140. decMultiplyOp(t, t, t, &aset, status); // acc=acc*acc [square]
  5141. } /*i*/ // 32 bits
  5142. // decNumberShow(t);
  5143. a=t; // and carry on using t instead of a
  5144. }
  5145. // Copy and round the result to res
  5146. residue=1; // indicate dirt to right ..
  5147. if (ISZERO(a)) residue=0; // .. unless underflowed to 0
  5148. aset.digits=set->digits; // [use default rounding]
  5149. decCopyFit(res, a, &aset, &residue, status); // copy & shorten
  5150. decFinish(res, set, &residue, status); // cleanup/set flags
  5151. } while(0); // end protected
  5152. if (allocrhs !=NULL) free(allocrhs); // drop any storage used
  5153. if (allocbufa!=NULL) free(allocbufa); // ..
  5154. if (allocbuft!=NULL) free(allocbuft); // ..
  5155. // [status is handled by caller]
  5156. return res;
  5157. } // decExpOp
  5158. /* ------------------------------------------------------------------ */
  5159. /* Initial-estimate natural logarithm table */
  5160. /* */
  5161. /* LNnn -- 90-entry 16-bit table for values from .10 through .99. */
  5162. /* The result is a 4-digit encode of the coefficient (c=the */
  5163. /* top 14 bits encoding 0-9999) and a 2-digit encode of the */
  5164. /* exponent (e=the bottom 2 bits encoding 0-3) */
  5165. /* */
  5166. /* The resulting value is given by: */
  5167. /* */
  5168. /* v = -c * 10**(-e-3) */
  5169. /* */
  5170. /* where e and c are extracted from entry k = LNnn[x-10] */
  5171. /* where x is truncated (NB) into the range 10 through 99, */
  5172. /* and then c = k>>2 and e = k&3. */
  5173. /* ------------------------------------------------------------------ */
  5174. const uShort LNnn[90]={9016, 8652, 8316, 8008, 7724, 7456, 7208,
  5175. 6972, 6748, 6540, 6340, 6148, 5968, 5792, 5628, 5464, 5312,
  5176. 5164, 5020, 4884, 4748, 4620, 4496, 4376, 4256, 4144, 4032,
  5177. 39233, 38181, 37157, 36157, 35181, 34229, 33297, 32389, 31501, 30629,
  5178. 29777, 28945, 28129, 27329, 26545, 25777, 25021, 24281, 23553, 22837,
  5179. 22137, 21445, 20769, 20101, 19445, 18801, 18165, 17541, 16925, 16321,
  5180. 15721, 15133, 14553, 13985, 13421, 12865, 12317, 11777, 11241, 10717,
  5181. 10197, 9685, 9177, 8677, 8185, 7697, 7213, 6737, 6269, 5801,
  5182. 5341, 4889, 4437, 39930, 35534, 31186, 26886, 22630, 18418, 14254,
  5183. 10130, 6046, 20055};
  5184. /* ------------------------------------------------------------------ */
  5185. /* decLnOp -- effect natural logarithm */
  5186. /* */
  5187. /* This computes C = ln(A) */
  5188. /* */
  5189. /* res is C, the result. C may be A */
  5190. /* rhs is A */
  5191. /* set is the context; note that rounding mode has no effect */
  5192. /* */
  5193. /* C must have space for set->digits digits. */
  5194. /* */
  5195. /* Notable cases: */
  5196. /* A<0 -> Invalid */
  5197. /* A=0 -> -Infinity (Exact) */
  5198. /* A=+Infinity -> +Infinity (Exact) */
  5199. /* A=1 exactly -> 0 (Exact) */
  5200. /* */
  5201. /* Restrictions (as for Exp): */
  5202. /* */
  5203. /* digits, emax, and -emin in the context must be less than */
  5204. /* DEC_MAX_MATH+11 (1000010), and the rhs must be within these */
  5205. /* bounds or a zero. This is an internal routine, so these */
  5206. /* restrictions are contractual and not enforced. */
  5207. /* */
  5208. /* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will */
  5209. /* almost always be correctly rounded, but may be up to 1 ulp in */
  5210. /* error in rare cases. */
  5211. /* ------------------------------------------------------------------ */
  5212. /* The result is calculated using Newton's method, with each */
  5213. /* iteration calculating a' = a + x * exp(-a) - 1. See, for example, */
  5214. /* Epperson 1989. */
  5215. /* */
  5216. /* The iteration ends when the adjustment x*exp(-a)-1 is tiny enough. */
  5217. /* This has to be calculated at the sum of the precision of x and the */
  5218. /* working precision. */
  5219. /* */
  5220. /* Implementation notes: */
  5221. /* */
  5222. /* 1. This is separated out as decLnOp so it can be called from */
  5223. /* other Mathematical functions (e.g., Log 10) with a wider range */
  5224. /* than normal. In particular, it can handle the slightly wider */
  5225. /* (+9+2) range needed by a power function. */
  5226. /* */
  5227. /* 2. The speed of this function is about 10x slower than exp, as */
  5228. /* it typically needs 4-6 iterations for short numbers, and the */
  5229. /* extra precision needed adds a squaring effect, twice. */
  5230. /* */
  5231. /* 3. Fastpaths are included for ln(10) and ln(2), up to length 40, */
  5232. /* as these are common requests. ln(10) is used by log10(x). */
  5233. /* */
  5234. /* 4. An iteration might be saved by widening the LNnn table, and */
  5235. /* would certainly save at least one if it were made ten times */
  5236. /* bigger, too (for truncated fractions 0.100 through 0.999). */
  5237. /* However, for most practical evaluations, at least four or five */
  5238. /* iterations will be neede -- so this would only speed up by */
  5239. /* 20-25% and that probably does not justify increasing the table */
  5240. /* size. */
  5241. /* */
  5242. /* 5. The static buffers are larger than might be expected to allow */
  5243. /* for calls from decNumberPower. */
  5244. /* ------------------------------------------------------------------ */
  5245. decNumber * decLnOp(decNumber *res, const decNumber *rhs,
  5246. decContext *set, uInt *status) {
  5247. uInt ignore=0; // working status accumulator
  5248. uInt needbytes; // for space calculations
  5249. Int residue; // rounding residue
  5250. Int r; // rhs=f*10**r [see below]
  5251. Int p; // working precision
  5252. Int pp; // precision for iteration
  5253. Int t; // work
  5254. // buffers for a (accumulator, typically precision+2) and b
  5255. // (adjustment calculator, same size)
  5256. decNumber bufa[D2N(DECBUFFER+12)];
  5257. decNumber *allocbufa=NULL; // -> allocated bufa, iff allocated
  5258. decNumber *a=bufa; // accumulator/work
  5259. decNumber bufb[D2N(DECBUFFER*2+2)];
  5260. decNumber *allocbufb=NULL; // -> allocated bufa, iff allocated
  5261. decNumber *b=bufb; // adjustment/work
  5262. decNumber numone; // constant 1
  5263. decNumber cmp; // work
  5264. decContext aset, bset; // working contexts
  5265. #if DECCHECK
  5266. Int iterations=0; // for later sanity check
  5267. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  5268. #endif
  5269. do { // protect allocated storage
  5270. if (SPECIALARG) { // handle infinities and NaNs
  5271. if (decNumberIsInfinite(rhs)) { // an infinity
  5272. if (decNumberIsNegative(rhs)) // -Infinity -> error
  5273. *status|=DEC_Invalid_operation;
  5274. else decNumberCopy(res, rhs); // +Infinity -> self
  5275. }
  5276. else decNaNs(res, rhs, NULL, set, status); // a NaN
  5277. break;}
  5278. if (ISZERO(rhs)) { // +/- zeros -> -Infinity
  5279. decNumberZero(res); // make clean
  5280. res->bits=DECINF|DECNEG; // set - infinity
  5281. break;} // [no status to set]
  5282. // Non-zero negatives are bad...
  5283. if (decNumberIsNegative(rhs)) { // -x -> error
  5284. *status|=DEC_Invalid_operation;
  5285. break;}
  5286. // Here, rhs is positive, finite, and in range
  5287. // lookaside fastpath code for ln(2) and ln(10) at common lengths
  5288. if (rhs->exponent==0 && set->digits<=40) {
  5289. #if DECDPUN==1
  5290. if (rhs->lsu[0]==0 && rhs->lsu[1]==1 && rhs->digits==2) { // ln(10)
  5291. #else
  5292. if (rhs->lsu[0]==10 && rhs->digits==2) { // ln(10)
  5293. #endif
  5294. aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
  5295. #define LN10 "2.302585092994045684017991454684364207601"
  5296. decNumberFromString(res, LN10, &aset);
  5297. *status|=(DEC_Inexact | DEC_Rounded); // is inexact
  5298. break;}
  5299. if (rhs->lsu[0]==2 && rhs->digits==1) { // ln(2)
  5300. aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
  5301. #define LN2 "0.6931471805599453094172321214581765680755"
  5302. decNumberFromString(res, LN2, &aset);
  5303. *status|=(DEC_Inexact | DEC_Rounded);
  5304. break;}
  5305. } // integer and short
  5306. // Determine the working precision. This is normally the
  5307. // requested precision + 2, with a minimum of 9. However, if
  5308. // the rhs is 'over-precise' then allow for all its digits to
  5309. // potentially participate (consider an rhs where all the excess
  5310. // digits are 9s) so in this case use rhs->digits+2.
  5311. p=MAXI(rhs->digits, MAXI(set->digits, 7))+2;
  5312. // Allocate space for the accumulator and the high-precision
  5313. // adjustment calculator, if necessary. The accumulator must
  5314. // be able to hold p digits, and the adjustment up to
  5315. // rhs->digits+p digits. They are also made big enough for 16
  5316. // digits so that they can be used for calculating the initial
  5317. // estimate.
  5318. needbytes=sizeof(decNumber)+(D2U(MAXI(p,16))-1)*sizeof(Unit);
  5319. if (needbytes>sizeof(bufa)) { // need malloc space
  5320. allocbufa=(decNumber *)malloc(needbytes);
  5321. if (allocbufa==NULL) { // hopeless -- abandon
  5322. *status|=DEC_Insufficient_storage;
  5323. break;}
  5324. a=allocbufa; // use the allocated space
  5325. }
  5326. pp=p+rhs->digits;
  5327. needbytes=sizeof(decNumber)+(D2U(MAXI(pp,16))-1)*sizeof(Unit);
  5328. if (needbytes>sizeof(bufb)) { // need malloc space
  5329. allocbufb=(decNumber *)malloc(needbytes);
  5330. if (allocbufb==NULL) { // hopeless -- abandon
  5331. *status|=DEC_Insufficient_storage;
  5332. break;}
  5333. b=allocbufb; // use the allocated space
  5334. }
  5335. // Prepare an initial estimate in acc. Calculate this by
  5336. // considering the coefficient of x to be a normalized fraction,
  5337. // f, with the decimal point at far left and multiplied by
  5338. // 10**r. Then, rhs=f*10**r and 0.1<=f<1, and
  5339. // ln(x) = ln(f) + ln(10)*r
  5340. // Get the initial estimate for ln(f) from a small lookup
  5341. // table (see above) indexed by the first two digits of f,
  5342. // truncated.
  5343. decContextDefault(&aset, DEC_INIT_DECIMAL64); // 16-digit extended
  5344. r=rhs->exponent+rhs->digits; // 'normalised' exponent
  5345. decNumberFromInt32(a, r); // a=r
  5346. decNumberFromInt32(b, 2302585); // b=ln(10) (2.302585)
  5347. b->exponent=-6; // ..
  5348. decMultiplyOp(a, a, b, &aset, &ignore); // a=a*b
  5349. // now get top two digits of rhs into b by simple truncate and
  5350. // force to integer
  5351. residue=0; // (no residue)
  5352. aset.digits=2; aset.round=DEC_ROUND_DOWN;
  5353. decCopyFit(b, rhs, &aset, &residue, &ignore); // copy & shorten
  5354. b->exponent=0; // make integer
  5355. t=decGetInt(b); // [cannot fail]
  5356. if (t<10) t=X10(t); // adjust single-digit b
  5357. t=LNnn[t-10]; // look up ln(b)
  5358. decNumberFromInt32(b, t>>2); // b=ln(b) coefficient
  5359. b->exponent=-(t&3)-3; // set exponent
  5360. b->bits=DECNEG; // ln(0.10)->ln(0.99) always -ve
  5361. aset.digits=16; aset.round=DEC_ROUND_HALF_EVEN; // restore
  5362. decAddOp(a, a, b, &aset, 0, &ignore); // acc=a+b
  5363. // the initial estimate is now in a, with up to 4 digits correct.
  5364. // When rhs is at or near Nmax the estimate will be low, so we
  5365. // will approach it from below, avoiding overflow when calling exp.
  5366. decNumberZero(&numone); *numone.lsu=1; // constant 1 for adjustment
  5367. // accumulator bounds are as requested (could underflow, but
  5368. // cannot overflow)
  5369. aset.emax=set->emax;
  5370. aset.emin=set->emin;
  5371. aset.clamp=0; // no concrete format
  5372. // set up a context to be used for the multiply and subtract
  5373. bset=aset;
  5374. bset.emax=DEC_MAX_MATH*2; // use double bounds for the
  5375. bset.emin=-DEC_MAX_MATH*2; // adjustment calculation
  5376. // [see decExpOp call below]
  5377. // for each iteration double the number of digits to calculate,
  5378. // up to a maximum of p
  5379. pp=9; // initial precision
  5380. // [initially 9 as then the sequence starts 7+2, 16+2, and
  5381. // 34+2, which is ideal for standard-sized numbers]
  5382. aset.digits=pp; // working context
  5383. bset.digits=pp+rhs->digits; // wider context
  5384. for (;;) { // iterate
  5385. #if DECCHECK
  5386. iterations++;
  5387. if (iterations>24) break; // consider 9 * 2**24
  5388. #endif
  5389. // calculate the adjustment (exp(-a)*x-1) into b. This is a
  5390. // catastrophic subtraction but it really is the difference
  5391. // from 1 that is of interest.
  5392. // Use the internal entry point to Exp as it allows the double
  5393. // range for calculating exp(-a) when a is the tiniest subnormal.
  5394. a->bits^=DECNEG; // make -a
  5395. decExpOp(b, a, &bset, &ignore); // b=exp(-a)
  5396. a->bits^=DECNEG; // restore sign of a
  5397. // now multiply by rhs and subtract 1, at the wider precision
  5398. decMultiplyOp(b, b, rhs, &bset, &ignore); // b=b*rhs
  5399. decAddOp(b, b, &numone, &bset, DECNEG, &ignore); // b=b-1
  5400. // the iteration ends when the adjustment cannot affect the
  5401. // result by >=0.5 ulp (at the requested digits), which
  5402. // is when its value is smaller than the accumulator by
  5403. // set->digits+1 digits (or it is zero) -- this is a looser
  5404. // requirement than for Exp because all that happens to the
  5405. // accumulator after this is the final rounding (but note that
  5406. // there must also be full precision in a, or a=0).
  5407. if (decNumberIsZero(b) ||
  5408. (a->digits+a->exponent)>=(b->digits+b->exponent+set->digits+1)) {
  5409. if (a->digits==p) break;
  5410. if (decNumberIsZero(a)) {
  5411. decCompareOp(&cmp, rhs, &numone, &aset, COMPARE, &ignore); // rhs=1 ?
  5412. if (cmp.lsu[0]==0) a->exponent=0; // yes, exact 0
  5413. else *status|=(DEC_Inexact | DEC_Rounded); // no, inexact
  5414. break;
  5415. }
  5416. // force padding if adjustment has gone to 0 before full length
  5417. if (decNumberIsZero(b)) b->exponent=a->exponent-p;
  5418. }
  5419. // not done yet ...
  5420. decAddOp(a, a, b, &aset, 0, &ignore); // a=a+b for next estimate
  5421. if (pp==p) continue; // precision is at maximum
  5422. // lengthen the next calculation
  5423. pp=pp*2; // double precision
  5424. if (pp>p) pp=p; // clamp to maximum
  5425. aset.digits=pp; // working context
  5426. bset.digits=pp+rhs->digits; // wider context
  5427. } // Newton's iteration
  5428. #if DECCHECK
  5429. // just a sanity check; remove the test to show always
  5430. if (iterations>24)
  5431. printf("Ln iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
  5432. (LI)iterations, (LI)*status, (LI)p, (LI)rhs->digits);
  5433. #endif
  5434. // Copy and round the result to res
  5435. residue=1; // indicate dirt to right
  5436. if (ISZERO(a)) residue=0; // .. unless underflowed to 0
  5437. aset.digits=set->digits; // [use default rounding]
  5438. decCopyFit(res, a, &aset, &residue, status); // copy & shorten
  5439. decFinish(res, set, &residue, status); // cleanup/set flags
  5440. } while(0); // end protected
  5441. if (allocbufa!=NULL) free(allocbufa); // drop any storage used
  5442. if (allocbufb!=NULL) free(allocbufb); // ..
  5443. // [status is handled by caller]
  5444. return res;
  5445. } // decLnOp
  5446. /* ------------------------------------------------------------------ */
  5447. /* decQuantizeOp -- force exponent to requested value */
  5448. /* */
  5449. /* This computes C = op(A, B), where op adjusts the coefficient */
  5450. /* of C (by rounding or shifting) such that the exponent (-scale) */
  5451. /* of C has the value B or matches the exponent of B. */
  5452. /* The numerical value of C will equal A, except for the effects of */
  5453. /* any rounding that occurred. */
  5454. /* */
  5455. /* res is C, the result. C may be A or B */
  5456. /* lhs is A, the number to adjust */
  5457. /* rhs is B, the requested exponent */
  5458. /* set is the context */
  5459. /* quant is 1 for quantize or 0 for rescale */
  5460. /* status is the status accumulator (this can be called without */
  5461. /* risk of control loss) */
  5462. /* */
  5463. /* C must have space for set->digits digits. */
  5464. /* */
  5465. /* Unless there is an error or the result is infinite, the exponent */
  5466. /* after the operation is guaranteed to be that requested. */
  5467. /* ------------------------------------------------------------------ */
  5468. static decNumber * decQuantizeOp(decNumber *res, const decNumber *lhs,
  5469. const decNumber *rhs, decContext *set,
  5470. Flag quant, uInt *status) {
  5471. #if DECSUBSET
  5472. decNumber *alloclhs=NULL; // non-NULL if rounded lhs allocated
  5473. decNumber *allocrhs=NULL; // .., rhs
  5474. #endif
  5475. const decNumber *inrhs=rhs; // save original rhs
  5476. Int reqdigits=set->digits; // requested DIGITS
  5477. Int reqexp; // requested exponent [-scale]
  5478. Int residue=0; // rounding residue
  5479. Int etiny=set->emin-(reqdigits-1);
  5480. #if DECCHECK
  5481. if (decCheckOperands(res, lhs, rhs, set)) return res;
  5482. #endif
  5483. do { // protect allocated storage
  5484. #if DECSUBSET
  5485. if (!set->extended) {
  5486. // reduce operands and set lostDigits status, as needed
  5487. if (lhs->digits>reqdigits) {
  5488. alloclhs=decRoundOperand(lhs, set, status);
  5489. if (alloclhs==NULL) break;
  5490. lhs=alloclhs;
  5491. }
  5492. if (rhs->digits>reqdigits) { // [this only checks lostDigits]
  5493. allocrhs=decRoundOperand(rhs, set, status);
  5494. if (allocrhs==NULL) break;
  5495. rhs=allocrhs;
  5496. }
  5497. }
  5498. #endif
  5499. // [following code does not require input rounding]
  5500. // Handle special values
  5501. if (SPECIALARGS) {
  5502. // NaNs get usual processing
  5503. if (SPECIALARGS & (DECSNAN | DECNAN))
  5504. decNaNs(res, lhs, rhs, set, status);
  5505. // one infinity but not both is bad
  5506. else if ((lhs->bits ^ rhs->bits) & DECINF)
  5507. *status|=DEC_Invalid_operation;
  5508. // both infinity: return lhs
  5509. else decNumberCopy(res, lhs); // [nop if in place]
  5510. break;
  5511. }
  5512. // set requested exponent
  5513. if (quant) reqexp=inrhs->exponent; // quantize -- match exponents
  5514. else { // rescale -- use value of rhs
  5515. // Original rhs must be an integer that fits and is in range,
  5516. // which could be from -1999999997 to +999999999, thanks to
  5517. // subnormals
  5518. reqexp=decGetInt(inrhs); // [cannot fail]
  5519. }
  5520. #if DECSUBSET
  5521. if (!set->extended) etiny=set->emin; // no subnormals
  5522. #endif
  5523. if (reqexp==BADINT // bad (rescale only) or ..
  5524. || reqexp==BIGODD || reqexp==BIGEVEN // very big (ditto) or ..
  5525. || (reqexp<etiny) // < lowest
  5526. || (reqexp>set->emax)) { // > emax
  5527. *status|=DEC_Invalid_operation;
  5528. break;}
  5529. // the RHS has been processed, so it can be overwritten now if necessary
  5530. if (ISZERO(lhs)) { // zero coefficient unchanged
  5531. decNumberCopy(res, lhs); // [nop if in place]
  5532. res->exponent=reqexp; // .. just set exponent
  5533. #if DECSUBSET
  5534. if (!set->extended) res->bits=0; // subset specification; no -0
  5535. #endif
  5536. }
  5537. else { // non-zero lhs
  5538. Int adjust=reqexp-lhs->exponent; // digit adjustment needed
  5539. // if adjusted coefficient will definitely not fit, give up now
  5540. if ((lhs->digits-adjust)>reqdigits) {
  5541. *status|=DEC_Invalid_operation;
  5542. break;
  5543. }
  5544. if (adjust>0) { // increasing exponent
  5545. // this will decrease the length of the coefficient by adjust
  5546. // digits, and must round as it does so
  5547. decContext workset; // work
  5548. workset=*set; // clone rounding, etc.
  5549. workset.digits=lhs->digits-adjust; // set requested length
  5550. // [note that the latter can be <1, here]
  5551. decCopyFit(res, lhs, &workset, &residue, status); // fit to result
  5552. decApplyRound(res, &workset, residue, status); // .. and round
  5553. residue=0; // [used]
  5554. // If just rounded a 999s case, exponent will be off by one;
  5555. // adjust back (after checking space), if so.
  5556. if (res->exponent>reqexp) {
  5557. // re-check needed, e.g., for quantize(0.9999, 0.001) under
  5558. // set->digits==3
  5559. if (res->digits==reqdigits) { // cannot shift by 1
  5560. *status&=~(DEC_Inexact | DEC_Rounded); // [clean these]
  5561. *status|=DEC_Invalid_operation;
  5562. break;
  5563. }
  5564. res->digits=decShiftToMost(res->lsu, res->digits, 1); // shift
  5565. res->exponent--; // (re)adjust the exponent.
  5566. }
  5567. #if DECSUBSET
  5568. if (ISZERO(res) && !set->extended) res->bits=0; // subset; no -0
  5569. #endif
  5570. } // increase
  5571. else /* adjust<=0 */ { // decreasing or = exponent
  5572. // this will increase the length of the coefficient by -adjust
  5573. // digits, by adding zero or more trailing zeros; this is
  5574. // already checked for fit, above
  5575. decNumberCopy(res, lhs); // [it will fit]
  5576. // if padding needed (adjust<0), add it now...
  5577. if (adjust<0) {
  5578. res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
  5579. res->exponent+=adjust; // adjust the exponent
  5580. }
  5581. } // decrease
  5582. } // non-zero
  5583. // Check for overflow [do not use Finalize in this case, as an
  5584. // overflow here is a "don't fit" situation]
  5585. if (res->exponent>set->emax-res->digits+1) { // too big
  5586. *status|=DEC_Invalid_operation;
  5587. break;
  5588. }
  5589. else {
  5590. decFinalize(res, set, &residue, status); // set subnormal flags
  5591. *status&=~DEC_Underflow; // suppress Underflow [as per 754]
  5592. }
  5593. } while(0); // end protected
  5594. #if DECSUBSET
  5595. if (allocrhs!=NULL) free(allocrhs); // drop any storage used
  5596. if (alloclhs!=NULL) free(alloclhs); // ..
  5597. #endif
  5598. return res;
  5599. } // decQuantizeOp
  5600. /* ------------------------------------------------------------------ */
  5601. /* decCompareOp -- compare, min, or max two Numbers */
  5602. /* */
  5603. /* This computes C = A ? B and carries out one of four operations: */
  5604. /* COMPARE -- returns the signum (as a number) giving the */
  5605. /* result of a comparison unless one or both */
  5606. /* operands is a NaN (in which case a NaN results) */
  5607. /* COMPSIG -- as COMPARE except that a quiet NaN raises */
  5608. /* Invalid operation. */
  5609. /* COMPMAX -- returns the larger of the operands, using the */
  5610. /* 754 maxnum operation */
  5611. /* COMPMAXMAG -- ditto, comparing absolute values */
  5612. /* COMPMIN -- the 754 minnum operation */
  5613. /* COMPMINMAG -- ditto, comparing absolute values */
  5614. /* COMTOTAL -- returns the signum (as a number) giving the */
  5615. /* result of a comparison using 754 total ordering */
  5616. /* */
  5617. /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
  5618. /* lhs is A */
  5619. /* rhs is B */
  5620. /* set is the context */
  5621. /* op is the operation flag */
  5622. /* status is the usual accumulator */
  5623. /* */
  5624. /* C must have space for one digit for COMPARE or set->digits for */
  5625. /* COMPMAX, COMPMIN, COMPMAXMAG, or COMPMINMAG. */
  5626. /* ------------------------------------------------------------------ */
  5627. /* The emphasis here is on speed for common cases, and avoiding */
  5628. /* coefficient comparison if possible. */
  5629. /* ------------------------------------------------------------------ */
  5630. decNumber * decCompareOp(decNumber *res, const decNumber *lhs,
  5631. const decNumber *rhs, decContext *set,
  5632. Flag op, uInt *status) {
  5633. #if DECSUBSET
  5634. decNumber *alloclhs=NULL; // non-NULL if rounded lhs allocated
  5635. decNumber *allocrhs=NULL; // .., rhs
  5636. #endif
  5637. Int result=0; // default result value
  5638. uByte merged; // work
  5639. #if DECCHECK
  5640. if (decCheckOperands(res, lhs, rhs, set)) return res;
  5641. #endif
  5642. do { // protect allocated storage
  5643. #if DECSUBSET
  5644. if (!set->extended) {
  5645. // reduce operands and set lostDigits status, as needed
  5646. if (lhs->digits>set->digits) {
  5647. alloclhs=decRoundOperand(lhs, set, status);
  5648. if (alloclhs==NULL) {result=BADINT; break;}
  5649. lhs=alloclhs;
  5650. }
  5651. if (rhs->digits>set->digits) {
  5652. allocrhs=decRoundOperand(rhs, set, status);
  5653. if (allocrhs==NULL) {result=BADINT; break;}
  5654. rhs=allocrhs;
  5655. }
  5656. }
  5657. #endif
  5658. // [following code does not require input rounding]
  5659. // If total ordering then handle differing signs 'up front'
  5660. if (op==COMPTOTAL) { // total ordering
  5661. if (decNumberIsNegative(lhs) & !decNumberIsNegative(rhs)) {
  5662. result=-1;
  5663. break;
  5664. }
  5665. if (!decNumberIsNegative(lhs) & decNumberIsNegative(rhs)) {
  5666. result=+1;
  5667. break;
  5668. }
  5669. }
  5670. // handle NaNs specially; let infinities drop through
  5671. // This assumes sNaN (even just one) leads to NaN.
  5672. merged=(lhs->bits | rhs->bits) & (DECSNAN | DECNAN);
  5673. if (merged) { // a NaN bit set
  5674. if (op==COMPARE); // result will be NaN
  5675. else if (op==COMPSIG) // treat qNaN as sNaN
  5676. *status|=DEC_Invalid_operation | DEC_sNaN;
  5677. else if (op==COMPTOTAL) { // total ordering, always finite
  5678. // signs are known to be the same; compute the ordering here
  5679. // as if the signs are both positive, then invert for negatives
  5680. if (!decNumberIsNaN(lhs)) result=-1;
  5681. else if (!decNumberIsNaN(rhs)) result=+1;
  5682. // here if both NaNs
  5683. else if (decNumberIsSNaN(lhs) && decNumberIsQNaN(rhs)) result=-1;
  5684. else if (decNumberIsQNaN(lhs) && decNumberIsSNaN(rhs)) result=+1;
  5685. else { // both NaN or both sNaN
  5686. // now it just depends on the payload
  5687. result=decUnitCompare(lhs->lsu, D2U(lhs->digits),
  5688. rhs->lsu, D2U(rhs->digits), 0);
  5689. // [Error not possible, as these are 'aligned']
  5690. } // both same NaNs
  5691. if (decNumberIsNegative(lhs)) result=-result;
  5692. break;
  5693. } // total order
  5694. else if (merged & DECSNAN); // sNaN -> qNaN
  5695. else { // here if MIN or MAX and one or two quiet NaNs
  5696. // min or max -- 754 rules ignore single NaN
  5697. if (!decNumberIsNaN(lhs) || !decNumberIsNaN(rhs)) {
  5698. // just one NaN; force choice to be the non-NaN operand
  5699. op=COMPMAX;
  5700. if (lhs->bits & DECNAN) result=-1; // pick rhs
  5701. else result=+1; // pick lhs
  5702. break;
  5703. }
  5704. } // max or min
  5705. op=COMPNAN; // use special path
  5706. decNaNs(res, lhs, rhs, set, status); // propagate NaN
  5707. break;
  5708. }
  5709. // have numbers
  5710. if (op==COMPMAXMAG || op==COMPMINMAG) result=decCompare(lhs, rhs, 1);
  5711. else result=decCompare(lhs, rhs, 0); // sign matters
  5712. } while(0); // end protected
  5713. if (result==BADINT) *status|=DEC_Insufficient_storage; // rare
  5714. else {
  5715. if (op==COMPARE || op==COMPSIG ||op==COMPTOTAL) { // returning signum
  5716. if (op==COMPTOTAL && result==0) {
  5717. // operands are numerically equal or same NaN (and same sign,
  5718. // tested first); if identical, leave result 0
  5719. if (lhs->exponent!=rhs->exponent) {
  5720. if (lhs->exponent<rhs->exponent) result=-1;
  5721. else result=+1;
  5722. if (decNumberIsNegative(lhs)) result=-result;
  5723. } // lexp!=rexp
  5724. } // total-order by exponent
  5725. decNumberZero(res); // [always a valid result]
  5726. if (result!=0) { // must be -1 or +1
  5727. *res->lsu=1;
  5728. if (result<0) res->bits=DECNEG;
  5729. }
  5730. }
  5731. else if (op==COMPNAN); // special, drop through
  5732. else { // MAX or MIN, non-NaN result
  5733. Int residue=0; // rounding accumulator
  5734. // choose the operand for the result
  5735. const decNumber *choice;
  5736. if (result==0) { // operands are numerically equal
  5737. // choose according to sign then exponent (see 754)
  5738. uByte slhs=(lhs->bits & DECNEG);
  5739. uByte srhs=(rhs->bits & DECNEG);
  5740. #if DECSUBSET
  5741. if (!set->extended) { // subset: force left-hand
  5742. op=COMPMAX;
  5743. result=+1;
  5744. }
  5745. else
  5746. #endif
  5747. if (slhs!=srhs) { // signs differ
  5748. if (slhs) result=-1; // rhs is max
  5749. else result=+1; // lhs is max
  5750. }
  5751. else if (slhs && srhs) { // both negative
  5752. if (lhs->exponent<rhs->exponent) result=+1;
  5753. else result=-1;
  5754. // [if equal, use lhs, technically identical]
  5755. }
  5756. else { // both positive
  5757. if (lhs->exponent>rhs->exponent) result=+1;
  5758. else result=-1;
  5759. // [ditto]
  5760. }
  5761. } // numerically equal
  5762. // here result will be non-0; reverse if looking for MIN
  5763. if (op==COMPMIN || op==COMPMINMAG) result=-result;
  5764. choice=(result>0 ? lhs : rhs); // choose
  5765. // copy chosen to result, rounding if need be
  5766. decCopyFit(res, choice, set, &residue, status);
  5767. decFinish(res, set, &residue, status);
  5768. }
  5769. }
  5770. #if DECSUBSET
  5771. if (allocrhs!=NULL) free(allocrhs); // free any storage used
  5772. if (alloclhs!=NULL) free(alloclhs); // ..
  5773. #endif
  5774. return res;
  5775. } // decCompareOp
  5776. /* ------------------------------------------------------------------ */
  5777. /* decCompare -- compare two decNumbers by numerical value */
  5778. /* */
  5779. /* This routine compares A ? B without altering them. */
  5780. /* */
  5781. /* Arg1 is A, a decNumber which is not a NaN */
  5782. /* Arg2 is B, a decNumber which is not a NaN */
  5783. /* Arg3 is 1 for a sign-independent compare, 0 otherwise */
  5784. /* */
  5785. /* returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure */
  5786. /* (the only possible failure is an allocation error) */
  5787. /* ------------------------------------------------------------------ */
  5788. static Int decCompare(const decNumber *lhs, const decNumber *rhs,
  5789. Flag abs) {
  5790. Int result; // result value
  5791. Int sigr; // rhs signum
  5792. Int compare; // work
  5793. result=1; // assume signum(lhs)
  5794. if (ISZERO(lhs)) result=0;
  5795. if (abs) {
  5796. if (ISZERO(rhs)) return result; // LHS wins or both 0
  5797. // RHS is non-zero
  5798. if (result==0) return -1; // LHS is 0; RHS wins
  5799. // [here, both non-zero, result=1]
  5800. }
  5801. else { // signs matter
  5802. if (result && decNumberIsNegative(lhs)) result=-1;
  5803. sigr=1; // compute signum(rhs)
  5804. if (ISZERO(rhs)) sigr=0;
  5805. else if (decNumberIsNegative(rhs)) sigr=-1;
  5806. if (result > sigr) return +1; // L > R, return 1
  5807. if (result < sigr) return -1; // L < R, return -1
  5808. if (result==0) return 0; // both 0
  5809. }
  5810. // signums are the same; both are non-zero
  5811. if ((lhs->bits | rhs->bits) & DECINF) { // one or more infinities
  5812. if (decNumberIsInfinite(rhs)) {
  5813. if (decNumberIsInfinite(lhs)) result=0;// both infinite
  5814. else result=-result; // only rhs infinite
  5815. }
  5816. return result;
  5817. }
  5818. // must compare the coefficients, allowing for exponents
  5819. if (lhs->exponent>rhs->exponent) { // LHS exponent larger
  5820. // swap sides, and sign
  5821. const decNumber *temp=lhs;
  5822. lhs=rhs;
  5823. rhs=temp;
  5824. result=-result;
  5825. }
  5826. compare=decUnitCompare(lhs->lsu, D2U(lhs->digits),
  5827. rhs->lsu, D2U(rhs->digits),
  5828. rhs->exponent-lhs->exponent);
  5829. if (compare!=BADINT) compare*=result; // comparison succeeded
  5830. return compare;
  5831. } // decCompare
  5832. /* ------------------------------------------------------------------ */
  5833. /* decUnitCompare -- compare two >=0 integers in Unit arrays */
  5834. /* */
  5835. /* This routine compares A ? B*10**E where A and B are unit arrays */
  5836. /* A is a plain integer */
  5837. /* B has an exponent of E (which must be non-negative) */
  5838. /* */
  5839. /* Arg1 is A first Unit (lsu) */
  5840. /* Arg2 is A length in Units */
  5841. /* Arg3 is B first Unit (lsu) */
  5842. /* Arg4 is B length in Units */
  5843. /* Arg5 is E (0 if the units are aligned) */
  5844. /* */
  5845. /* returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure */
  5846. /* (the only possible failure is an allocation error, which can */
  5847. /* only occur if E!=0) */
  5848. /* ------------------------------------------------------------------ */
  5849. static Int decUnitCompare(const Unit *a, Int alength,
  5850. const Unit *b, Int blength, Int exp) {
  5851. Unit *acc; // accumulator for result
  5852. Unit accbuff[SD2U(DECBUFFER*2+1)]; // local buffer
  5853. Unit *allocacc=NULL; // -> allocated acc buffer, iff allocated
  5854. Int accunits, need; // units in use or needed for acc
  5855. const Unit *l, *r, *u; // work
  5856. Int expunits, exprem, result; // ..
  5857. if (exp==0) { // aligned; fastpath
  5858. if (alength>blength) return 1;
  5859. if (alength<blength) return -1;
  5860. // same number of units in both -- need unit-by-unit compare
  5861. l=a+alength-1;
  5862. r=b+alength-1;
  5863. for (;l>=a; l--, r--) {
  5864. if (*l>*r) return 1;
  5865. if (*l<*r) return -1;
  5866. }
  5867. return 0; // all units match
  5868. } // aligned
  5869. // Unaligned. If one is >1 unit longer than the other, padded
  5870. // approximately, then can return easily
  5871. if (alength>blength+(Int)D2U(exp)) return 1;
  5872. if (alength+1<blength+(Int)D2U(exp)) return -1;
  5873. // Need to do a real subtract. For this, a result buffer is needed
  5874. // even though only the sign is of interest. Its length needs
  5875. // to be the larger of alength and padded blength, +2
  5876. need=blength+D2U(exp); // maximum real length of B
  5877. if (need<alength) need=alength;
  5878. need+=2;
  5879. acc=accbuff; // assume use local buffer
  5880. if (need*sizeof(Unit)>sizeof(accbuff)) {
  5881. allocacc=(Unit *)malloc(need*sizeof(Unit));
  5882. if (allocacc==NULL) return BADINT; // hopeless -- abandon
  5883. acc=allocacc;
  5884. }
  5885. // Calculate units and remainder from exponent.
  5886. expunits=exp/DECDPUN;
  5887. exprem=exp%DECDPUN;
  5888. // subtract [A+B*(-m)]
  5889. accunits=decUnitAddSub(a, alength, b, blength, expunits, acc,
  5890. -(Int)powers[exprem]);
  5891. // [UnitAddSub result may have leading zeros, even on zero]
  5892. if (accunits<0) result=-1; // negative result
  5893. else { // non-negative result
  5894. // check units of the result before freeing any storage
  5895. for (u=acc; u<acc+accunits-1 && *u==0;) u++;
  5896. result=(*u==0 ? 0 : +1);
  5897. }
  5898. // clean up and return the result
  5899. if (allocacc!=NULL) free(allocacc); // drop any storage used
  5900. return result;
  5901. } // decUnitCompare
  5902. /* ------------------------------------------------------------------ */
  5903. /* decUnitAddSub -- add or subtract two >=0 integers in Unit arrays */
  5904. /* */
  5905. /* This routine performs the calculation: */
  5906. /* */
  5907. /* C=A+(B*M) */
  5908. /* */
  5909. /* Where M is in the range -DECDPUNMAX through +DECDPUNMAX. */
  5910. /* */
  5911. /* A may be shorter or longer than B. */
  5912. /* */
  5913. /* Leading zeros are not removed after a calculation. The result is */
  5914. /* either the same length as the longer of A and B (adding any */
  5915. /* shift), or one Unit longer than that (if a Unit carry occurred). */
  5916. /* */
  5917. /* A and B content are not altered unless C is also A or B. */
  5918. /* C may be the same array as A or B, but only if no zero padding is */
  5919. /* requested (that is, C may be B only if bshift==0). */
  5920. /* C is filled from the lsu; only those units necessary to complete */
  5921. /* the calculation are referenced. */
  5922. /* */
  5923. /* Arg1 is A first Unit (lsu) */
  5924. /* Arg2 is A length in Units */
  5925. /* Arg3 is B first Unit (lsu) */
  5926. /* Arg4 is B length in Units */
  5927. /* Arg5 is B shift in Units (>=0; pads with 0 units if positive) */
  5928. /* Arg6 is C first Unit (lsu) */
  5929. /* Arg7 is M, the multiplier */
  5930. /* */
  5931. /* returns the count of Units written to C, which will be non-zero */
  5932. /* and negated if the result is negative. That is, the sign of the */
  5933. /* returned Int is the sign of the result (positive for zero) and */
  5934. /* the absolute value of the Int is the count of Units. */
  5935. /* */
  5936. /* It is the caller's responsibility to make sure that C size is */
  5937. /* safe, allowing space if necessary for a one-Unit carry. */
  5938. /* */
  5939. /* This routine is severely performance-critical; *any* change here */
  5940. /* must be measured (timed) to assure no performance degradation. */
  5941. /* In particular, trickery here tends to be counter-productive, as */
  5942. /* increased complexity of code hurts register optimizations on */
  5943. /* register-poor architectures. Avoiding divisions is nearly */
  5944. /* always a Good Idea, however. */
  5945. /* */
  5946. /* Special thanks to Rick McGuire (IBM Cambridge, MA) and Dave Clark */
  5947. /* (IBM Warwick, UK) for some of the ideas used in this routine. */
  5948. /* ------------------------------------------------------------------ */
  5949. static Int decUnitAddSub(const Unit *a, Int alength,
  5950. const Unit *b, Int blength, Int bshift,
  5951. Unit *c, Int m) {
  5952. const Unit *alsu=a; // A lsu [need to remember it]
  5953. Unit *clsu=c; // C ditto
  5954. Unit *minC; // low water mark for C
  5955. Unit *maxC; // high water mark for C
  5956. eInt carry=0; // carry integer (could be Long)
  5957. Int add; // work
  5958. #if DECDPUN<=4 // myriadal, millenary, etc.
  5959. Int est; // estimated quotient
  5960. #endif
  5961. #if DECTRACE
  5962. if (alength<1 || blength<1)
  5963. printf("decUnitAddSub: alen blen m %ld %ld [%ld]\n", alength, blength, m);
  5964. #endif
  5965. maxC=c+alength; // A is usually the longer
  5966. minC=c+blength; // .. and B the shorter
  5967. if (bshift!=0) { // B is shifted; low As copy across
  5968. minC+=bshift;
  5969. // if in place [common], skip copy unless there's a gap [rare]
  5970. if (a==c && bshift<=alength) {
  5971. c+=bshift;
  5972. a+=bshift;
  5973. }
  5974. else for (; c<clsu+bshift; a++, c++) { // copy needed
  5975. if (a<alsu+alength) *c=*a;
  5976. else *c=0;
  5977. }
  5978. }
  5979. if (minC>maxC) { // swap
  5980. Unit *hold=minC;
  5981. minC=maxC;
  5982. maxC=hold;
  5983. }
  5984. // For speed, do the addition as two loops; the first where both A
  5985. // and B contribute, and the second (if necessary) where only one or
  5986. // other of the numbers contribute.
  5987. // Carry handling is the same (i.e., duplicated) in each case.
  5988. for (; c<minC; c++) {
  5989. carry+=*a;
  5990. a++;
  5991. carry+=((eInt)*b)*m; // [special-casing m=1/-1
  5992. b++; // here is not a win]
  5993. // here carry is new Unit of digits; it could be +ve or -ve
  5994. if ((ueInt)carry<=DECDPUNMAX) { // fastpath 0-DECDPUNMAX
  5995. *c=(Unit)carry;
  5996. carry=0;
  5997. continue;
  5998. }
  5999. #if DECDPUN==4 // use divide-by-multiply
  6000. if (carry>=0) {
  6001. est=(((ueInt)carry>>11)*53687)>>18;
  6002. *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
  6003. carry=est; // likely quotient [89%]
  6004. if (*c<DECDPUNMAX+1) continue; // estimate was correct
  6005. carry++;
  6006. *c-=DECDPUNMAX+1;
  6007. continue;
  6008. }
  6009. // negative case
  6010. carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
  6011. est=(((ueInt)carry>>11)*53687)>>18;
  6012. *c=(Unit)(carry-est*(DECDPUNMAX+1));
  6013. carry=est-(DECDPUNMAX+1); // correctly negative
  6014. if (*c<DECDPUNMAX+1) continue; // was OK
  6015. carry++;
  6016. *c-=DECDPUNMAX+1;
  6017. #elif DECDPUN==3
  6018. if (carry>=0) {
  6019. est=(((ueInt)carry>>3)*16777)>>21;
  6020. *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
  6021. carry=est; // likely quotient [99%]
  6022. if (*c<DECDPUNMAX+1) continue; // estimate was correct
  6023. carry++;
  6024. *c-=DECDPUNMAX+1;
  6025. continue;
  6026. }
  6027. // negative case
  6028. carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
  6029. est=(((ueInt)carry>>3)*16777)>>21;
  6030. *c=(Unit)(carry-est*(DECDPUNMAX+1));
  6031. carry=est-(DECDPUNMAX+1); // correctly negative
  6032. if (*c<DECDPUNMAX+1) continue; // was OK
  6033. carry++;
  6034. *c-=DECDPUNMAX+1;
  6035. #elif DECDPUN<=2
  6036. // Can use QUOT10 as carry <= 4 digits
  6037. if (carry>=0) {
  6038. est=QUOT10(carry, DECDPUN);
  6039. *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
  6040. carry=est; // quotient
  6041. continue;
  6042. }
  6043. // negative case
  6044. carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
  6045. est=QUOT10(carry, DECDPUN);
  6046. *c=(Unit)(carry-est*(DECDPUNMAX+1));
  6047. carry=est-(DECDPUNMAX+1); // correctly negative
  6048. #else
  6049. // remainder operator is undefined if negative, so must test
  6050. if ((ueInt)carry<(DECDPUNMAX+1)*2) { // fastpath carry +1
  6051. *c=(Unit)(carry-(DECDPUNMAX+1)); // [helps additions]
  6052. carry=1;
  6053. continue;
  6054. }
  6055. if (carry>=0) {
  6056. *c=(Unit)(carry%(DECDPUNMAX+1));
  6057. carry=carry/(DECDPUNMAX+1);
  6058. continue;
  6059. }
  6060. // negative case
  6061. carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
  6062. *c=(Unit)(carry%(DECDPUNMAX+1));
  6063. carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
  6064. #endif
  6065. } // c
  6066. // now may have one or other to complete
  6067. // [pretest to avoid loop setup/shutdown]
  6068. if (c<maxC) for (; c<maxC; c++) {
  6069. if (a<alsu+alength) { // still in A
  6070. carry+=*a;
  6071. a++;
  6072. }
  6073. else { // inside B
  6074. carry+=((eInt)*b)*m;
  6075. b++;
  6076. }
  6077. // here carry is new Unit of digits; it could be +ve or -ve and
  6078. // magnitude up to DECDPUNMAX squared
  6079. if ((ueInt)carry<=DECDPUNMAX) { // fastpath 0-DECDPUNMAX
  6080. *c=(Unit)carry;
  6081. carry=0;
  6082. continue;
  6083. }
  6084. // result for this unit is negative or >DECDPUNMAX
  6085. #if DECDPUN==4 // use divide-by-multiply
  6086. if (carry>=0) {
  6087. est=(((ueInt)carry>>11)*53687)>>18;
  6088. *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
  6089. carry=est; // likely quotient [79.7%]
  6090. if (*c<DECDPUNMAX+1) continue; // estimate was correct
  6091. carry++;
  6092. *c-=DECDPUNMAX+1;
  6093. continue;
  6094. }
  6095. // negative case
  6096. carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
  6097. est=(((ueInt)carry>>11)*53687)>>18;
  6098. *c=(Unit)(carry-est*(DECDPUNMAX+1));
  6099. carry=est-(DECDPUNMAX+1); // correctly negative
  6100. if (*c<DECDPUNMAX+1) continue; // was OK
  6101. carry++;
  6102. *c-=DECDPUNMAX+1;
  6103. #elif DECDPUN==3
  6104. if (carry>=0) {
  6105. est=(((ueInt)carry>>3)*16777)>>21;
  6106. *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
  6107. carry=est; // likely quotient [99%]
  6108. if (*c<DECDPUNMAX+1) continue; // estimate was correct
  6109. carry++;
  6110. *c-=DECDPUNMAX+1;
  6111. continue;
  6112. }
  6113. // negative case
  6114. carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
  6115. est=(((ueInt)carry>>3)*16777)>>21;
  6116. *c=(Unit)(carry-est*(DECDPUNMAX+1));
  6117. carry=est-(DECDPUNMAX+1); // correctly negative
  6118. if (*c<DECDPUNMAX+1) continue; // was OK
  6119. carry++;
  6120. *c-=DECDPUNMAX+1;
  6121. #elif DECDPUN<=2
  6122. if (carry>=0) {
  6123. est=QUOT10(carry, DECDPUN);
  6124. *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
  6125. carry=est; // quotient
  6126. continue;
  6127. }
  6128. // negative case
  6129. carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
  6130. est=QUOT10(carry, DECDPUN);
  6131. *c=(Unit)(carry-est*(DECDPUNMAX+1));
  6132. carry=est-(DECDPUNMAX+1); // correctly negative
  6133. #else
  6134. if ((ueInt)carry<(DECDPUNMAX+1)*2){ // fastpath carry 1
  6135. *c=(Unit)(carry-(DECDPUNMAX+1));
  6136. carry=1;
  6137. continue;
  6138. }
  6139. // remainder operator is undefined if negative, so must test
  6140. if (carry>=0) {
  6141. *c=(Unit)(carry%(DECDPUNMAX+1));
  6142. carry=carry/(DECDPUNMAX+1);
  6143. continue;
  6144. }
  6145. // negative case
  6146. carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
  6147. *c=(Unit)(carry%(DECDPUNMAX+1));
  6148. carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
  6149. #endif
  6150. } // c
  6151. // OK, all A and B processed; might still have carry or borrow
  6152. // return number of Units in the result, negated if a borrow
  6153. if (carry==0) return c-clsu; // no carry, so no more to do
  6154. if (carry>0) { // positive carry
  6155. *c=(Unit)carry; // place as new unit
  6156. c++; // ..
  6157. return c-clsu;
  6158. }
  6159. // -ve carry: it's a borrow; complement needed
  6160. add=1; // temporary carry...
  6161. for (c=clsu; c<maxC; c++) {
  6162. add=DECDPUNMAX+add-*c;
  6163. if (add<=DECDPUNMAX) {
  6164. *c=(Unit)add;
  6165. add=0;
  6166. }
  6167. else {
  6168. *c=0;
  6169. add=1;
  6170. }
  6171. }
  6172. // add an extra unit iff it would be non-zero
  6173. #if DECTRACE
  6174. printf("UAS borrow: add %ld, carry %ld\n", add, carry);
  6175. #endif
  6176. if ((add-carry-1)!=0) {
  6177. *c=(Unit)(add-carry-1);
  6178. c++; // interesting, include it
  6179. }
  6180. return clsu-c; // -ve result indicates borrowed
  6181. } // decUnitAddSub
  6182. /* ------------------------------------------------------------------ */
  6183. /* decTrim -- trim trailing zeros or normalize */
  6184. /* */
  6185. /* dn is the number to trim or normalize */
  6186. /* set is the context to use to check for clamp */
  6187. /* all is 1 to remove all trailing zeros, 0 for just fraction ones */
  6188. /* noclamp is 1 to unconditional (unclamped) trim */
  6189. /* dropped returns the number of discarded trailing zeros */
  6190. /* returns dn */
  6191. /* */
  6192. /* If clamp is set in the context then the number of zeros trimmed */
  6193. /* may be limited if the exponent is high. */
  6194. /* All fields are updated as required. This is a utility operation, */
  6195. /* so special values are unchanged and no error is possible. */
  6196. /* ------------------------------------------------------------------ */
  6197. static decNumber * decTrim(decNumber *dn, decContext *set, Flag all,
  6198. Flag noclamp, Int *dropped) {
  6199. Int d, exp; // work
  6200. uInt cut; // ..
  6201. Unit *up; // -> current Unit
  6202. #if DECCHECK
  6203. if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
  6204. #endif
  6205. *dropped=0; // assume no zeros dropped
  6206. if ((dn->bits & DECSPECIAL) // fast exit if special ..
  6207. || (*dn->lsu & 0x01)) return dn; // .. or odd
  6208. if (ISZERO(dn)) { // .. or 0
  6209. dn->exponent=0; // (sign is preserved)
  6210. return dn;
  6211. }
  6212. // have a finite number which is even
  6213. exp=dn->exponent;
  6214. cut=1; // digit (1-DECDPUN) in Unit
  6215. up=dn->lsu; // -> current Unit
  6216. for (d=0; d<dn->digits-1; d++) { // [don't strip the final digit]
  6217. // slice by powers
  6218. #if DECDPUN<=4
  6219. uInt quot=QUOT10(*up, cut);
  6220. if ((*up-quot*powers[cut])!=0) break; // found non-0 digit
  6221. #else
  6222. if (*up%powers[cut]!=0) break; // found non-0 digit
  6223. #endif
  6224. // have a trailing 0
  6225. if (!all) { // trimming
  6226. // [if exp>0 then all trailing 0s are significant for trim]
  6227. if (exp<=0) { // if digit might be significant
  6228. if (exp==0) break; // then quit
  6229. exp++; // next digit might be significant
  6230. }
  6231. }
  6232. cut++; // next power
  6233. if (cut>DECDPUN) { // need new Unit
  6234. up++;
  6235. cut=1;
  6236. }
  6237. } // d
  6238. if (d==0) return dn; // none to drop
  6239. // may need to limit drop if clamping
  6240. if (set->clamp && !noclamp) {
  6241. Int maxd=set->emax-set->digits+1-dn->exponent;
  6242. if (maxd<=0) return dn; // nothing possible
  6243. if (d>maxd) d=maxd;
  6244. }
  6245. // effect the drop
  6246. decShiftToLeast(dn->lsu, D2U(dn->digits), d);
  6247. dn->exponent+=d; // maintain numerical value
  6248. dn->digits-=d; // new length
  6249. *dropped=d; // report the count
  6250. return dn;
  6251. } // decTrim
  6252. /* ------------------------------------------------------------------ */
  6253. /* decReverse -- reverse a Unit array in place */
  6254. /* */
  6255. /* ulo is the start of the array */
  6256. /* uhi is the end of the array (highest Unit to include) */
  6257. /* */
  6258. /* The units ulo through uhi are reversed in place (if the number */
  6259. /* of units is odd, the middle one is untouched). Note that the */
  6260. /* digit(s) in each unit are unaffected. */
  6261. /* ------------------------------------------------------------------ */
  6262. static void decReverse(Unit *ulo, Unit *uhi) {
  6263. Unit temp;
  6264. for (; ulo<uhi; ulo++, uhi--) {
  6265. temp=*ulo;
  6266. *ulo=*uhi;
  6267. *uhi=temp;
  6268. }
  6269. return;
  6270. } // decReverse
  6271. /* ------------------------------------------------------------------ */
  6272. /* decShiftToMost -- shift digits in array towards most significant */
  6273. /* */
  6274. /* uar is the array */
  6275. /* digits is the count of digits in use in the array */
  6276. /* shift is the number of zeros to pad with (least significant); */
  6277. /* it must be zero or positive */
  6278. /* */
  6279. /* returns the new length of the integer in the array, in digits */
  6280. /* */
  6281. /* No overflow is permitted (that is, the uar array must be known to */
  6282. /* be large enough to hold the result, after shifting). */
  6283. /* ------------------------------------------------------------------ */
  6284. static Int decShiftToMost(Unit *uar, Int digits, Int shift) {
  6285. Unit *target, *source, *first; // work
  6286. Int cut; // odd 0's to add
  6287. uInt next; // work
  6288. if (shift==0) return digits; // [fastpath] nothing to do
  6289. if ((digits+shift)<=DECDPUN) { // [fastpath] single-unit case
  6290. *uar=(Unit)(*uar*powers[shift]);
  6291. return digits+shift;
  6292. }
  6293. next=0; // all paths
  6294. source=uar+D2U(digits)-1; // where msu comes from
  6295. target=source+D2U(shift); // where upper part of first cut goes
  6296. cut=DECDPUN-MSUDIGITS(shift); // where to slice
  6297. if (cut==0) { // unit-boundary case
  6298. for (; source>=uar; source--, target--) *target=*source;
  6299. }
  6300. else {
  6301. first=uar+D2U(digits+shift)-1; // where msu of source will end up
  6302. for (; source>=uar; source--, target--) {
  6303. // split the source Unit and accumulate remainder for next
  6304. #if DECDPUN<=4
  6305. uInt quot=QUOT10(*source, cut);
  6306. uInt rem=*source-quot*powers[cut];
  6307. next+=quot;
  6308. #else
  6309. uInt rem=*source%powers[cut];
  6310. next+=*source/powers[cut];
  6311. #endif
  6312. if (target<=first) *target=(Unit)next; // write to target iff valid
  6313. next=rem*powers[DECDPUN-cut]; // save remainder for next Unit
  6314. }
  6315. } // shift-move
  6316. // propagate any partial unit to one below and clear the rest
  6317. for (; target>=uar; target--) {
  6318. *target=(Unit)next;
  6319. next=0;
  6320. }
  6321. return digits+shift;
  6322. } // decShiftToMost
  6323. /* ------------------------------------------------------------------ */
  6324. /* decShiftToLeast -- shift digits in array towards least significant */
  6325. /* */
  6326. /* uar is the array */
  6327. /* units is length of the array, in units */
  6328. /* shift is the number of digits to remove from the lsu end; it */
  6329. /* must be zero or positive and <= than units*DECDPUN. */
  6330. /* */
  6331. /* returns the new length of the integer in the array, in units */
  6332. /* */
  6333. /* Removed digits are discarded (lost). Units not required to hold */
  6334. /* the final result are unchanged. */
  6335. /* ------------------------------------------------------------------ */
  6336. static Int decShiftToLeast(Unit *uar, Int units, Int shift) {
  6337. Unit *target, *up; // work
  6338. Int cut, count; // work
  6339. Int quot, rem; // for division
  6340. if (shift==0) return units; // [fastpath] nothing to do
  6341. if (shift==units*DECDPUN) { // [fastpath] little to do
  6342. *uar=0; // all digits cleared gives zero
  6343. return 1; // leaves just the one
  6344. }
  6345. target=uar; // both paths
  6346. cut=MSUDIGITS(shift);
  6347. if (cut==DECDPUN) { // unit-boundary case; easy
  6348. up=uar+D2U(shift);
  6349. for (; up<uar+units; target++, up++) *target=*up;
  6350. return target-uar;
  6351. }
  6352. // messier
  6353. up=uar+D2U(shift-cut); // source; correct to whole Units
  6354. count=units*DECDPUN-shift; // the maximum new length
  6355. #if DECDPUN<=4
  6356. quot=QUOT10(*up, cut);
  6357. #else
  6358. quot=*up/powers[cut];
  6359. #endif
  6360. for (; ; target++) {
  6361. *target=(Unit)quot;
  6362. count-=(DECDPUN-cut);
  6363. if (count<=0) break;
  6364. up++;
  6365. quot=*up;
  6366. #if DECDPUN<=4
  6367. quot=QUOT10(quot, cut);
  6368. rem=*up-quot*powers[cut];
  6369. #else
  6370. rem=quot%powers[cut];
  6371. quot=quot/powers[cut];
  6372. #endif
  6373. *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
  6374. count-=cut;
  6375. if (count<=0) break;
  6376. }
  6377. return target-uar+1;
  6378. } // decShiftToLeast
  6379. #if DECSUBSET
  6380. /* ------------------------------------------------------------------ */
  6381. /* decRoundOperand -- round an operand [used for subset only] */
  6382. /* */
  6383. /* dn is the number to round (dn->digits is > set->digits) */
  6384. /* set is the relevant context */
  6385. /* status is the status accumulator */
  6386. /* */
  6387. /* returns an allocated decNumber with the rounded result. */
  6388. /* */
  6389. /* lostDigits and other status may be set by this. */
  6390. /* */
  6391. /* Since the input is an operand, it must not be modified. */
  6392. /* Instead, return an allocated decNumber, rounded as required. */
  6393. /* It is the caller's responsibility to free the allocated storage. */
  6394. /* */
  6395. /* If no storage is available then the result cannot be used, so NULL */
  6396. /* is returned. */
  6397. /* ------------------------------------------------------------------ */
  6398. static decNumber *decRoundOperand(const decNumber *dn, decContext *set,
  6399. uInt *status) {
  6400. decNumber *res; // result structure
  6401. uInt newstatus=0; // status from round
  6402. Int residue=0; // rounding accumulator
  6403. // Allocate storage for the returned decNumber, big enough for the
  6404. // length specified by the context
  6405. res=(decNumber *)malloc(sizeof(decNumber)
  6406. +(D2U(set->digits)-1)*sizeof(Unit));
  6407. if (res==NULL) {
  6408. *status|=DEC_Insufficient_storage;
  6409. return NULL;
  6410. }
  6411. decCopyFit(res, dn, set, &residue, &newstatus);
  6412. decApplyRound(res, set, residue, &newstatus);
  6413. // If that set Inexact then "lost digits" is raised...
  6414. if (newstatus & DEC_Inexact) newstatus|=DEC_Lost_digits;
  6415. *status|=newstatus;
  6416. return res;
  6417. } // decRoundOperand
  6418. #endif
  6419. /* ------------------------------------------------------------------ */
  6420. /* decCopyFit -- copy a number, truncating the coefficient if needed */
  6421. /* */
  6422. /* dest is the target decNumber */
  6423. /* src is the source decNumber */
  6424. /* set is the context [used for length (digits) and rounding mode] */
  6425. /* residue is the residue accumulator */
  6426. /* status contains the current status to be updated */
  6427. /* */
  6428. /* (dest==src is allowed and will be a no-op if fits) */
  6429. /* All fields are updated as required. */
  6430. /* ------------------------------------------------------------------ */
  6431. static void decCopyFit(decNumber *dest, const decNumber *src,
  6432. decContext *set, Int *residue, uInt *status) {
  6433. dest->bits=src->bits;
  6434. dest->exponent=src->exponent;
  6435. decSetCoeff(dest, set, src->lsu, src->digits, residue, status);
  6436. } // decCopyFit
  6437. /* ------------------------------------------------------------------ */
  6438. /* decSetCoeff -- set the coefficient of a number */
  6439. /* */
  6440. /* dn is the number whose coefficient array is to be set. */
  6441. /* It must have space for set->digits digits */
  6442. /* set is the context [for size] */
  6443. /* lsu -> lsu of the source coefficient [may be dn->lsu] */
  6444. /* len is digits in the source coefficient [may be dn->digits] */
  6445. /* residue is the residue accumulator. This has values as in */
  6446. /* decApplyRound, and will be unchanged unless the */
  6447. /* target size is less than len. In this case, the */
  6448. /* coefficient is truncated and the residue is updated to */
  6449. /* reflect the previous residue and the dropped digits. */
  6450. /* status is the status accumulator, as usual */
  6451. /* */
  6452. /* The coefficient may already be in the number, or it can be an */
  6453. /* external intermediate array. If it is in the number, lsu must == */
  6454. /* dn->lsu and len must == dn->digits. */
  6455. /* */
  6456. /* Note that the coefficient length (len) may be < set->digits, and */
  6457. /* in this case this merely copies the coefficient (or is a no-op */
  6458. /* if dn->lsu==lsu). */
  6459. /* */
  6460. /* Note also that (only internally, from decQuantizeOp and */
  6461. /* decSetSubnormal) the value of set->digits may be less than one, */
  6462. /* indicating a round to left. This routine handles that case */
  6463. /* correctly; caller ensures space. */
  6464. /* */
  6465. /* dn->digits, dn->lsu (and as required), and dn->exponent are */
  6466. /* updated as necessary. dn->bits (sign) is unchanged. */
  6467. /* */
  6468. /* DEC_Rounded status is set if any digits are discarded. */
  6469. /* DEC_Inexact status is set if any non-zero digits are discarded, or */
  6470. /* incoming residue was non-0 (implies rounded) */
  6471. /* ------------------------------------------------------------------ */
  6472. // mapping array: maps 0-9 to canonical residues, so that a residue
  6473. // can be adjusted in the range [-1, +1] and achieve correct rounding
  6474. // 0 1 2 3 4 5 6 7 8 9
  6475. static const uByte resmap[10]={0, 3, 3, 3, 3, 5, 7, 7, 7, 7};
  6476. static void decSetCoeff(decNumber *dn, decContext *set, const Unit *lsu,
  6477. Int len, Int *residue, uInt *status) {
  6478. Int discard; // number of digits to discard
  6479. uInt cut; // cut point in Unit
  6480. const Unit *up; // work
  6481. Unit *target; // ..
  6482. Int count; // ..
  6483. #if DECDPUN<=4
  6484. uInt temp; // ..
  6485. #endif
  6486. discard=len-set->digits; // digits to discard
  6487. if (discard<=0) { // no digits are being discarded
  6488. if (dn->lsu!=lsu) { // copy needed
  6489. // copy the coefficient array to the result number; no shift needed
  6490. count=len; // avoids D2U
  6491. up=lsu;
  6492. for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
  6493. *target=*up;
  6494. dn->digits=len; // set the new length
  6495. }
  6496. // dn->exponent and residue are unchanged, record any inexactitude
  6497. if (*residue!=0) *status|=(DEC_Inexact | DEC_Rounded);
  6498. return;
  6499. }
  6500. // some digits must be discarded ...
  6501. dn->exponent+=discard; // maintain numerical value
  6502. *status|=DEC_Rounded; // accumulate Rounded status
  6503. if (*residue>1) *residue=1; // previous residue now to right, so reduce
  6504. if (discard>len) { // everything, +1, is being discarded
  6505. // guard digit is 0
  6506. // residue is all the number [NB could be all 0s]
  6507. if (*residue<=0) { // not already positive
  6508. count=len; // avoids D2U
  6509. for (up=lsu; count>0; up++, count-=DECDPUN) if (*up!=0) { // found non-0
  6510. *residue=1;
  6511. break; // no need to check any others
  6512. }
  6513. }
  6514. if (*residue!=0) *status|=DEC_Inexact; // record inexactitude
  6515. *dn->lsu=0; // coefficient will now be 0
  6516. dn->digits=1; // ..
  6517. return;
  6518. } // total discard
  6519. // partial discard [most common case]
  6520. // here, at least the first (most significant) discarded digit exists
  6521. // spin up the number, noting residue during the spin, until get to
  6522. // the Unit with the first discarded digit. When reach it, extract
  6523. // it and remember its position
  6524. count=0;
  6525. for (up=lsu;; up++) {
  6526. count+=DECDPUN;
  6527. if (count>=discard) break; // full ones all checked
  6528. if (*up!=0) *residue=1;
  6529. } // up
  6530. // here up -> Unit with first discarded digit
  6531. cut=discard-(count-DECDPUN)-1;
  6532. if (cut==DECDPUN-1) { // unit-boundary case (fast)
  6533. Unit half=(Unit)powers[DECDPUN]>>1;
  6534. // set residue directly
  6535. if (*up>=half) {
  6536. if (*up>half) *residue=7;
  6537. else *residue+=5; // add sticky bit
  6538. }
  6539. else { // <half
  6540. if (*up!=0) *residue=3; // [else is 0, leave as sticky bit]
  6541. }
  6542. if (set->digits<=0) { // special for Quantize/Subnormal :-(
  6543. *dn->lsu=0; // .. result is 0
  6544. dn->digits=1; // ..
  6545. }
  6546. else { // shift to least
  6547. count=set->digits; // now digits to end up with
  6548. dn->digits=count; // set the new length
  6549. up++; // move to next
  6550. // on unit boundary, so shift-down copy loop is simple
  6551. for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
  6552. *target=*up;
  6553. }
  6554. } // unit-boundary case
  6555. else { // discard digit is in low digit(s), and not top digit
  6556. uInt discard1; // first discarded digit
  6557. uInt quot, rem; // for divisions
  6558. if (cut==0) quot=*up; // is at bottom of unit
  6559. else /* cut>0 */ { // it's not at bottom of unit
  6560. #if DECDPUN<=4
  6561. quot=QUOT10(*up, cut);
  6562. rem=*up-quot*powers[cut];
  6563. #else
  6564. rem=*up%powers[cut];
  6565. quot=*up/powers[cut];
  6566. #endif
  6567. if (rem!=0) *residue=1;
  6568. }
  6569. // discard digit is now at bottom of quot
  6570. #if DECDPUN<=4
  6571. temp=(quot*6554)>>16; // fast /10
  6572. // Vowels algorithm here not a win (9 instructions)
  6573. discard1=quot-X10(temp);
  6574. quot=temp;
  6575. #else
  6576. discard1=quot%10;
  6577. quot=quot/10;
  6578. #endif
  6579. // here, discard1 is the guard digit, and residue is everything
  6580. // else [use mapping array to accumulate residue safely]
  6581. *residue+=resmap[discard1];
  6582. cut++; // update cut
  6583. // here: up -> Unit of the array with bottom digit
  6584. // cut is the division point for each Unit
  6585. // quot holds the uncut high-order digits for the current unit
  6586. if (set->digits<=0) { // special for Quantize/Subnormal :-(
  6587. *dn->lsu=0; // .. result is 0
  6588. dn->digits=1; // ..
  6589. }
  6590. else { // shift to least needed
  6591. count=set->digits; // now digits to end up with
  6592. dn->digits=count; // set the new length
  6593. // shift-copy the coefficient array to the result number
  6594. for (target=dn->lsu; ; target++) {
  6595. *target=(Unit)quot;
  6596. count-=(DECDPUN-cut);
  6597. if (count<=0) break;
  6598. up++;
  6599. quot=*up;
  6600. #if DECDPUN<=4
  6601. quot=QUOT10(quot, cut);
  6602. rem=*up-quot*powers[cut];
  6603. #else
  6604. rem=quot%powers[cut];
  6605. quot=quot/powers[cut];
  6606. #endif
  6607. *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
  6608. count-=cut;
  6609. if (count<=0) break;
  6610. } // shift-copy loop
  6611. } // shift to least
  6612. } // not unit boundary
  6613. if (*residue!=0) *status|=DEC_Inexact; // record inexactitude
  6614. return;
  6615. } // decSetCoeff
  6616. /* ------------------------------------------------------------------ */
  6617. /* decApplyRound -- apply pending rounding to a number */
  6618. /* */
  6619. /* dn is the number, with space for set->digits digits */
  6620. /* set is the context [for size and rounding mode] */
  6621. /* residue indicates pending rounding, being any accumulated */
  6622. /* guard and sticky information. It may be: */
  6623. /* 6-9: rounding digit is >5 */
  6624. /* 5: rounding digit is exactly half-way */
  6625. /* 1-4: rounding digit is <5 and >0 */
  6626. /* 0: the coefficient is exact */
  6627. /* -1: as 1, but the hidden digits are subtractive, that */
  6628. /* is, of the opposite sign to dn. In this case the */
  6629. /* coefficient must be non-0. This case occurs when */
  6630. /* subtracting a small number (which can be reduced to */
  6631. /* a sticky bit); see decAddOp. */
  6632. /* status is the status accumulator, as usual */
  6633. /* */
  6634. /* This routine applies rounding while keeping the length of the */
  6635. /* coefficient constant. The exponent and status are unchanged */
  6636. /* except if: */
  6637. /* */
  6638. /* -- the coefficient was increased and is all nines (in which */
  6639. /* case Overflow could occur, and is handled directly here so */
  6640. /* the caller does not need to re-test for overflow) */
  6641. /* */
  6642. /* -- the coefficient was decreased and becomes all nines (in which */
  6643. /* case Underflow could occur, and is also handled directly). */
  6644. /* */
  6645. /* All fields in dn are updated as required. */
  6646. /* */
  6647. /* ------------------------------------------------------------------ */
  6648. static void decApplyRound(decNumber *dn, decContext *set, Int residue,
  6649. uInt *status) {
  6650. Int bump; // 1 if coefficient needs to be incremented
  6651. // -1 if coefficient needs to be decremented
  6652. if (residue==0) return; // nothing to apply
  6653. bump=0; // assume a smooth ride
  6654. // now decide whether, and how, to round, depending on mode
  6655. switch (set->round) {
  6656. case DEC_ROUND_05UP: { // round zero or five up (for reround)
  6657. // This is the same as DEC_ROUND_DOWN unless there is a
  6658. // positive residue and the lsd of dn is 0 or 5, in which case
  6659. // it is bumped; when residue is <0, the number is therefore
  6660. // bumped down unless the final digit was 1 or 6 (in which
  6661. // case it is bumped down and then up -- a no-op)
  6662. Int lsd5=*dn->lsu%5; // get lsd and quintate
  6663. if (residue<0 && lsd5!=1) bump=-1;
  6664. else if (residue>0 && lsd5==0) bump=1;
  6665. // [bump==1 could be applied directly; use common path for clarity]
  6666. break;} // r-05
  6667. case DEC_ROUND_DOWN: {
  6668. // no change, except if negative residue
  6669. if (residue<0) bump=-1;
  6670. break;} // r-d
  6671. case DEC_ROUND_HALF_DOWN: {
  6672. if (residue>5) bump=1;
  6673. break;} // r-h-d
  6674. case DEC_ROUND_HALF_EVEN: {
  6675. if (residue>5) bump=1; // >0.5 goes up
  6676. else if (residue==5) { // exactly 0.5000...
  6677. // 0.5 goes up iff [new] lsd is odd
  6678. if (*dn->lsu & 0x01) bump=1;
  6679. }
  6680. break;} // r-h-e
  6681. case DEC_ROUND_HALF_UP: {
  6682. if (residue>=5) bump=1;
  6683. break;} // r-h-u
  6684. case DEC_ROUND_UP: {
  6685. if (residue>0) bump=1;
  6686. break;} // r-u
  6687. case DEC_ROUND_CEILING: {
  6688. // same as _UP for positive numbers, and as _DOWN for negatives
  6689. // [negative residue cannot occur on 0]
  6690. if (decNumberIsNegative(dn)) {
  6691. if (residue<0) bump=-1;
  6692. }
  6693. else {
  6694. if (residue>0) bump=1;
  6695. }
  6696. break;} // r-c
  6697. case DEC_ROUND_FLOOR: {
  6698. // same as _UP for negative numbers, and as _DOWN for positive
  6699. // [negative residue cannot occur on 0]
  6700. if (!decNumberIsNegative(dn)) {
  6701. if (residue<0) bump=-1;
  6702. }
  6703. else {
  6704. if (residue>0) bump=1;
  6705. }
  6706. break;} // r-f
  6707. default: { // e.g., DEC_ROUND_MAX
  6708. *status|=DEC_Invalid_context;
  6709. #if DECTRACE || (DECCHECK && DECVERB)
  6710. printf("Unknown rounding mode: %d\n", set->round);
  6711. #endif
  6712. break;}
  6713. } // switch
  6714. // now bump the number, up or down, if need be
  6715. if (bump==0) return; // no action required
  6716. // Simply use decUnitAddSub unless bumping up and the number is
  6717. // all nines. In this special case set to 100... explicitly
  6718. // and adjust the exponent by one (as otherwise could overflow
  6719. // the array)
  6720. // Similarly handle all-nines result if bumping down.
  6721. if (bump>0) {
  6722. Unit *up; // work
  6723. uInt count=dn->digits; // digits to be checked
  6724. for (up=dn->lsu; ; up++) {
  6725. if (count<=DECDPUN) {
  6726. // this is the last Unit (the msu)
  6727. if (*up!=powers[count]-1) break; // not still 9s
  6728. // here if it, too, is all nines
  6729. *up=(Unit)powers[count-1]; // here 999 -> 100 etc.
  6730. for (up=up-1; up>=dn->lsu; up--) *up=0; // others all to 0
  6731. dn->exponent++; // and bump exponent
  6732. // [which, very rarely, could cause Overflow...]
  6733. if ((dn->exponent+dn->digits)>set->emax+1) {
  6734. decSetOverflow(dn, set, status);
  6735. }
  6736. return; // done
  6737. }
  6738. // a full unit to check, with more to come
  6739. if (*up!=DECDPUNMAX) break; // not still 9s
  6740. count-=DECDPUN;
  6741. } // up
  6742. } // bump>0
  6743. else { // -1
  6744. // here checking for a pre-bump of 1000... (leading 1, all
  6745. // other digits zero)
  6746. Unit *up, *sup; // work
  6747. uInt count=dn->digits; // digits to be checked
  6748. for (up=dn->lsu; ; up++) {
  6749. if (count<=DECDPUN) {
  6750. // this is the last Unit (the msu)
  6751. if (*up!=powers[count-1]) break; // not 100..
  6752. // here if have the 1000... case
  6753. sup=up; // save msu pointer
  6754. *up=(Unit)powers[count]-1; // here 100 in msu -> 999
  6755. // others all to all-nines, too
  6756. for (up=up-1; up>=dn->lsu; up--) *up=(Unit)powers[DECDPUN]-1;
  6757. dn->exponent--; // and bump exponent
  6758. // iff the number was at the subnormal boundary (exponent=etiny)
  6759. // then the exponent is now out of range, so it will in fact get
  6760. // clamped to etiny and the final 9 dropped.
  6761. // printf(">> emin=%d exp=%d sdig=%d\n", set->emin,
  6762. // dn->exponent, set->digits);
  6763. if (dn->exponent+1==set->emin-set->digits+1) {
  6764. if (count==1 && dn->digits==1) *sup=0; // here 9 -> 0[.9]
  6765. else {
  6766. *sup=(Unit)powers[count-1]-1; // here 999.. in msu -> 99..
  6767. dn->digits--;
  6768. }
  6769. dn->exponent++;
  6770. *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
  6771. }
  6772. return; // done
  6773. }
  6774. // a full unit to check, with more to come
  6775. if (*up!=0) break; // not still 0s
  6776. count-=DECDPUN;
  6777. } // up
  6778. } // bump<0
  6779. // Actual bump needed. Do it.
  6780. decUnitAddSub(dn->lsu, D2U(dn->digits), uarrone, 1, 0, dn->lsu, bump);
  6781. } // decApplyRound
  6782. #if DECSUBSET
  6783. /* ------------------------------------------------------------------ */
  6784. /* decFinish -- finish processing a number */
  6785. /* */
  6786. /* dn is the number */
  6787. /* set is the context */
  6788. /* residue is the rounding accumulator (as in decApplyRound) */
  6789. /* status is the accumulator */
  6790. /* */
  6791. /* This finishes off the current number by: */
  6792. /* 1. If not extended: */
  6793. /* a. Converting a zero result to clean '0' */
  6794. /* b. Reducing positive exponents to 0, if would fit in digits */
  6795. /* 2. Checking for overflow and subnormals (always) */
  6796. /* Note this is just Finalize when no subset arithmetic. */
  6797. /* All fields are updated as required. */
  6798. /* ------------------------------------------------------------------ */
  6799. static void decFinish(decNumber *dn, decContext *set, Int *residue,
  6800. uInt *status) {
  6801. if (!set->extended) {
  6802. if ISZERO(dn) { // value is zero
  6803. dn->exponent=0; // clean exponent ..
  6804. dn->bits=0; // .. and sign
  6805. return; // no error possible
  6806. }
  6807. if (dn->exponent>=0) { // non-negative exponent
  6808. // >0; reduce to integer if possible
  6809. if (set->digits >= (dn->exponent+dn->digits)) {
  6810. dn->digits=decShiftToMost(dn->lsu, dn->digits, dn->exponent);
  6811. dn->exponent=0;
  6812. }
  6813. }
  6814. } // !extended
  6815. decFinalize(dn, set, residue, status);
  6816. } // decFinish
  6817. #endif
  6818. /* ------------------------------------------------------------------ */
  6819. /* decFinalize -- final check, clamp, and round of a number */
  6820. /* */
  6821. /* dn is the number */
  6822. /* set is the context */
  6823. /* residue is the rounding accumulator (as in decApplyRound) */
  6824. /* status is the status accumulator */
  6825. /* */
  6826. /* This finishes off the current number by checking for subnormal */
  6827. /* results, applying any pending rounding, checking for overflow, */
  6828. /* and applying any clamping. */
  6829. /* Underflow and overflow conditions are raised as appropriate. */
  6830. /* All fields are updated as required. */
  6831. /* ------------------------------------------------------------------ */
  6832. static void decFinalize(decNumber *dn, decContext *set, Int *residue,
  6833. uInt *status) {
  6834. Int shift; // shift needed if clamping
  6835. Int tinyexp=set->emin-dn->digits+1; // precalculate subnormal boundary
  6836. // Must be careful, here, when checking the exponent as the
  6837. // adjusted exponent could overflow 31 bits [because it may already
  6838. // be up to twice the expected].
  6839. // First test for subnormal. This must be done before any final
  6840. // round as the result could be rounded to Nmin or 0.
  6841. if (dn->exponent<=tinyexp) { // prefilter
  6842. Int comp;
  6843. decNumber nmin;
  6844. // A very nasty case here is dn == Nmin and residue<0
  6845. if (dn->exponent<tinyexp) {
  6846. // Go handle subnormals; this will apply round if needed.
  6847. decSetSubnormal(dn, set, residue, status);
  6848. return;
  6849. }
  6850. // Equals case: only subnormal if dn=Nmin and negative residue
  6851. decNumberZero(&nmin);
  6852. nmin.lsu[0]=1;
  6853. nmin.exponent=set->emin;
  6854. comp=decCompare(dn, &nmin, 1); // (signless compare)
  6855. if (comp==BADINT) { // oops
  6856. *status|=DEC_Insufficient_storage; // abandon...
  6857. return;
  6858. }
  6859. if (*residue<0 && comp==0) { // neg residue and dn==Nmin
  6860. decApplyRound(dn, set, *residue, status); // might force down
  6861. decSetSubnormal(dn, set, residue, status);
  6862. return;
  6863. }
  6864. }
  6865. // now apply any pending round (this could raise overflow).
  6866. if (*residue!=0) decApplyRound(dn, set, *residue, status);
  6867. // Check for overflow [redundant in the 'rare' case] or clamp
  6868. if (dn->exponent<=set->emax-set->digits+1) return; // neither needed
  6869. // here when might have an overflow or clamp to do
  6870. if (dn->exponent>set->emax-dn->digits+1) { // too big
  6871. decSetOverflow(dn, set, status);
  6872. return;
  6873. }
  6874. // here when the result is normal but in clamp range
  6875. if (!set->clamp) return;
  6876. // here when need to apply the IEEE exponent clamp (fold-down)
  6877. shift=dn->exponent-(set->emax-set->digits+1);
  6878. // shift coefficient (if non-zero)
  6879. if (!ISZERO(dn)) {
  6880. dn->digits=decShiftToMost(dn->lsu, dn->digits, shift);
  6881. }
  6882. dn->exponent-=shift; // adjust the exponent to match
  6883. *status|=DEC_Clamped; // and record the dirty deed
  6884. return;
  6885. } // decFinalize
  6886. /* ------------------------------------------------------------------ */
  6887. /* decSetOverflow -- set number to proper overflow value */
  6888. /* */
  6889. /* dn is the number (used for sign [only] and result) */
  6890. /* set is the context [used for the rounding mode, etc.] */
  6891. /* status contains the current status to be updated */
  6892. /* */
  6893. /* This sets the sign of a number and sets its value to either */
  6894. /* Infinity or the maximum finite value, depending on the sign of */
  6895. /* dn and the rounding mode, following IEEE 754 rules. */
  6896. /* ------------------------------------------------------------------ */
  6897. static void decSetOverflow(decNumber *dn, decContext *set, uInt *status) {
  6898. Flag needmax=0; // result is maximum finite value
  6899. uByte sign=dn->bits&DECNEG; // clean and save sign bit
  6900. if (ISZERO(dn)) { // zero does not overflow magnitude
  6901. Int emax=set->emax; // limit value
  6902. if (set->clamp) emax-=set->digits-1; // lower if clamping
  6903. if (dn->exponent>emax) { // clamp required
  6904. dn->exponent=emax;
  6905. *status|=DEC_Clamped;
  6906. }
  6907. return;
  6908. }
  6909. decNumberZero(dn);
  6910. switch (set->round) {
  6911. case DEC_ROUND_DOWN: {
  6912. needmax=1; // never Infinity
  6913. break;} // r-d
  6914. case DEC_ROUND_05UP: {
  6915. needmax=1; // never Infinity
  6916. break;} // r-05
  6917. case DEC_ROUND_CEILING: {
  6918. if (sign) needmax=1; // Infinity if non-negative
  6919. break;} // r-c
  6920. case DEC_ROUND_FLOOR: {
  6921. if (!sign) needmax=1; // Infinity if negative
  6922. break;} // r-f
  6923. default: break; // Infinity in all other cases
  6924. }
  6925. if (needmax) {
  6926. decSetMaxValue(dn, set);
  6927. dn->bits=sign; // set sign
  6928. }
  6929. else dn->bits=sign|DECINF; // Value is +/-Infinity
  6930. *status|=DEC_Overflow | DEC_Inexact | DEC_Rounded;
  6931. } // decSetOverflow
  6932. /* ------------------------------------------------------------------ */
  6933. /* decSetMaxValue -- set number to +Nmax (maximum normal value) */
  6934. /* */
  6935. /* dn is the number to set */
  6936. /* set is the context [used for digits and emax] */
  6937. /* */
  6938. /* This sets the number to the maximum positive value. */
  6939. /* ------------------------------------------------------------------ */
  6940. static void decSetMaxValue(decNumber *dn, decContext *set) {
  6941. Unit *up; // work
  6942. Int count=set->digits; // nines to add
  6943. dn->digits=count;
  6944. // fill in all nines to set maximum value
  6945. for (up=dn->lsu; ; up++) {
  6946. if (count>DECDPUN) *up=DECDPUNMAX; // unit full o'nines
  6947. else { // this is the msu
  6948. *up=(Unit)(powers[count]-1);
  6949. break;
  6950. }
  6951. count-=DECDPUN; // filled those digits
  6952. } // up
  6953. dn->bits=0; // + sign
  6954. dn->exponent=set->emax-set->digits+1;
  6955. } // decSetMaxValue
  6956. /* ------------------------------------------------------------------ */
  6957. /* decSetSubnormal -- process value whose exponent is <Emin */
  6958. /* */
  6959. /* dn is the number (used as input as well as output; it may have */
  6960. /* an allowed subnormal value, which may need to be rounded) */
  6961. /* set is the context [used for the rounding mode] */
  6962. /* residue is any pending residue */
  6963. /* status contains the current status to be updated */
  6964. /* */
  6965. /* If subset mode, set result to zero and set Underflow flags. */
  6966. /* */
  6967. /* Value may be zero with a low exponent; this does not set Subnormal */
  6968. /* but the exponent will be clamped to Etiny. */
  6969. /* */
  6970. /* Otherwise ensure exponent is not out of range, and round as */
  6971. /* necessary. Underflow is set if the result is Inexact. */
  6972. /* ------------------------------------------------------------------ */
  6973. static void decSetSubnormal(decNumber *dn, decContext *set, Int *residue,
  6974. uInt *status) {
  6975. decContext workset; // work
  6976. Int etiny, adjust; // ..
  6977. #if DECSUBSET
  6978. // simple set to zero and 'hard underflow' for subset
  6979. if (!set->extended) {
  6980. decNumberZero(dn);
  6981. // always full overflow
  6982. *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
  6983. return;
  6984. }
  6985. #endif
  6986. // Full arithmetic -- allow subnormals, rounded to minimum exponent
  6987. // (Etiny) if needed
  6988. etiny=set->emin-(set->digits-1); // smallest allowed exponent
  6989. if ISZERO(dn) { // value is zero
  6990. // residue can never be non-zero here
  6991. #if DECCHECK
  6992. if (*residue!=0) {
  6993. printf("++ Subnormal 0 residue %ld\n", (LI)*residue);
  6994. *status|=DEC_Invalid_operation;
  6995. }
  6996. #endif
  6997. if (dn->exponent<etiny) { // clamp required
  6998. dn->exponent=etiny;
  6999. *status|=DEC_Clamped;
  7000. }
  7001. return;
  7002. }
  7003. *status|=DEC_Subnormal; // have a non-zero subnormal
  7004. adjust=etiny-dn->exponent; // calculate digits to remove
  7005. if (adjust<=0) { // not out of range; unrounded
  7006. // residue can never be non-zero here, except in the Nmin-residue
  7007. // case (which is a subnormal result), so can take fast-path here
  7008. // it may already be inexact (from setting the coefficient)
  7009. if (*status&DEC_Inexact) *status|=DEC_Underflow;
  7010. return;
  7011. }
  7012. // adjust>0, so need to rescale the result so exponent becomes Etiny
  7013. // [this code is similar to that in rescale]
  7014. workset=*set; // clone rounding, etc.
  7015. workset.digits=dn->digits-adjust; // set requested length
  7016. workset.emin-=adjust; // and adjust emin to match
  7017. // [note that the latter can be <1, here, similar to Rescale case]
  7018. decSetCoeff(dn, &workset, dn->lsu, dn->digits, residue, status);
  7019. decApplyRound(dn, &workset, *residue, status);
  7020. // Use 754 default rule: Underflow is set iff Inexact
  7021. // [independent of whether trapped]
  7022. if (*status&DEC_Inexact) *status|=DEC_Underflow;
  7023. // if rounded up a 999s case, exponent will be off by one; adjust
  7024. // back if so [it will fit, because it was shortened earlier]
  7025. if (dn->exponent>etiny) {
  7026. dn->digits=decShiftToMost(dn->lsu, dn->digits, 1);
  7027. dn->exponent--; // (re)adjust the exponent.
  7028. }
  7029. // if rounded to zero, it is by definition clamped...
  7030. if (ISZERO(dn)) *status|=DEC_Clamped;
  7031. } // decSetSubnormal
  7032. /* ------------------------------------------------------------------ */
  7033. /* decCheckMath - check entry conditions for a math function */
  7034. /* */
  7035. /* This checks the context and the operand */
  7036. /* */
  7037. /* rhs is the operand to check */
  7038. /* set is the context to check */
  7039. /* status is unchanged if both are good */
  7040. /* */
  7041. /* returns non-zero if status is changed, 0 otherwise */
  7042. /* */
  7043. /* Restrictions enforced: */
  7044. /* */
  7045. /* digits, emax, and -emin in the context must be less than */
  7046. /* DEC_MAX_MATH (999999), and A must be within these bounds if */
  7047. /* non-zero. Invalid_operation is set in the status if a */
  7048. /* restriction is violated. */
  7049. /* ------------------------------------------------------------------ */
  7050. static uInt decCheckMath(const decNumber *rhs, decContext *set,
  7051. uInt *status) {
  7052. uInt save=*status; // record
  7053. if (set->digits>DEC_MAX_MATH
  7054. || set->emax>DEC_MAX_MATH
  7055. || -set->emin>DEC_MAX_MATH) *status|=DEC_Invalid_context;
  7056. else if ((rhs->digits>DEC_MAX_MATH
  7057. || rhs->exponent+rhs->digits>DEC_MAX_MATH+1
  7058. || rhs->exponent+rhs->digits<2*(1-DEC_MAX_MATH))
  7059. && !ISZERO(rhs)) *status|=DEC_Invalid_operation;
  7060. return (*status!=save);
  7061. } // decCheckMath
  7062. /* ------------------------------------------------------------------ */
  7063. /* decGetInt -- get integer from a number */
  7064. /* */
  7065. /* dn is the number [which will not be altered] */
  7066. /* */
  7067. /* returns one of: */
  7068. /* BADINT if there is a non-zero fraction */
  7069. /* the converted integer */
  7070. /* BIGEVEN if the integer is even and magnitude > 2*10**9 */
  7071. /* BIGODD if the integer is odd and magnitude > 2*10**9 */
  7072. /* */
  7073. /* This checks and gets a whole number from the input decNumber. */
  7074. /* The sign can be determined from dn by the caller when BIGEVEN or */
  7075. /* BIGODD is returned. */
  7076. /* ------------------------------------------------------------------ */
  7077. static Int decGetInt(const decNumber *dn) {
  7078. Int theInt; // result accumulator
  7079. const Unit *up; // work
  7080. Int got; // digits (real or not) processed
  7081. Int ilength=dn->digits+dn->exponent; // integral length
  7082. Flag neg=decNumberIsNegative(dn); // 1 if -ve
  7083. // The number must be an integer that fits in 10 digits
  7084. // Assert, here, that 10 is enough for any rescale Etiny
  7085. #if DEC_MAX_EMAX > 999999999
  7086. #error GetInt may need updating [for Emax]
  7087. #endif
  7088. #if DEC_MIN_EMIN < -999999999
  7089. #error GetInt may need updating [for Emin]
  7090. #endif
  7091. if (ISZERO(dn)) return 0; // zeros are OK, with any exponent
  7092. up=dn->lsu; // ready for lsu
  7093. theInt=0; // ready to accumulate
  7094. if (dn->exponent>=0) { // relatively easy
  7095. // no fractional part [usual]; allow for positive exponent
  7096. got=dn->exponent;
  7097. }
  7098. else { // -ve exponent; some fractional part to check and discard
  7099. Int count=-dn->exponent; // digits to discard
  7100. // spin up whole units until reach the Unit with the unit digit
  7101. for (; count>=DECDPUN; up++) {
  7102. if (*up!=0) return BADINT; // non-zero Unit to discard
  7103. count-=DECDPUN;
  7104. }
  7105. if (count==0) got=0; // [a multiple of DECDPUN]
  7106. else { // [not multiple of DECDPUN]
  7107. Int rem; // work
  7108. // slice off fraction digits and check for non-zero
  7109. #if DECDPUN<=4
  7110. theInt=QUOT10(*up, count);
  7111. rem=*up-theInt*powers[count];
  7112. #else
  7113. rem=*up%powers[count]; // slice off discards
  7114. theInt=*up/powers[count];
  7115. #endif
  7116. if (rem!=0) return BADINT; // non-zero fraction
  7117. // it looks good
  7118. got=DECDPUN-count; // number of digits so far
  7119. up++; // ready for next
  7120. }
  7121. }
  7122. // now it's known there's no fractional part
  7123. // tricky code now, to accumulate up to 9.3 digits
  7124. if (got==0) {theInt=*up; got+=DECDPUN; up++;} // ensure lsu is there
  7125. if (ilength<11) {
  7126. Int save=theInt;
  7127. // collect any remaining unit(s)
  7128. for (; got<ilength; up++) {
  7129. theInt+=*up*powers[got];
  7130. got+=DECDPUN;
  7131. }
  7132. if (ilength==10) { // need to check for wrap
  7133. if (theInt/(Int)powers[got-DECDPUN]!=(Int)*(up-1)) ilength=11;
  7134. // [that test also disallows the BADINT result case]
  7135. else if (neg && theInt>1999999997) ilength=11;
  7136. else if (!neg && theInt>999999999) ilength=11;
  7137. if (ilength==11) theInt=save; // restore correct low bit
  7138. }
  7139. }
  7140. if (ilength>10) { // too big
  7141. if (theInt&1) return BIGODD; // bottom bit 1
  7142. return BIGEVEN; // bottom bit 0
  7143. }
  7144. if (neg) theInt=-theInt; // apply sign
  7145. return theInt;
  7146. } // decGetInt
  7147. /* ------------------------------------------------------------------ */
  7148. /* decDecap -- decapitate the coefficient of a number */
  7149. /* */
  7150. /* dn is the number to be decapitated */
  7151. /* drop is the number of digits to be removed from the left of dn; */
  7152. /* this must be <= dn->digits (if equal, the coefficient is */
  7153. /* set to 0) */
  7154. /* */
  7155. /* Returns dn; dn->digits will be <= the initial digits less drop */
  7156. /* (after removing drop digits there may be leading zero digits */
  7157. /* which will also be removed). Only dn->lsu and dn->digits change. */
  7158. /* ------------------------------------------------------------------ */
  7159. static decNumber *decDecap(decNumber *dn, Int drop) {
  7160. Unit *msu; // -> target cut point
  7161. Int cut; // work
  7162. if (drop>=dn->digits) { // losing the whole thing
  7163. #if DECCHECK
  7164. if (drop>dn->digits)
  7165. printf("decDecap called with drop>digits [%ld>%ld]\n",
  7166. (LI)drop, (LI)dn->digits);
  7167. #endif
  7168. dn->lsu[0]=0;
  7169. dn->digits=1;
  7170. return dn;
  7171. }
  7172. msu=dn->lsu+D2U(dn->digits-drop)-1; // -> likely msu
  7173. cut=MSUDIGITS(dn->digits-drop); // digits to be in use in msu
  7174. if (cut!=DECDPUN) *msu%=powers[cut]; // clear left digits
  7175. // that may have left leading zero digits, so do a proper count...
  7176. dn->digits=decGetDigits(dn->lsu, msu-dn->lsu+1);
  7177. return dn;
  7178. } // decDecap
  7179. /* ------------------------------------------------------------------ */
  7180. /* decBiStr -- compare string with pairwise options */
  7181. /* */
  7182. /* targ is the string to compare */
  7183. /* str1 is one of the strings to compare against (length may be 0) */
  7184. /* str2 is the other; it must be the same length as str1 */
  7185. /* */
  7186. /* returns 1 if strings compare equal, (that is, it is the same */
  7187. /* length as str1 and str2, and each character of targ is in either */
  7188. /* str1 or str2 in the corresponding position), or 0 otherwise */
  7189. /* */
  7190. /* This is used for generic caseless compare, including the awkward */
  7191. /* case of the Turkish dotted and dotless Is. Use as (for example): */
  7192. /* if (decBiStr(test, "mike", "MIKE")) ... */
  7193. /* ------------------------------------------------------------------ */
  7194. static Flag decBiStr(const char *targ, const char *str1, const char *str2) {
  7195. for (;;targ++, str1++, str2++) {
  7196. if (*targ!=*str1 && *targ!=*str2) return 0;
  7197. // *targ has a match in one (or both, if terminator)
  7198. if (*targ=='\0') break;
  7199. } // forever
  7200. return 1;
  7201. } // decBiStr
  7202. /* ------------------------------------------------------------------ */
  7203. /* decNaNs -- handle NaN operand or operands */
  7204. /* */
  7205. /* res is the result number */
  7206. /* lhs is the first operand */
  7207. /* rhs is the second operand, or NULL if none */
  7208. /* context is used to limit payload length */
  7209. /* status contains the current status */
  7210. /* returns res in case convenient */
  7211. /* */
  7212. /* Called when one or both operands is a NaN, and propagates the */
  7213. /* appropriate result to res. When an sNaN is found, it is changed */
  7214. /* to a qNaN and Invalid operation is set. */
  7215. /* ------------------------------------------------------------------ */
  7216. static decNumber * decNaNs(decNumber *res, const decNumber *lhs,
  7217. const decNumber *rhs, decContext *set,
  7218. uInt *status) {
  7219. // This decision tree ends up with LHS being the source pointer,
  7220. // and status updated if need be
  7221. if (lhs->bits & DECSNAN)
  7222. *status|=DEC_Invalid_operation | DEC_sNaN;
  7223. else if (rhs==NULL);
  7224. else if (rhs->bits & DECSNAN) {
  7225. lhs=rhs;
  7226. *status|=DEC_Invalid_operation | DEC_sNaN;
  7227. }
  7228. else if (lhs->bits & DECNAN);
  7229. else lhs=rhs;
  7230. // propagate the payload
  7231. if (lhs->digits<=set->digits) decNumberCopy(res, lhs); // easy
  7232. else { // too long
  7233. const Unit *ul;
  7234. Unit *ur, *uresp1;
  7235. // copy safe number of units, then decapitate
  7236. res->bits=lhs->bits; // need sign etc.
  7237. uresp1=res->lsu+D2U(set->digits);
  7238. for (ur=res->lsu, ul=lhs->lsu; ur<uresp1; ur++, ul++) *ur=*ul;
  7239. res->digits=D2U(set->digits)*DECDPUN;
  7240. // maybe still too long
  7241. if (res->digits>set->digits) decDecap(res, res->digits-set->digits);
  7242. }
  7243. res->bits&=~DECSNAN; // convert any sNaN to NaN, while
  7244. res->bits|=DECNAN; // .. preserving sign
  7245. res->exponent=0; // clean exponent
  7246. // [coefficient was copied/decapitated]
  7247. return res;
  7248. } // decNaNs
  7249. /* ------------------------------------------------------------------ */
  7250. /* decStatus -- apply non-zero status */
  7251. /* */
  7252. /* dn is the number to set if error */
  7253. /* status contains the current status (not yet in context) */
  7254. /* set is the context */
  7255. /* */
  7256. /* If the status is an error status, the number is set to a NaN, */
  7257. /* unless the error was an overflow, divide-by-zero, or underflow, */
  7258. /* in which case the number will have already been set. */
  7259. /* */
  7260. /* The context status is then updated with the new status. Note that */
  7261. /* this may raise a signal, so control may never return from this */
  7262. /* routine (hence resources must be recovered before it is called). */
  7263. /* ------------------------------------------------------------------ */
  7264. static void decStatus(decNumber *dn, uInt status, decContext *set) {
  7265. if (status & DEC_NaNs) { // error status -> NaN
  7266. // if cause was an sNaN, clear and propagate [NaN is already set up]
  7267. if (status & DEC_sNaN) status&=~DEC_sNaN;
  7268. else {
  7269. decNumberZero(dn); // other error: clean throughout
  7270. dn->bits=DECNAN; // and make a quiet NaN
  7271. }
  7272. }
  7273. decContextSetStatus(set, status); // [may not return]
  7274. return;
  7275. } // decStatus
  7276. /* ------------------------------------------------------------------ */
  7277. /* decGetDigits -- count digits in a Units array */
  7278. /* */
  7279. /* uar is the Unit array holding the number (this is often an */
  7280. /* accumulator of some sort) */
  7281. /* len is the length of the array in units [>=1] */
  7282. /* */
  7283. /* returns the number of (significant) digits in the array */
  7284. /* */
  7285. /* All leading zeros are excluded, except the last if the array has */
  7286. /* only zero Units. */
  7287. /* ------------------------------------------------------------------ */
  7288. // This may be called twice during some operations.
  7289. static Int decGetDigits(Unit *uar, Int len) {
  7290. Unit *up=uar+(len-1); // -> msu
  7291. Int digits=(len-1)*DECDPUN+1; // possible digits excluding msu
  7292. #if DECDPUN>4
  7293. uInt const *pow; // work
  7294. #endif
  7295. // (at least 1 in final msu)
  7296. #if DECCHECK
  7297. if (len<1) printf("decGetDigits called with len<1 [%ld]\n", (LI)len);
  7298. #endif
  7299. for (; up>=uar; up--) {
  7300. if (*up==0) { // unit is all 0s
  7301. if (digits==1) break; // a zero has one digit
  7302. digits-=DECDPUN; // adjust for 0 unit
  7303. continue;}
  7304. // found the first (most significant) non-zero Unit
  7305. #if DECDPUN>1 // not done yet
  7306. if (*up<10) break; // is 1-9
  7307. digits++;
  7308. #if DECDPUN>2 // not done yet
  7309. if (*up<100) break; // is 10-99
  7310. digits++;
  7311. #if DECDPUN>3 // not done yet
  7312. if (*up<1000) break; // is 100-999
  7313. digits++;
  7314. #if DECDPUN>4 // count the rest ...
  7315. for (pow=&powers[4]; *up>=*pow; pow++) digits++;
  7316. #endif
  7317. #endif
  7318. #endif
  7319. #endif
  7320. break;
  7321. } // up
  7322. return digits;
  7323. } // decGetDigits
  7324. #if DECTRACE | DECCHECK
  7325. /* ------------------------------------------------------------------ */
  7326. /* decNumberShow -- display a number [debug aid] */
  7327. /* dn is the number to show */
  7328. /* */
  7329. /* Shows: sign, exponent, coefficient (msu first), digits */
  7330. /* or: sign, special-value */
  7331. /* ------------------------------------------------------------------ */
  7332. // this is public so other modules can use it
  7333. void decNumberShow(const decNumber *dn) {
  7334. const Unit *up; // work
  7335. uInt u, d; // ..
  7336. Int cut; // ..
  7337. char isign='+'; // main sign
  7338. if (dn==NULL) {
  7339. printf("NULL\n");
  7340. return;}
  7341. if (decNumberIsNegative(dn)) isign='-';
  7342. printf(" >> %c ", isign);
  7343. if (dn->bits&DECSPECIAL) { // Is a special value
  7344. if (decNumberIsInfinite(dn)) printf("Infinity");
  7345. else { // a NaN
  7346. if (dn->bits&DECSNAN) printf("sNaN"); // signalling NaN
  7347. else printf("NaN");
  7348. }
  7349. // if coefficient and exponent are 0, no more to do
  7350. if (dn->exponent==0 && dn->digits==1 && *dn->lsu==0) {
  7351. printf("\n");
  7352. return;}
  7353. // drop through to report other information
  7354. printf(" ");
  7355. }
  7356. // now carefully display the coefficient
  7357. up=dn->lsu+D2U(dn->digits)-1; // msu
  7358. printf("%ld", (LI)*up);
  7359. for (up=up-1; up>=dn->lsu; up--) {
  7360. u=*up;
  7361. printf(":");
  7362. for (cut=DECDPUN-1; cut>=0; cut--) {
  7363. d=u/powers[cut];
  7364. u-=d*powers[cut];
  7365. printf("%ld", (LI)d);
  7366. } // cut
  7367. } // up
  7368. if (dn->exponent!=0) {
  7369. char esign='+';
  7370. if (dn->exponent<0) esign='-';
  7371. printf(" E%c%ld", esign, (LI)abs(dn->exponent));
  7372. }
  7373. printf(" [%ld]\n", (LI)dn->digits);
  7374. } // decNumberShow
  7375. #endif
  7376. #if DECTRACE || DECCHECK
  7377. /* ------------------------------------------------------------------ */
  7378. /* decDumpAr -- display a unit array [debug/check aid] */
  7379. /* name is a single-character tag name */
  7380. /* ar is the array to display */
  7381. /* len is the length of the array in Units */
  7382. /* ------------------------------------------------------------------ */
  7383. static void decDumpAr(char name, const Unit *ar, Int len) {
  7384. Int i;
  7385. const char *spec;
  7386. #if DECDPUN==9
  7387. spec="%09d ";
  7388. #elif DECDPUN==8
  7389. spec="%08d ";
  7390. #elif DECDPUN==7
  7391. spec="%07d ";
  7392. #elif DECDPUN==6
  7393. spec="%06d ";
  7394. #elif DECDPUN==5
  7395. spec="%05d ";
  7396. #elif DECDPUN==4
  7397. spec="%04d ";
  7398. #elif DECDPUN==3
  7399. spec="%03d ";
  7400. #elif DECDPUN==2
  7401. spec="%02d ";
  7402. #else
  7403. spec="%d ";
  7404. #endif
  7405. printf(" :%c: ", name);
  7406. for (i=len-1; i>=0; i--) {
  7407. if (i==len-1) printf("%ld ", (LI)ar[i]);
  7408. else printf(spec, ar[i]);
  7409. }
  7410. printf("\n");
  7411. return;}
  7412. #endif
  7413. #if DECCHECK
  7414. /* ------------------------------------------------------------------ */
  7415. /* decCheckOperands -- check operand(s) to a routine */
  7416. /* res is the result structure (not checked; it will be set to */
  7417. /* quiet NaN if error found (and it is not NULL)) */
  7418. /* lhs is the first operand (may be DECUNRESU) */
  7419. /* rhs is the second (may be DECUNUSED) */
  7420. /* set is the context (may be DECUNCONT) */
  7421. /* returns 0 if both operands, and the context are clean, or 1 */
  7422. /* otherwise (in which case the context will show an error, */
  7423. /* unless NULL). Note that res is not cleaned; caller should */
  7424. /* handle this so res=NULL case is safe. */
  7425. /* The caller is expected to abandon immediately if 1 is returned. */
  7426. /* ------------------------------------------------------------------ */
  7427. static Flag decCheckOperands(decNumber *res, const decNumber *lhs,
  7428. const decNumber *rhs, decContext *set) {
  7429. Flag bad=0;
  7430. if (set==NULL) { // oops; hopeless
  7431. #if DECTRACE || DECVERB
  7432. printf("Reference to context is NULL.\n");
  7433. #endif
  7434. bad=1;
  7435. return 1;}
  7436. else if (set!=DECUNCONT
  7437. && (set->digits<1 || set->round>=DEC_ROUND_MAX)) {
  7438. bad=1;
  7439. #if DECTRACE || DECVERB
  7440. printf("Bad context [digits=%ld round=%ld].\n",
  7441. (LI)set->digits, (LI)set->round);
  7442. #endif
  7443. }
  7444. else {
  7445. if (res==NULL) {
  7446. bad=1;
  7447. #if DECTRACE
  7448. // this one not DECVERB as standard tests include NULL
  7449. printf("Reference to result is NULL.\n");
  7450. #endif
  7451. }
  7452. if (!bad && lhs!=DECUNUSED) bad=(decCheckNumber(lhs));
  7453. if (!bad && rhs!=DECUNUSED) bad=(decCheckNumber(rhs));
  7454. }
  7455. if (bad) {
  7456. if (set!=DECUNCONT) decContextSetStatus(set, DEC_Invalid_operation);
  7457. if (res!=DECUNRESU && res!=NULL) {
  7458. decNumberZero(res);
  7459. res->bits=DECNAN; // qNaN
  7460. }
  7461. }
  7462. return bad;
  7463. } // decCheckOperands
  7464. /* ------------------------------------------------------------------ */
  7465. /* decCheckNumber -- check a number */
  7466. /* dn is the number to check */
  7467. /* returns 0 if the number is clean, or 1 otherwise */
  7468. /* */
  7469. /* The number is considered valid if it could be a result from some */
  7470. /* operation in some valid context. */
  7471. /* ------------------------------------------------------------------ */
  7472. static Flag decCheckNumber(const decNumber *dn) {
  7473. const Unit *up; // work
  7474. uInt maxuint; // ..
  7475. Int ae, d, digits; // ..
  7476. Int emin, emax; // ..
  7477. if (dn==NULL) { // hopeless
  7478. #if DECTRACE
  7479. // this one not DECVERB as standard tests include NULL
  7480. printf("Reference to decNumber is NULL.\n");
  7481. #endif
  7482. return 1;}
  7483. // check special values
  7484. if (dn->bits & DECSPECIAL) {
  7485. if (dn->exponent!=0) {
  7486. #if DECTRACE || DECVERB
  7487. printf("Exponent %ld (not 0) for a special value [%02x].\n",
  7488. (LI)dn->exponent, dn->bits);
  7489. #endif
  7490. return 1;}
  7491. // 2003.09.08: NaNs may now have coefficients, so next tests Inf only
  7492. if (decNumberIsInfinite(dn)) {
  7493. if (dn->digits!=1) {
  7494. #if DECTRACE || DECVERB
  7495. printf("Digits %ld (not 1) for an infinity.\n", (LI)dn->digits);
  7496. #endif
  7497. return 1;}
  7498. if (*dn->lsu!=0) {
  7499. #if DECTRACE || DECVERB
  7500. printf("LSU %ld (not 0) for an infinity.\n", (LI)*dn->lsu);
  7501. #endif
  7502. decDumpAr('I', dn->lsu, D2U(dn->digits));
  7503. return 1;}
  7504. } // Inf
  7505. // 2002.12.26: negative NaNs can now appear through proposed IEEE
  7506. // concrete formats (decimal64, etc.).
  7507. return 0;
  7508. }
  7509. // check the coefficient
  7510. if (dn->digits<1 || dn->digits>DECNUMMAXP) {
  7511. #if DECTRACE || DECVERB
  7512. printf("Digits %ld in number.\n", (LI)dn->digits);
  7513. #endif
  7514. return 1;}
  7515. d=dn->digits;
  7516. for (up=dn->lsu; d>0; up++) {
  7517. if (d>DECDPUN) maxuint=DECDPUNMAX;
  7518. else { // reached the msu
  7519. maxuint=powers[d]-1;
  7520. if (dn->digits>1 && *up<powers[d-1]) {
  7521. #if DECTRACE || DECVERB
  7522. printf("Leading 0 in number.\n");
  7523. decNumberShow(dn);
  7524. #endif
  7525. return 1;}
  7526. }
  7527. if (*up>maxuint) {
  7528. #if DECTRACE || DECVERB
  7529. printf("Bad Unit [%08lx] in %ld-digit number at offset %ld [maxuint %ld].\n",
  7530. (LI)*up, (LI)dn->digits, (LI)(up-dn->lsu), (LI)maxuint);
  7531. #endif
  7532. return 1;}
  7533. d-=DECDPUN;
  7534. }
  7535. // check the exponent. Note that input operands can have exponents
  7536. // which are out of the set->emin/set->emax and set->digits range
  7537. // (just as they can have more digits than set->digits).
  7538. ae=dn->exponent+dn->digits-1; // adjusted exponent
  7539. emax=DECNUMMAXE;
  7540. emin=DECNUMMINE;
  7541. digits=DECNUMMAXP;
  7542. if (ae<emin-(digits-1)) {
  7543. #if DECTRACE || DECVERB
  7544. printf("Adjusted exponent underflow [%ld].\n", (LI)ae);
  7545. decNumberShow(dn);
  7546. #endif
  7547. return 1;}
  7548. if (ae>+emax) {
  7549. #if DECTRACE || DECVERB
  7550. printf("Adjusted exponent overflow [%ld].\n", (LI)ae);
  7551. decNumberShow(dn);
  7552. #endif
  7553. return 1;}
  7554. return 0; // it's OK
  7555. } // decCheckNumber
  7556. /* ------------------------------------------------------------------ */
  7557. /* decCheckInexact -- check a normal finite inexact result has digits */
  7558. /* dn is the number to check */
  7559. /* set is the context (for status and precision) */
  7560. /* sets Invalid operation, etc., if some digits are missing */
  7561. /* [this check is not made for DECSUBSET compilation or when */
  7562. /* subnormal is not set] */
  7563. /* ------------------------------------------------------------------ */
  7564. static void decCheckInexact(const decNumber *dn, decContext *set) {
  7565. #if !DECSUBSET && DECEXTFLAG
  7566. if ((set->status & (DEC_Inexact|DEC_Subnormal))==DEC_Inexact
  7567. && (set->digits!=dn->digits) && !(dn->bits & DECSPECIAL)) {
  7568. #if DECTRACE || DECVERB
  7569. printf("Insufficient digits [%ld] on normal Inexact result.\n",
  7570. (LI)dn->digits);
  7571. decNumberShow(dn);
  7572. #endif
  7573. decContextSetStatus(set, DEC_Invalid_operation);
  7574. }
  7575. #else
  7576. // next is a noop for quiet compiler
  7577. if (dn!=NULL && dn->digits==0) set->status|=DEC_Invalid_operation;
  7578. #endif
  7579. return;
  7580. } // decCheckInexact
  7581. #endif
  7582. #if DECALLOC
  7583. #undef malloc
  7584. #undef free
  7585. /* ------------------------------------------------------------------ */
  7586. /* decMalloc -- accountable allocation routine */
  7587. /* n is the number of bytes to allocate */
  7588. /* */
  7589. /* Semantics is the same as the stdlib malloc routine, but bytes */
  7590. /* allocated are accounted for globally, and corruption fences are */
  7591. /* added before and after the 'actual' storage. */
  7592. /* ------------------------------------------------------------------ */
  7593. /* This routine allocates storage with an extra twelve bytes; 8 are */
  7594. /* at the start and hold: */
  7595. /* 0-3 the original length requested */
  7596. /* 4-7 buffer corruption detection fence (DECFENCE, x4) */
  7597. /* The 4 bytes at the end also hold a corruption fence (DECFENCE, x4) */
  7598. /* ------------------------------------------------------------------ */
  7599. static void *decMalloc(size_t n) {
  7600. uInt size=n+12; // true size
  7601. void *alloc; // -> allocated storage
  7602. uByte *b, *b0; // work
  7603. uInt uiwork; // for macros
  7604. alloc=malloc(size); // -> allocated storage
  7605. if (alloc==NULL) return NULL; // out of strorage
  7606. b0=(uByte *)alloc; // as bytes
  7607. decAllocBytes+=n; // account for storage
  7608. UBFROMUI(alloc, n); // save n
  7609. // printf(" alloc ++ dAB: %ld (%ld)\n", (LI)decAllocBytes, (LI)n);
  7610. for (b=b0+4; b<b0+8; b++) *b=DECFENCE;
  7611. for (b=b0+n+8; b<b0+n+12; b++) *b=DECFENCE;
  7612. return b0+8; // -> play area
  7613. } // decMalloc
  7614. /* ------------------------------------------------------------------ */
  7615. /* decFree -- accountable free routine */
  7616. /* alloc is the storage to free */
  7617. /* */
  7618. /* Semantics is the same as the stdlib malloc routine, except that */
  7619. /* the global storage accounting is updated and the fences are */
  7620. /* checked to ensure that no routine has written 'out of bounds'. */
  7621. /* ------------------------------------------------------------------ */
  7622. /* This routine first checks that the fences have not been corrupted. */
  7623. /* It then frees the storage using the 'truw' storage address (that */
  7624. /* is, offset by 8). */
  7625. /* ------------------------------------------------------------------ */
  7626. static void decFree(void *alloc) {
  7627. uInt n; // original length
  7628. uByte *b, *b0; // work
  7629. uInt uiwork; // for macros
  7630. if (alloc==NULL) return; // allowed; it's a nop
  7631. b0=(uByte *)alloc; // as bytes
  7632. b0-=8; // -> true start of storage
  7633. n=UBTOUI(b0); // lift length
  7634. for (b=b0+4; b<b0+8; b++) if (*b!=DECFENCE)
  7635. printf("=== Corrupt byte [%02x] at offset %d from %ld ===\n", *b,
  7636. b-b0-8, (LI)b0);
  7637. for (b=b0+n+8; b<b0+n+12; b++) if (*b!=DECFENCE)
  7638. printf("=== Corrupt byte [%02x] at offset +%d from %ld, n=%ld ===\n", *b,
  7639. b-b0-8, (LI)b0, (LI)n);
  7640. free(b0); // drop the storage
  7641. decAllocBytes-=n; // account for storage
  7642. // printf(" free -- dAB: %d (%d)\n", decAllocBytes, -n);
  7643. } // decFree
  7644. #define malloc(a) decMalloc(a)
  7645. #define free(a) decFree(a)
  7646. #endif