decimal.js 131 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877
  1. ;(function (globalScope) {
  2. 'use strict';
  3. /*
  4. * decimal.js v10.2.1
  5. * An arbitrary-precision Decimal type for JavaScript.
  6. * https://github.com/MikeMcl/decimal.js
  7. * Copyright (c) 2020 Michael Mclaughlin <M8ch88l@gmail.com>
  8. * MIT Licence
  9. */
  10. // ----------------------------------- EDITABLE DEFAULTS ------------------------------------ //
  11. // The maximum exponent magnitude.
  12. // The limit on the value of `toExpNeg`, `toExpPos`, `minE` and `maxE`.
  13. var EXP_LIMIT = 9e15, // 0 to 9e15
  14. // The limit on the value of `precision`, and on the value of the first argument to
  15. // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`.
  16. MAX_DIGITS = 1e9, // 0 to 1e9
  17. // Base conversion alphabet.
  18. NUMERALS = '0123456789abcdef',
  19. // The natural logarithm of 10 (1025 digits).
  20. LN10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058',
  21. // Pi (1025 digits).
  22. PI = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789',
  23. // The initial configuration properties of the Decimal constructor.
  24. DEFAULTS = {
  25. // These values must be integers within the stated ranges (inclusive).
  26. // Most of these values can be changed at run-time using the `Decimal.config` method.
  27. // The maximum number of significant digits of the result of a calculation or base conversion.
  28. // E.g. `Decimal.config({ precision: 20 });`
  29. precision: 20, // 1 to MAX_DIGITS
  30. // The rounding mode used when rounding to `precision`.
  31. //
  32. // ROUND_UP 0 Away from zero.
  33. // ROUND_DOWN 1 Towards zero.
  34. // ROUND_CEIL 2 Towards +Infinity.
  35. // ROUND_FLOOR 3 Towards -Infinity.
  36. // ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up.
  37. // ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
  38. // ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
  39. // ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
  40. // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
  41. //
  42. // E.g.
  43. // `Decimal.rounding = 4;`
  44. // `Decimal.rounding = Decimal.ROUND_HALF_UP;`
  45. rounding: 4, // 0 to 8
  46. // The modulo mode used when calculating the modulus: a mod n.
  47. // The quotient (q = a / n) is calculated according to the corresponding rounding mode.
  48. // The remainder (r) is calculated as: r = a - n * q.
  49. //
  50. // UP 0 The remainder is positive if the dividend is negative, else is negative.
  51. // DOWN 1 The remainder has the same sign as the dividend (JavaScript %).
  52. // FLOOR 3 The remainder has the same sign as the divisor (Python %).
  53. // HALF_EVEN 6 The IEEE 754 remainder function.
  54. // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). Always positive.
  55. //
  56. // Truncated division (1), floored division (3), the IEEE 754 remainder (6), and Euclidian
  57. // division (9) are commonly used for the modulus operation. The other rounding modes can also
  58. // be used, but they may not give useful results.
  59. modulo: 1, // 0 to 9
  60. // The exponent value at and beneath which `toString` returns exponential notation.
  61. // JavaScript numbers: -7
  62. toExpNeg: -7, // 0 to -EXP_LIMIT
  63. // The exponent value at and above which `toString` returns exponential notation.
  64. // JavaScript numbers: 21
  65. toExpPos: 21, // 0 to EXP_LIMIT
  66. // The minimum exponent value, beneath which underflow to zero occurs.
  67. // JavaScript numbers: -324 (5e-324)
  68. minE: -EXP_LIMIT, // -1 to -EXP_LIMIT
  69. // The maximum exponent value, above which overflow to Infinity occurs.
  70. // JavaScript numbers: 308 (1.7976931348623157e+308)
  71. maxE: EXP_LIMIT, // 1 to EXP_LIMIT
  72. // Whether to use cryptographically-secure random number generation, if available.
  73. crypto: false // true/false
  74. },
  75. // ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- //
  76. Decimal, inexact, noConflict, quadrant,
  77. external = true,
  78. decimalError = '[DecimalError] ',
  79. invalidArgument = decimalError + 'Invalid argument: ',
  80. precisionLimitExceeded = decimalError + 'Precision limit exceeded',
  81. cryptoUnavailable = decimalError + 'crypto unavailable',
  82. mathfloor = Math.floor,
  83. mathpow = Math.pow,
  84. isBinary = /^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,
  85. isHex = /^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,
  86. isOctal = /^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,
  87. isDecimal = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
  88. BASE = 1e7,
  89. LOG_BASE = 7,
  90. MAX_SAFE_INTEGER = 9007199254740991,
  91. LN10_PRECISION = LN10.length - 1,
  92. PI_PRECISION = PI.length - 1,
  93. // Decimal.prototype object
  94. P = { name: '[object Decimal]' };
  95. // Decimal prototype methods
  96. /*
  97. * absoluteValue abs
  98. * ceil
  99. * comparedTo cmp
  100. * cosine cos
  101. * cubeRoot cbrt
  102. * decimalPlaces dp
  103. * dividedBy div
  104. * dividedToIntegerBy divToInt
  105. * equals eq
  106. * floor
  107. * greaterThan gt
  108. * greaterThanOrEqualTo gte
  109. * hyperbolicCosine cosh
  110. * hyperbolicSine sinh
  111. * hyperbolicTangent tanh
  112. * inverseCosine acos
  113. * inverseHyperbolicCosine acosh
  114. * inverseHyperbolicSine asinh
  115. * inverseHyperbolicTangent atanh
  116. * inverseSine asin
  117. * inverseTangent atan
  118. * isFinite
  119. * isInteger isInt
  120. * isNaN
  121. * isNegative isNeg
  122. * isPositive isPos
  123. * isZero
  124. * lessThan lt
  125. * lessThanOrEqualTo lte
  126. * logarithm log
  127. * [maximum] [max]
  128. * [minimum] [min]
  129. * minus sub
  130. * modulo mod
  131. * naturalExponential exp
  132. * naturalLogarithm ln
  133. * negated neg
  134. * plus add
  135. * precision sd
  136. * round
  137. * sine sin
  138. * squareRoot sqrt
  139. * tangent tan
  140. * times mul
  141. * toBinary
  142. * toDecimalPlaces toDP
  143. * toExponential
  144. * toFixed
  145. * toFraction
  146. * toHexadecimal toHex
  147. * toNearest
  148. * toNumber
  149. * toOctal
  150. * toPower pow
  151. * toPrecision
  152. * toSignificantDigits toSD
  153. * toString
  154. * truncated trunc
  155. * valueOf toJSON
  156. */
  157. /*
  158. * Return a new Decimal whose value is the absolute value of this Decimal.
  159. *
  160. */
  161. P.absoluteValue = P.abs = function () {
  162. var x = new this.constructor(this);
  163. if (x.s < 0) x.s = 1;
  164. return finalise(x);
  165. };
  166. /*
  167. * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the
  168. * direction of positive Infinity.
  169. *
  170. */
  171. P.ceil = function () {
  172. return finalise(new this.constructor(this), this.e + 1, 2);
  173. };
  174. /*
  175. * Return
  176. * 1 if the value of this Decimal is greater than the value of `y`,
  177. * -1 if the value of this Decimal is less than the value of `y`,
  178. * 0 if they have the same value,
  179. * NaN if the value of either Decimal is NaN.
  180. *
  181. */
  182. P.comparedTo = P.cmp = function (y) {
  183. var i, j, xdL, ydL,
  184. x = this,
  185. xd = x.d,
  186. yd = (y = new x.constructor(y)).d,
  187. xs = x.s,
  188. ys = y.s;
  189. // Either NaN or ±Infinity?
  190. if (!xd || !yd) {
  191. return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1;
  192. }
  193. // Either zero?
  194. if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0;
  195. // Signs differ?
  196. if (xs !== ys) return xs;
  197. // Compare exponents.
  198. if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1;
  199. xdL = xd.length;
  200. ydL = yd.length;
  201. // Compare digit by digit.
  202. for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) {
  203. if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1;
  204. }
  205. // Compare lengths.
  206. return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1;
  207. };
  208. /*
  209. * Return a new Decimal whose value is the cosine of the value in radians of this Decimal.
  210. *
  211. * Domain: [-Infinity, Infinity]
  212. * Range: [-1, 1]
  213. *
  214. * cos(0) = 1
  215. * cos(-0) = 1
  216. * cos(Infinity) = NaN
  217. * cos(-Infinity) = NaN
  218. * cos(NaN) = NaN
  219. *
  220. */
  221. P.cosine = P.cos = function () {
  222. var pr, rm,
  223. x = this,
  224. Ctor = x.constructor;
  225. if (!x.d) return new Ctor(NaN);
  226. // cos(0) = cos(-0) = 1
  227. if (!x.d[0]) return new Ctor(1);
  228. pr = Ctor.precision;
  229. rm = Ctor.rounding;
  230. Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;
  231. Ctor.rounding = 1;
  232. x = cosine(Ctor, toLessThanHalfPi(Ctor, x));
  233. Ctor.precision = pr;
  234. Ctor.rounding = rm;
  235. return finalise(quadrant == 2 || quadrant == 3 ? x.neg() : x, pr, rm, true);
  236. };
  237. /*
  238. *
  239. * Return a new Decimal whose value is the cube root of the value of this Decimal, rounded to
  240. * `precision` significant digits using rounding mode `rounding`.
  241. *
  242. * cbrt(0) = 0
  243. * cbrt(-0) = -0
  244. * cbrt(1) = 1
  245. * cbrt(-1) = -1
  246. * cbrt(N) = N
  247. * cbrt(-I) = -I
  248. * cbrt(I) = I
  249. *
  250. * Math.cbrt(x) = (x < 0 ? -Math.pow(-x, 1/3) : Math.pow(x, 1/3))
  251. *
  252. */
  253. P.cubeRoot = P.cbrt = function () {
  254. var e, m, n, r, rep, s, sd, t, t3, t3plusx,
  255. x = this,
  256. Ctor = x.constructor;
  257. if (!x.isFinite() || x.isZero()) return new Ctor(x);
  258. external = false;
  259. // Initial estimate.
  260. s = x.s * mathpow(x.s * x, 1 / 3);
  261. // Math.cbrt underflow/overflow?
  262. // Pass x to Math.pow as integer, then adjust the exponent of the result.
  263. if (!s || Math.abs(s) == 1 / 0) {
  264. n = digitsToString(x.d);
  265. e = x.e;
  266. // Adjust n exponent so it is a multiple of 3 away from x exponent.
  267. if (s = (e - n.length + 1) % 3) n += (s == 1 || s == -2 ? '0' : '00');
  268. s = mathpow(n, 1 / 3);
  269. // Rarely, e may be one less than the result exponent value.
  270. e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2));
  271. if (s == 1 / 0) {
  272. n = '5e' + e;
  273. } else {
  274. n = s.toExponential();
  275. n = n.slice(0, n.indexOf('e') + 1) + e;
  276. }
  277. r = new Ctor(n);
  278. r.s = x.s;
  279. } else {
  280. r = new Ctor(s.toString());
  281. }
  282. sd = (e = Ctor.precision) + 3;
  283. // Halley's method.
  284. // TODO? Compare Newton's method.
  285. for (;;) {
  286. t = r;
  287. t3 = t.times(t).times(t);
  288. t3plusx = t3.plus(x);
  289. r = divide(t3plusx.plus(x).times(t), t3plusx.plus(t3), sd + 2, 1);
  290. // TODO? Replace with for-loop and checkRoundingDigits.
  291. if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {
  292. n = n.slice(sd - 3, sd + 1);
  293. // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or 4999
  294. // , i.e. approaching a rounding boundary, continue the iteration.
  295. if (n == '9999' || !rep && n == '4999') {
  296. // On the first iteration only, check to see if rounding up gives the exact result as the
  297. // nines may infinitely repeat.
  298. if (!rep) {
  299. finalise(t, e + 1, 0);
  300. if (t.times(t).times(t).eq(x)) {
  301. r = t;
  302. break;
  303. }
  304. }
  305. sd += 4;
  306. rep = 1;
  307. } else {
  308. // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.
  309. // If not, then there are further digits and m will be truthy.
  310. if (!+n || !+n.slice(1) && n.charAt(0) == '5') {
  311. // Truncate to the first rounding digit.
  312. finalise(r, e + 1, 1);
  313. m = !r.times(r).times(r).eq(x);
  314. }
  315. break;
  316. }
  317. }
  318. }
  319. external = true;
  320. return finalise(r, e, Ctor.rounding, m);
  321. };
  322. /*
  323. * Return the number of decimal places of the value of this Decimal.
  324. *
  325. */
  326. P.decimalPlaces = P.dp = function () {
  327. var w,
  328. d = this.d,
  329. n = NaN;
  330. if (d) {
  331. w = d.length - 1;
  332. n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE;
  333. // Subtract the number of trailing zeros of the last word.
  334. w = d[w];
  335. if (w) for (; w % 10 == 0; w /= 10) n--;
  336. if (n < 0) n = 0;
  337. }
  338. return n;
  339. };
  340. /*
  341. * n / 0 = I
  342. * n / N = N
  343. * n / I = 0
  344. * 0 / n = 0
  345. * 0 / 0 = N
  346. * 0 / N = N
  347. * 0 / I = 0
  348. * N / n = N
  349. * N / 0 = N
  350. * N / N = N
  351. * N / I = N
  352. * I / n = I
  353. * I / 0 = I
  354. * I / N = N
  355. * I / I = N
  356. *
  357. * Return a new Decimal whose value is the value of this Decimal divided by `y`, rounded to
  358. * `precision` significant digits using rounding mode `rounding`.
  359. *
  360. */
  361. P.dividedBy = P.div = function (y) {
  362. return divide(this, new this.constructor(y));
  363. };
  364. /*
  365. * Return a new Decimal whose value is the integer part of dividing the value of this Decimal
  366. * by the value of `y`, rounded to `precision` significant digits using rounding mode `rounding`.
  367. *
  368. */
  369. P.dividedToIntegerBy = P.divToInt = function (y) {
  370. var x = this,
  371. Ctor = x.constructor;
  372. return finalise(divide(x, new Ctor(y), 0, 1, 1), Ctor.precision, Ctor.rounding);
  373. };
  374. /*
  375. * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false.
  376. *
  377. */
  378. P.equals = P.eq = function (y) {
  379. return this.cmp(y) === 0;
  380. };
  381. /*
  382. * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the
  383. * direction of negative Infinity.
  384. *
  385. */
  386. P.floor = function () {
  387. return finalise(new this.constructor(this), this.e + 1, 3);
  388. };
  389. /*
  390. * Return true if the value of this Decimal is greater than the value of `y`, otherwise return
  391. * false.
  392. *
  393. */
  394. P.greaterThan = P.gt = function (y) {
  395. return this.cmp(y) > 0;
  396. };
  397. /*
  398. * Return true if the value of this Decimal is greater than or equal to the value of `y`,
  399. * otherwise return false.
  400. *
  401. */
  402. P.greaterThanOrEqualTo = P.gte = function (y) {
  403. var k = this.cmp(y);
  404. return k == 1 || k === 0;
  405. };
  406. /*
  407. * Return a new Decimal whose value is the hyperbolic cosine of the value in radians of this
  408. * Decimal.
  409. *
  410. * Domain: [-Infinity, Infinity]
  411. * Range: [1, Infinity]
  412. *
  413. * cosh(x) = 1 + x^2/2! + x^4/4! + x^6/6! + ...
  414. *
  415. * cosh(0) = 1
  416. * cosh(-0) = 1
  417. * cosh(Infinity) = Infinity
  418. * cosh(-Infinity) = Infinity
  419. * cosh(NaN) = NaN
  420. *
  421. * x time taken (ms) result
  422. * 1000 9 9.8503555700852349694e+433
  423. * 10000 25 4.4034091128314607936e+4342
  424. * 100000 171 1.4033316802130615897e+43429
  425. * 1000000 3817 1.5166076984010437725e+434294
  426. * 10000000 abandoned after 2 minute wait
  427. *
  428. * TODO? Compare performance of cosh(x) = 0.5 * (exp(x) + exp(-x))
  429. *
  430. */
  431. P.hyperbolicCosine = P.cosh = function () {
  432. var k, n, pr, rm, len,
  433. x = this,
  434. Ctor = x.constructor,
  435. one = new Ctor(1);
  436. if (!x.isFinite()) return new Ctor(x.s ? 1 / 0 : NaN);
  437. if (x.isZero()) return one;
  438. pr = Ctor.precision;
  439. rm = Ctor.rounding;
  440. Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;
  441. Ctor.rounding = 1;
  442. len = x.d.length;
  443. // Argument reduction: cos(4x) = 1 - 8cos^2(x) + 8cos^4(x) + 1
  444. // i.e. cos(x) = 1 - cos^2(x/4)(8 - 8cos^2(x/4))
  445. // Estimate the optimum number of times to use the argument reduction.
  446. // TODO? Estimation reused from cosine() and may not be optimal here.
  447. if (len < 32) {
  448. k = Math.ceil(len / 3);
  449. n = (1 / tinyPow(4, k)).toString();
  450. } else {
  451. k = 16;
  452. n = '2.3283064365386962890625e-10';
  453. }
  454. x = taylorSeries(Ctor, 1, x.times(n), new Ctor(1), true);
  455. // Reverse argument reduction
  456. var cosh2_x,
  457. i = k,
  458. d8 = new Ctor(8);
  459. for (; i--;) {
  460. cosh2_x = x.times(x);
  461. x = one.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8))));
  462. }
  463. return finalise(x, Ctor.precision = pr, Ctor.rounding = rm, true);
  464. };
  465. /*
  466. * Return a new Decimal whose value is the hyperbolic sine of the value in radians of this
  467. * Decimal.
  468. *
  469. * Domain: [-Infinity, Infinity]
  470. * Range: [-Infinity, Infinity]
  471. *
  472. * sinh(x) = x + x^3/3! + x^5/5! + x^7/7! + ...
  473. *
  474. * sinh(0) = 0
  475. * sinh(-0) = -0
  476. * sinh(Infinity) = Infinity
  477. * sinh(-Infinity) = -Infinity
  478. * sinh(NaN) = NaN
  479. *
  480. * x time taken (ms)
  481. * 10 2 ms
  482. * 100 5 ms
  483. * 1000 14 ms
  484. * 10000 82 ms
  485. * 100000 886 ms 1.4033316802130615897e+43429
  486. * 200000 2613 ms
  487. * 300000 5407 ms
  488. * 400000 8824 ms
  489. * 500000 13026 ms 8.7080643612718084129e+217146
  490. * 1000000 48543 ms
  491. *
  492. * TODO? Compare performance of sinh(x) = 0.5 * (exp(x) - exp(-x))
  493. *
  494. */
  495. P.hyperbolicSine = P.sinh = function () {
  496. var k, pr, rm, len,
  497. x = this,
  498. Ctor = x.constructor;
  499. if (!x.isFinite() || x.isZero()) return new Ctor(x);
  500. pr = Ctor.precision;
  501. rm = Ctor.rounding;
  502. Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;
  503. Ctor.rounding = 1;
  504. len = x.d.length;
  505. if (len < 3) {
  506. x = taylorSeries(Ctor, 2, x, x, true);
  507. } else {
  508. // Alternative argument reduction: sinh(3x) = sinh(x)(3 + 4sinh^2(x))
  509. // i.e. sinh(x) = sinh(x/3)(3 + 4sinh^2(x/3))
  510. // 3 multiplications and 1 addition
  511. // Argument reduction: sinh(5x) = sinh(x)(5 + sinh^2(x)(20 + 16sinh^2(x)))
  512. // i.e. sinh(x) = sinh(x/5)(5 + sinh^2(x/5)(20 + 16sinh^2(x/5)))
  513. // 4 multiplications and 2 additions
  514. // Estimate the optimum number of times to use the argument reduction.
  515. k = 1.4 * Math.sqrt(len);
  516. k = k > 16 ? 16 : k | 0;
  517. x = x.times(1 / tinyPow(5, k));
  518. x = taylorSeries(Ctor, 2, x, x, true);
  519. // Reverse argument reduction
  520. var sinh2_x,
  521. d5 = new Ctor(5),
  522. d16 = new Ctor(16),
  523. d20 = new Ctor(20);
  524. for (; k--;) {
  525. sinh2_x = x.times(x);
  526. x = x.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20))));
  527. }
  528. }
  529. Ctor.precision = pr;
  530. Ctor.rounding = rm;
  531. return finalise(x, pr, rm, true);
  532. };
  533. /*
  534. * Return a new Decimal whose value is the hyperbolic tangent of the value in radians of this
  535. * Decimal.
  536. *
  537. * Domain: [-Infinity, Infinity]
  538. * Range: [-1, 1]
  539. *
  540. * tanh(x) = sinh(x) / cosh(x)
  541. *
  542. * tanh(0) = 0
  543. * tanh(-0) = -0
  544. * tanh(Infinity) = 1
  545. * tanh(-Infinity) = -1
  546. * tanh(NaN) = NaN
  547. *
  548. */
  549. P.hyperbolicTangent = P.tanh = function () {
  550. var pr, rm,
  551. x = this,
  552. Ctor = x.constructor;
  553. if (!x.isFinite()) return new Ctor(x.s);
  554. if (x.isZero()) return new Ctor(x);
  555. pr = Ctor.precision;
  556. rm = Ctor.rounding;
  557. Ctor.precision = pr + 7;
  558. Ctor.rounding = 1;
  559. return divide(x.sinh(), x.cosh(), Ctor.precision = pr, Ctor.rounding = rm);
  560. };
  561. /*
  562. * Return a new Decimal whose value is the arccosine (inverse cosine) in radians of the value of
  563. * this Decimal.
  564. *
  565. * Domain: [-1, 1]
  566. * Range: [0, pi]
  567. *
  568. * acos(x) = pi/2 - asin(x)
  569. *
  570. * acos(0) = pi/2
  571. * acos(-0) = pi/2
  572. * acos(1) = 0
  573. * acos(-1) = pi
  574. * acos(1/2) = pi/3
  575. * acos(-1/2) = 2*pi/3
  576. * acos(|x| > 1) = NaN
  577. * acos(NaN) = NaN
  578. *
  579. */
  580. P.inverseCosine = P.acos = function () {
  581. var halfPi,
  582. x = this,
  583. Ctor = x.constructor,
  584. k = x.abs().cmp(1),
  585. pr = Ctor.precision,
  586. rm = Ctor.rounding;
  587. if (k !== -1) {
  588. return k === 0
  589. // |x| is 1
  590. ? x.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0)
  591. // |x| > 1 or x is NaN
  592. : new Ctor(NaN);
  593. }
  594. if (x.isZero()) return getPi(Ctor, pr + 4, rm).times(0.5);
  595. // TODO? Special case acos(0.5) = pi/3 and acos(-0.5) = 2*pi/3
  596. Ctor.precision = pr + 6;
  597. Ctor.rounding = 1;
  598. x = x.asin();
  599. halfPi = getPi(Ctor, pr + 4, rm).times(0.5);
  600. Ctor.precision = pr;
  601. Ctor.rounding = rm;
  602. return halfPi.minus(x);
  603. };
  604. /*
  605. * Return a new Decimal whose value is the inverse of the hyperbolic cosine in radians of the
  606. * value of this Decimal.
  607. *
  608. * Domain: [1, Infinity]
  609. * Range: [0, Infinity]
  610. *
  611. * acosh(x) = ln(x + sqrt(x^2 - 1))
  612. *
  613. * acosh(x < 1) = NaN
  614. * acosh(NaN) = NaN
  615. * acosh(Infinity) = Infinity
  616. * acosh(-Infinity) = NaN
  617. * acosh(0) = NaN
  618. * acosh(-0) = NaN
  619. * acosh(1) = 0
  620. * acosh(-1) = NaN
  621. *
  622. */
  623. P.inverseHyperbolicCosine = P.acosh = function () {
  624. var pr, rm,
  625. x = this,
  626. Ctor = x.constructor;
  627. if (x.lte(1)) return new Ctor(x.eq(1) ? 0 : NaN);
  628. if (!x.isFinite()) return new Ctor(x);
  629. pr = Ctor.precision;
  630. rm = Ctor.rounding;
  631. Ctor.precision = pr + Math.max(Math.abs(x.e), x.sd()) + 4;
  632. Ctor.rounding = 1;
  633. external = false;
  634. x = x.times(x).minus(1).sqrt().plus(x);
  635. external = true;
  636. Ctor.precision = pr;
  637. Ctor.rounding = rm;
  638. return x.ln();
  639. };
  640. /*
  641. * Return a new Decimal whose value is the inverse of the hyperbolic sine in radians of the value
  642. * of this Decimal.
  643. *
  644. * Domain: [-Infinity, Infinity]
  645. * Range: [-Infinity, Infinity]
  646. *
  647. * asinh(x) = ln(x + sqrt(x^2 + 1))
  648. *
  649. * asinh(NaN) = NaN
  650. * asinh(Infinity) = Infinity
  651. * asinh(-Infinity) = -Infinity
  652. * asinh(0) = 0
  653. * asinh(-0) = -0
  654. *
  655. */
  656. P.inverseHyperbolicSine = P.asinh = function () {
  657. var pr, rm,
  658. x = this,
  659. Ctor = x.constructor;
  660. if (!x.isFinite() || x.isZero()) return new Ctor(x);
  661. pr = Ctor.precision;
  662. rm = Ctor.rounding;
  663. Ctor.precision = pr + 2 * Math.max(Math.abs(x.e), x.sd()) + 6;
  664. Ctor.rounding = 1;
  665. external = false;
  666. x = x.times(x).plus(1).sqrt().plus(x);
  667. external = true;
  668. Ctor.precision = pr;
  669. Ctor.rounding = rm;
  670. return x.ln();
  671. };
  672. /*
  673. * Return a new Decimal whose value is the inverse of the hyperbolic tangent in radians of the
  674. * value of this Decimal.
  675. *
  676. * Domain: [-1, 1]
  677. * Range: [-Infinity, Infinity]
  678. *
  679. * atanh(x) = 0.5 * ln((1 + x) / (1 - x))
  680. *
  681. * atanh(|x| > 1) = NaN
  682. * atanh(NaN) = NaN
  683. * atanh(Infinity) = NaN
  684. * atanh(-Infinity) = NaN
  685. * atanh(0) = 0
  686. * atanh(-0) = -0
  687. * atanh(1) = Infinity
  688. * atanh(-1) = -Infinity
  689. *
  690. */
  691. P.inverseHyperbolicTangent = P.atanh = function () {
  692. var pr, rm, wpr, xsd,
  693. x = this,
  694. Ctor = x.constructor;
  695. if (!x.isFinite()) return new Ctor(NaN);
  696. if (x.e >= 0) return new Ctor(x.abs().eq(1) ? x.s / 0 : x.isZero() ? x : NaN);
  697. pr = Ctor.precision;
  698. rm = Ctor.rounding;
  699. xsd = x.sd();
  700. if (Math.max(xsd, pr) < 2 * -x.e - 1) return finalise(new Ctor(x), pr, rm, true);
  701. Ctor.precision = wpr = xsd - x.e;
  702. x = divide(x.plus(1), new Ctor(1).minus(x), wpr + pr, 1);
  703. Ctor.precision = pr + 4;
  704. Ctor.rounding = 1;
  705. x = x.ln();
  706. Ctor.precision = pr;
  707. Ctor.rounding = rm;
  708. return x.times(0.5);
  709. };
  710. /*
  711. * Return a new Decimal whose value is the arcsine (inverse sine) in radians of the value of this
  712. * Decimal.
  713. *
  714. * Domain: [-Infinity, Infinity]
  715. * Range: [-pi/2, pi/2]
  716. *
  717. * asin(x) = 2*atan(x/(1 + sqrt(1 - x^2)))
  718. *
  719. * asin(0) = 0
  720. * asin(-0) = -0
  721. * asin(1/2) = pi/6
  722. * asin(-1/2) = -pi/6
  723. * asin(1) = pi/2
  724. * asin(-1) = -pi/2
  725. * asin(|x| > 1) = NaN
  726. * asin(NaN) = NaN
  727. *
  728. * TODO? Compare performance of Taylor series.
  729. *
  730. */
  731. P.inverseSine = P.asin = function () {
  732. var halfPi, k,
  733. pr, rm,
  734. x = this,
  735. Ctor = x.constructor;
  736. if (x.isZero()) return new Ctor(x);
  737. k = x.abs().cmp(1);
  738. pr = Ctor.precision;
  739. rm = Ctor.rounding;
  740. if (k !== -1) {
  741. // |x| is 1
  742. if (k === 0) {
  743. halfPi = getPi(Ctor, pr + 4, rm).times(0.5);
  744. halfPi.s = x.s;
  745. return halfPi;
  746. }
  747. // |x| > 1 or x is NaN
  748. return new Ctor(NaN);
  749. }
  750. // TODO? Special case asin(1/2) = pi/6 and asin(-1/2) = -pi/6
  751. Ctor.precision = pr + 6;
  752. Ctor.rounding = 1;
  753. x = x.div(new Ctor(1).minus(x.times(x)).sqrt().plus(1)).atan();
  754. Ctor.precision = pr;
  755. Ctor.rounding = rm;
  756. return x.times(2);
  757. };
  758. /*
  759. * Return a new Decimal whose value is the arctangent (inverse tangent) in radians of the value
  760. * of this Decimal.
  761. *
  762. * Domain: [-Infinity, Infinity]
  763. * Range: [-pi/2, pi/2]
  764. *
  765. * atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...
  766. *
  767. * atan(0) = 0
  768. * atan(-0) = -0
  769. * atan(1) = pi/4
  770. * atan(-1) = -pi/4
  771. * atan(Infinity) = pi/2
  772. * atan(-Infinity) = -pi/2
  773. * atan(NaN) = NaN
  774. *
  775. */
  776. P.inverseTangent = P.atan = function () {
  777. var i, j, k, n, px, t, r, wpr, x2,
  778. x = this,
  779. Ctor = x.constructor,
  780. pr = Ctor.precision,
  781. rm = Ctor.rounding;
  782. if (!x.isFinite()) {
  783. if (!x.s) return new Ctor(NaN);
  784. if (pr + 4 <= PI_PRECISION) {
  785. r = getPi(Ctor, pr + 4, rm).times(0.5);
  786. r.s = x.s;
  787. return r;
  788. }
  789. } else if (x.isZero()) {
  790. return new Ctor(x);
  791. } else if (x.abs().eq(1) && pr + 4 <= PI_PRECISION) {
  792. r = getPi(Ctor, pr + 4, rm).times(0.25);
  793. r.s = x.s;
  794. return r;
  795. }
  796. Ctor.precision = wpr = pr + 10;
  797. Ctor.rounding = 1;
  798. // TODO? if (x >= 1 && pr <= PI_PRECISION) atan(x) = halfPi * x.s - atan(1 / x);
  799. // Argument reduction
  800. // Ensure |x| < 0.42
  801. // atan(x) = 2 * atan(x / (1 + sqrt(1 + x^2)))
  802. k = Math.min(28, wpr / LOG_BASE + 2 | 0);
  803. for (i = k; i; --i) x = x.div(x.times(x).plus(1).sqrt().plus(1));
  804. external = false;
  805. j = Math.ceil(wpr / LOG_BASE);
  806. n = 1;
  807. x2 = x.times(x);
  808. r = new Ctor(x);
  809. px = x;
  810. // atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...
  811. for (; i !== -1;) {
  812. px = px.times(x2);
  813. t = r.minus(px.div(n += 2));
  814. px = px.times(x2);
  815. r = t.plus(px.div(n += 2));
  816. if (r.d[j] !== void 0) for (i = j; r.d[i] === t.d[i] && i--;);
  817. }
  818. if (k) r = r.times(2 << (k - 1));
  819. external = true;
  820. return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true);
  821. };
  822. /*
  823. * Return true if the value of this Decimal is a finite number, otherwise return false.
  824. *
  825. */
  826. P.isFinite = function () {
  827. return !!this.d;
  828. };
  829. /*
  830. * Return true if the value of this Decimal is an integer, otherwise return false.
  831. *
  832. */
  833. P.isInteger = P.isInt = function () {
  834. return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2;
  835. };
  836. /*
  837. * Return true if the value of this Decimal is NaN, otherwise return false.
  838. *
  839. */
  840. P.isNaN = function () {
  841. return !this.s;
  842. };
  843. /*
  844. * Return true if the value of this Decimal is negative, otherwise return false.
  845. *
  846. */
  847. P.isNegative = P.isNeg = function () {
  848. return this.s < 0;
  849. };
  850. /*
  851. * Return true if the value of this Decimal is positive, otherwise return false.
  852. *
  853. */
  854. P.isPositive = P.isPos = function () {
  855. return this.s > 0;
  856. };
  857. /*
  858. * Return true if the value of this Decimal is 0 or -0, otherwise return false.
  859. *
  860. */
  861. P.isZero = function () {
  862. return !!this.d && this.d[0] === 0;
  863. };
  864. /*
  865. * Return true if the value of this Decimal is less than `y`, otherwise return false.
  866. *
  867. */
  868. P.lessThan = P.lt = function (y) {
  869. return this.cmp(y) < 0;
  870. };
  871. /*
  872. * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false.
  873. *
  874. */
  875. P.lessThanOrEqualTo = P.lte = function (y) {
  876. return this.cmp(y) < 1;
  877. };
  878. /*
  879. * Return the logarithm of the value of this Decimal to the specified base, rounded to `precision`
  880. * significant digits using rounding mode `rounding`.
  881. *
  882. * If no base is specified, return log[10](arg).
  883. *
  884. * log[base](arg) = ln(arg) / ln(base)
  885. *
  886. * The result will always be correctly rounded if the base of the log is 10, and 'almost always'
  887. * otherwise:
  888. *
  889. * Depending on the rounding mode, the result may be incorrectly rounded if the first fifteen
  890. * rounding digits are [49]99999999999999 or [50]00000000000000. In that case, the maximum error
  891. * between the result and the correctly rounded result will be one ulp (unit in the last place).
  892. *
  893. * log[-b](a) = NaN
  894. * log[0](a) = NaN
  895. * log[1](a) = NaN
  896. * log[NaN](a) = NaN
  897. * log[Infinity](a) = NaN
  898. * log[b](0) = -Infinity
  899. * log[b](-0) = -Infinity
  900. * log[b](-a) = NaN
  901. * log[b](1) = 0
  902. * log[b](Infinity) = Infinity
  903. * log[b](NaN) = NaN
  904. *
  905. * [base] {number|string|Decimal} The base of the logarithm.
  906. *
  907. */
  908. P.logarithm = P.log = function (base) {
  909. var isBase10, d, denominator, k, inf, num, sd, r,
  910. arg = this,
  911. Ctor = arg.constructor,
  912. pr = Ctor.precision,
  913. rm = Ctor.rounding,
  914. guard = 5;
  915. // Default base is 10.
  916. if (base == null) {
  917. base = new Ctor(10);
  918. isBase10 = true;
  919. } else {
  920. base = new Ctor(base);
  921. d = base.d;
  922. // Return NaN if base is negative, or non-finite, or is 0 or 1.
  923. if (base.s < 0 || !d || !d[0] || base.eq(1)) return new Ctor(NaN);
  924. isBase10 = base.eq(10);
  925. }
  926. d = arg.d;
  927. // Is arg negative, non-finite, 0 or 1?
  928. if (arg.s < 0 || !d || !d[0] || arg.eq(1)) {
  929. return new Ctor(d && !d[0] ? -1 / 0 : arg.s != 1 ? NaN : d ? 0 : 1 / 0);
  930. }
  931. // The result will have a non-terminating decimal expansion if base is 10 and arg is not an
  932. // integer power of 10.
  933. if (isBase10) {
  934. if (d.length > 1) {
  935. inf = true;
  936. } else {
  937. for (k = d[0]; k % 10 === 0;) k /= 10;
  938. inf = k !== 1;
  939. }
  940. }
  941. external = false;
  942. sd = pr + guard;
  943. num = naturalLogarithm(arg, sd);
  944. denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);
  945. // The result will have 5 rounding digits.
  946. r = divide(num, denominator, sd, 1);
  947. // If at a rounding boundary, i.e. the result's rounding digits are [49]9999 or [50]0000,
  948. // calculate 10 further digits.
  949. //
  950. // If the result is known to have an infinite decimal expansion, repeat this until it is clear
  951. // that the result is above or below the boundary. Otherwise, if after calculating the 10
  952. // further digits, the last 14 are nines, round up and assume the result is exact.
  953. // Also assume the result is exact if the last 14 are zero.
  954. //
  955. // Example of a result that will be incorrectly rounded:
  956. // log[1048576](4503599627370502) = 2.60000000000000009610279511444746...
  957. // The above result correctly rounded using ROUND_CEIL to 1 decimal place should be 2.7, but it
  958. // will be given as 2.6 as there are 15 zeros immediately after the requested decimal place, so
  959. // the exact result would be assumed to be 2.6, which rounded using ROUND_CEIL to 1 decimal
  960. // place is still 2.6.
  961. if (checkRoundingDigits(r.d, k = pr, rm)) {
  962. do {
  963. sd += 10;
  964. num = naturalLogarithm(arg, sd);
  965. denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);
  966. r = divide(num, denominator, sd, 1);
  967. if (!inf) {
  968. // Check for 14 nines from the 2nd rounding digit, as the first may be 4.
  969. if (+digitsToString(r.d).slice(k + 1, k + 15) + 1 == 1e14) {
  970. r = finalise(r, pr + 1, 0);
  971. }
  972. break;
  973. }
  974. } while (checkRoundingDigits(r.d, k += 10, rm));
  975. }
  976. external = true;
  977. return finalise(r, pr, rm);
  978. };
  979. /*
  980. * Return a new Decimal whose value is the maximum of the arguments and the value of this Decimal.
  981. *
  982. * arguments {number|string|Decimal}
  983. *
  984. P.max = function () {
  985. Array.prototype.push.call(arguments, this);
  986. return maxOrMin(this.constructor, arguments, 'lt');
  987. };
  988. */
  989. /*
  990. * Return a new Decimal whose value is the minimum of the arguments and the value of this Decimal.
  991. *
  992. * arguments {number|string|Decimal}
  993. *
  994. P.min = function () {
  995. Array.prototype.push.call(arguments, this);
  996. return maxOrMin(this.constructor, arguments, 'gt');
  997. };
  998. */
  999. /*
  1000. * n - 0 = n
  1001. * n - N = N
  1002. * n - I = -I
  1003. * 0 - n = -n
  1004. * 0 - 0 = 0
  1005. * 0 - N = N
  1006. * 0 - I = -I
  1007. * N - n = N
  1008. * N - 0 = N
  1009. * N - N = N
  1010. * N - I = N
  1011. * I - n = I
  1012. * I - 0 = I
  1013. * I - N = N
  1014. * I - I = N
  1015. *
  1016. * Return a new Decimal whose value is the value of this Decimal minus `y`, rounded to `precision`
  1017. * significant digits using rounding mode `rounding`.
  1018. *
  1019. */
  1020. P.minus = P.sub = function (y) {
  1021. var d, e, i, j, k, len, pr, rm, xd, xe, xLTy, yd,
  1022. x = this,
  1023. Ctor = x.constructor;
  1024. y = new Ctor(y);
  1025. // If either is not finite...
  1026. if (!x.d || !y.d) {
  1027. // Return NaN if either is NaN.
  1028. if (!x.s || !y.s) y = new Ctor(NaN);
  1029. // Return y negated if x is finite and y is ±Infinity.
  1030. else if (x.d) y.s = -y.s;
  1031. // Return x if y is finite and x is ±Infinity.
  1032. // Return x if both are ±Infinity with different signs.
  1033. // Return NaN if both are ±Infinity with the same sign.
  1034. else y = new Ctor(y.d || x.s !== y.s ? x : NaN);
  1035. return y;
  1036. }
  1037. // If signs differ...
  1038. if (x.s != y.s) {
  1039. y.s = -y.s;
  1040. return x.plus(y);
  1041. }
  1042. xd = x.d;
  1043. yd = y.d;
  1044. pr = Ctor.precision;
  1045. rm = Ctor.rounding;
  1046. // If either is zero...
  1047. if (!xd[0] || !yd[0]) {
  1048. // Return y negated if x is zero and y is non-zero.
  1049. if (yd[0]) y.s = -y.s;
  1050. // Return x if y is zero and x is non-zero.
  1051. else if (xd[0]) y = new Ctor(x);
  1052. // Return zero if both are zero.
  1053. // From IEEE 754 (2008) 6.3: 0 - 0 = -0 - -0 = -0 when rounding to -Infinity.
  1054. else return new Ctor(rm === 3 ? -0 : 0);
  1055. return external ? finalise(y, pr, rm) : y;
  1056. }
  1057. // x and y are finite, non-zero numbers with the same sign.
  1058. // Calculate base 1e7 exponents.
  1059. e = mathfloor(y.e / LOG_BASE);
  1060. xe = mathfloor(x.e / LOG_BASE);
  1061. xd = xd.slice();
  1062. k = xe - e;
  1063. // If base 1e7 exponents differ...
  1064. if (k) {
  1065. xLTy = k < 0;
  1066. if (xLTy) {
  1067. d = xd;
  1068. k = -k;
  1069. len = yd.length;
  1070. } else {
  1071. d = yd;
  1072. e = xe;
  1073. len = xd.length;
  1074. }
  1075. // Numbers with massively different exponents would result in a very high number of
  1076. // zeros needing to be prepended, but this can be avoided while still ensuring correct
  1077. // rounding by limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`.
  1078. i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2;
  1079. if (k > i) {
  1080. k = i;
  1081. d.length = 1;
  1082. }
  1083. // Prepend zeros to equalise exponents.
  1084. d.reverse();
  1085. for (i = k; i--;) d.push(0);
  1086. d.reverse();
  1087. // Base 1e7 exponents equal.
  1088. } else {
  1089. // Check digits to determine which is the bigger number.
  1090. i = xd.length;
  1091. len = yd.length;
  1092. xLTy = i < len;
  1093. if (xLTy) len = i;
  1094. for (i = 0; i < len; i++) {
  1095. if (xd[i] != yd[i]) {
  1096. xLTy = xd[i] < yd[i];
  1097. break;
  1098. }
  1099. }
  1100. k = 0;
  1101. }
  1102. if (xLTy) {
  1103. d = xd;
  1104. xd = yd;
  1105. yd = d;
  1106. y.s = -y.s;
  1107. }
  1108. len = xd.length;
  1109. // Append zeros to `xd` if shorter.
  1110. // Don't add zeros to `yd` if shorter as subtraction only needs to start at `yd` length.
  1111. for (i = yd.length - len; i > 0; --i) xd[len++] = 0;
  1112. // Subtract yd from xd.
  1113. for (i = yd.length; i > k;) {
  1114. if (xd[--i] < yd[i]) {
  1115. for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1;
  1116. --xd[j];
  1117. xd[i] += BASE;
  1118. }
  1119. xd[i] -= yd[i];
  1120. }
  1121. // Remove trailing zeros.
  1122. for (; xd[--len] === 0;) xd.pop();
  1123. // Remove leading zeros and adjust exponent accordingly.
  1124. for (; xd[0] === 0; xd.shift()) --e;
  1125. // Zero?
  1126. if (!xd[0]) return new Ctor(rm === 3 ? -0 : 0);
  1127. y.d = xd;
  1128. y.e = getBase10Exponent(xd, e);
  1129. return external ? finalise(y, pr, rm) : y;
  1130. };
  1131. /*
  1132. * n % 0 = N
  1133. * n % N = N
  1134. * n % I = n
  1135. * 0 % n = 0
  1136. * -0 % n = -0
  1137. * 0 % 0 = N
  1138. * 0 % N = N
  1139. * 0 % I = 0
  1140. * N % n = N
  1141. * N % 0 = N
  1142. * N % N = N
  1143. * N % I = N
  1144. * I % n = N
  1145. * I % 0 = N
  1146. * I % N = N
  1147. * I % I = N
  1148. *
  1149. * Return a new Decimal whose value is the value of this Decimal modulo `y`, rounded to
  1150. * `precision` significant digits using rounding mode `rounding`.
  1151. *
  1152. * The result depends on the modulo mode.
  1153. *
  1154. */
  1155. P.modulo = P.mod = function (y) {
  1156. var q,
  1157. x = this,
  1158. Ctor = x.constructor;
  1159. y = new Ctor(y);
  1160. // Return NaN if x is ±Infinity or NaN, or y is NaN or ±0.
  1161. if (!x.d || !y.s || y.d && !y.d[0]) return new Ctor(NaN);
  1162. // Return x if y is ±Infinity or x is ±0.
  1163. if (!y.d || x.d && !x.d[0]) {
  1164. return finalise(new Ctor(x), Ctor.precision, Ctor.rounding);
  1165. }
  1166. // Prevent rounding of intermediate calculations.
  1167. external = false;
  1168. if (Ctor.modulo == 9) {
  1169. // Euclidian division: q = sign(y) * floor(x / abs(y))
  1170. // result = x - q * y where 0 <= result < abs(y)
  1171. q = divide(x, y.abs(), 0, 3, 1);
  1172. q.s *= y.s;
  1173. } else {
  1174. q = divide(x, y, 0, Ctor.modulo, 1);
  1175. }
  1176. q = q.times(y);
  1177. external = true;
  1178. return x.minus(q);
  1179. };
  1180. /*
  1181. * Return a new Decimal whose value is the natural exponential of the value of this Decimal,
  1182. * i.e. the base e raised to the power the value of this Decimal, rounded to `precision`
  1183. * significant digits using rounding mode `rounding`.
  1184. *
  1185. */
  1186. P.naturalExponential = P.exp = function () {
  1187. return naturalExponential(this);
  1188. };
  1189. /*
  1190. * Return a new Decimal whose value is the natural logarithm of the value of this Decimal,
  1191. * rounded to `precision` significant digits using rounding mode `rounding`.
  1192. *
  1193. */
  1194. P.naturalLogarithm = P.ln = function () {
  1195. return naturalLogarithm(this);
  1196. };
  1197. /*
  1198. * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by
  1199. * -1.
  1200. *
  1201. */
  1202. P.negated = P.neg = function () {
  1203. var x = new this.constructor(this);
  1204. x.s = -x.s;
  1205. return finalise(x);
  1206. };
  1207. /*
  1208. * n + 0 = n
  1209. * n + N = N
  1210. * n + I = I
  1211. * 0 + n = n
  1212. * 0 + 0 = 0
  1213. * 0 + N = N
  1214. * 0 + I = I
  1215. * N + n = N
  1216. * N + 0 = N
  1217. * N + N = N
  1218. * N + I = N
  1219. * I + n = I
  1220. * I + 0 = I
  1221. * I + N = N
  1222. * I + I = I
  1223. *
  1224. * Return a new Decimal whose value is the value of this Decimal plus `y`, rounded to `precision`
  1225. * significant digits using rounding mode `rounding`.
  1226. *
  1227. */
  1228. P.plus = P.add = function (y) {
  1229. var carry, d, e, i, k, len, pr, rm, xd, yd,
  1230. x = this,
  1231. Ctor = x.constructor;
  1232. y = new Ctor(y);
  1233. // If either is not finite...
  1234. if (!x.d || !y.d) {
  1235. // Return NaN if either is NaN.
  1236. if (!x.s || !y.s) y = new Ctor(NaN);
  1237. // Return x if y is finite and x is ±Infinity.
  1238. // Return x if both are ±Infinity with the same sign.
  1239. // Return NaN if both are ±Infinity with different signs.
  1240. // Return y if x is finite and y is ±Infinity.
  1241. else if (!x.d) y = new Ctor(y.d || x.s === y.s ? x : NaN);
  1242. return y;
  1243. }
  1244. // If signs differ...
  1245. if (x.s != y.s) {
  1246. y.s = -y.s;
  1247. return x.minus(y);
  1248. }
  1249. xd = x.d;
  1250. yd = y.d;
  1251. pr = Ctor.precision;
  1252. rm = Ctor.rounding;
  1253. // If either is zero...
  1254. if (!xd[0] || !yd[0]) {
  1255. // Return x if y is zero.
  1256. // Return y if y is non-zero.
  1257. if (!yd[0]) y = new Ctor(x);
  1258. return external ? finalise(y, pr, rm) : y;
  1259. }
  1260. // x and y are finite, non-zero numbers with the same sign.
  1261. // Calculate base 1e7 exponents.
  1262. k = mathfloor(x.e / LOG_BASE);
  1263. e = mathfloor(y.e / LOG_BASE);
  1264. xd = xd.slice();
  1265. i = k - e;
  1266. // If base 1e7 exponents differ...
  1267. if (i) {
  1268. if (i < 0) {
  1269. d = xd;
  1270. i = -i;
  1271. len = yd.length;
  1272. } else {
  1273. d = yd;
  1274. e = k;
  1275. len = xd.length;
  1276. }
  1277. // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1.
  1278. k = Math.ceil(pr / LOG_BASE);
  1279. len = k > len ? k + 1 : len + 1;
  1280. if (i > len) {
  1281. i = len;
  1282. d.length = 1;
  1283. }
  1284. // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts.
  1285. d.reverse();
  1286. for (; i--;) d.push(0);
  1287. d.reverse();
  1288. }
  1289. len = xd.length;
  1290. i = yd.length;
  1291. // If yd is longer than xd, swap xd and yd so xd points to the longer array.
  1292. if (len - i < 0) {
  1293. i = len;
  1294. d = yd;
  1295. yd = xd;
  1296. xd = d;
  1297. }
  1298. // Only start adding at yd.length - 1 as the further digits of xd can be left as they are.
  1299. for (carry = 0; i;) {
  1300. carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0;
  1301. xd[i] %= BASE;
  1302. }
  1303. if (carry) {
  1304. xd.unshift(carry);
  1305. ++e;
  1306. }
  1307. // Remove trailing zeros.
  1308. // No need to check for zero, as +x + +y != 0 && -x + -y != 0
  1309. for (len = xd.length; xd[--len] == 0;) xd.pop();
  1310. y.d = xd;
  1311. y.e = getBase10Exponent(xd, e);
  1312. return external ? finalise(y, pr, rm) : y;
  1313. };
  1314. /*
  1315. * Return the number of significant digits of the value of this Decimal.
  1316. *
  1317. * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
  1318. *
  1319. */
  1320. P.precision = P.sd = function (z) {
  1321. var k,
  1322. x = this;
  1323. if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z);
  1324. if (x.d) {
  1325. k = getPrecision(x.d);
  1326. if (z && x.e + 1 > k) k = x.e + 1;
  1327. } else {
  1328. k = NaN;
  1329. }
  1330. return k;
  1331. };
  1332. /*
  1333. * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using
  1334. * rounding mode `rounding`.
  1335. *
  1336. */
  1337. P.round = function () {
  1338. var x = this,
  1339. Ctor = x.constructor;
  1340. return finalise(new Ctor(x), x.e + 1, Ctor.rounding);
  1341. };
  1342. /*
  1343. * Return a new Decimal whose value is the sine of the value in radians of this Decimal.
  1344. *
  1345. * Domain: [-Infinity, Infinity]
  1346. * Range: [-1, 1]
  1347. *
  1348. * sin(x) = x - x^3/3! + x^5/5! - ...
  1349. *
  1350. * sin(0) = 0
  1351. * sin(-0) = -0
  1352. * sin(Infinity) = NaN
  1353. * sin(-Infinity) = NaN
  1354. * sin(NaN) = NaN
  1355. *
  1356. */
  1357. P.sine = P.sin = function () {
  1358. var pr, rm,
  1359. x = this,
  1360. Ctor = x.constructor;
  1361. if (!x.isFinite()) return new Ctor(NaN);
  1362. if (x.isZero()) return new Ctor(x);
  1363. pr = Ctor.precision;
  1364. rm = Ctor.rounding;
  1365. Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;
  1366. Ctor.rounding = 1;
  1367. x = sine(Ctor, toLessThanHalfPi(Ctor, x));
  1368. Ctor.precision = pr;
  1369. Ctor.rounding = rm;
  1370. return finalise(quadrant > 2 ? x.neg() : x, pr, rm, true);
  1371. };
  1372. /*
  1373. * Return a new Decimal whose value is the square root of this Decimal, rounded to `precision`
  1374. * significant digits using rounding mode `rounding`.
  1375. *
  1376. * sqrt(-n) = N
  1377. * sqrt(N) = N
  1378. * sqrt(-I) = N
  1379. * sqrt(I) = I
  1380. * sqrt(0) = 0
  1381. * sqrt(-0) = -0
  1382. *
  1383. */
  1384. P.squareRoot = P.sqrt = function () {
  1385. var m, n, sd, r, rep, t,
  1386. x = this,
  1387. d = x.d,
  1388. e = x.e,
  1389. s = x.s,
  1390. Ctor = x.constructor;
  1391. // Negative/NaN/Infinity/zero?
  1392. if (s !== 1 || !d || !d[0]) {
  1393. return new Ctor(!s || s < 0 && (!d || d[0]) ? NaN : d ? x : 1 / 0);
  1394. }
  1395. external = false;
  1396. // Initial estimate.
  1397. s = Math.sqrt(+x);
  1398. // Math.sqrt underflow/overflow?
  1399. // Pass x to Math.sqrt as integer, then adjust the exponent of the result.
  1400. if (s == 0 || s == 1 / 0) {
  1401. n = digitsToString(d);
  1402. if ((n.length + e) % 2 == 0) n += '0';
  1403. s = Math.sqrt(n);
  1404. e = mathfloor((e + 1) / 2) - (e < 0 || e % 2);
  1405. if (s == 1 / 0) {
  1406. n = '5e' + e;
  1407. } else {
  1408. n = s.toExponential();
  1409. n = n.slice(0, n.indexOf('e') + 1) + e;
  1410. }
  1411. r = new Ctor(n);
  1412. } else {
  1413. r = new Ctor(s.toString());
  1414. }
  1415. sd = (e = Ctor.precision) + 3;
  1416. // Newton-Raphson iteration.
  1417. for (;;) {
  1418. t = r;
  1419. r = t.plus(divide(x, t, sd + 2, 1)).times(0.5);
  1420. // TODO? Replace with for-loop and checkRoundingDigits.
  1421. if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {
  1422. n = n.slice(sd - 3, sd + 1);
  1423. // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or
  1424. // 4999, i.e. approaching a rounding boundary, continue the iteration.
  1425. if (n == '9999' || !rep && n == '4999') {
  1426. // On the first iteration only, check to see if rounding up gives the exact result as the
  1427. // nines may infinitely repeat.
  1428. if (!rep) {
  1429. finalise(t, e + 1, 0);
  1430. if (t.times(t).eq(x)) {
  1431. r = t;
  1432. break;
  1433. }
  1434. }
  1435. sd += 4;
  1436. rep = 1;
  1437. } else {
  1438. // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.
  1439. // If not, then there are further digits and m will be truthy.
  1440. if (!+n || !+n.slice(1) && n.charAt(0) == '5') {
  1441. // Truncate to the first rounding digit.
  1442. finalise(r, e + 1, 1);
  1443. m = !r.times(r).eq(x);
  1444. }
  1445. break;
  1446. }
  1447. }
  1448. }
  1449. external = true;
  1450. return finalise(r, e, Ctor.rounding, m);
  1451. };
  1452. /*
  1453. * Return a new Decimal whose value is the tangent of the value in radians of this Decimal.
  1454. *
  1455. * Domain: [-Infinity, Infinity]
  1456. * Range: [-Infinity, Infinity]
  1457. *
  1458. * tan(0) = 0
  1459. * tan(-0) = -0
  1460. * tan(Infinity) = NaN
  1461. * tan(-Infinity) = NaN
  1462. * tan(NaN) = NaN
  1463. *
  1464. */
  1465. P.tangent = P.tan = function () {
  1466. var pr, rm,
  1467. x = this,
  1468. Ctor = x.constructor;
  1469. if (!x.isFinite()) return new Ctor(NaN);
  1470. if (x.isZero()) return new Ctor(x);
  1471. pr = Ctor.precision;
  1472. rm = Ctor.rounding;
  1473. Ctor.precision = pr + 10;
  1474. Ctor.rounding = 1;
  1475. x = x.sin();
  1476. x.s = 1;
  1477. x = divide(x, new Ctor(1).minus(x.times(x)).sqrt(), pr + 10, 0);
  1478. Ctor.precision = pr;
  1479. Ctor.rounding = rm;
  1480. return finalise(quadrant == 2 || quadrant == 4 ? x.neg() : x, pr, rm, true);
  1481. };
  1482. /*
  1483. * n * 0 = 0
  1484. * n * N = N
  1485. * n * I = I
  1486. * 0 * n = 0
  1487. * 0 * 0 = 0
  1488. * 0 * N = N
  1489. * 0 * I = N
  1490. * N * n = N
  1491. * N * 0 = N
  1492. * N * N = N
  1493. * N * I = N
  1494. * I * n = I
  1495. * I * 0 = N
  1496. * I * N = N
  1497. * I * I = I
  1498. *
  1499. * Return a new Decimal whose value is this Decimal times `y`, rounded to `precision` significant
  1500. * digits using rounding mode `rounding`.
  1501. *
  1502. */
  1503. P.times = P.mul = function (y) {
  1504. var carry, e, i, k, r, rL, t, xdL, ydL,
  1505. x = this,
  1506. Ctor = x.constructor,
  1507. xd = x.d,
  1508. yd = (y = new Ctor(y)).d;
  1509. y.s *= x.s;
  1510. // If either is NaN, ±Infinity or ±0...
  1511. if (!xd || !xd[0] || !yd || !yd[0]) {
  1512. return new Ctor(!y.s || xd && !xd[0] && !yd || yd && !yd[0] && !xd
  1513. // Return NaN if either is NaN.
  1514. // Return NaN if x is ±0 and y is ±Infinity, or y is ±0 and x is ±Infinity.
  1515. ? NaN
  1516. // Return ±Infinity if either is ±Infinity.
  1517. // Return ±0 if either is ±0.
  1518. : !xd || !yd ? y.s / 0 : y.s * 0);
  1519. }
  1520. e = mathfloor(x.e / LOG_BASE) + mathfloor(y.e / LOG_BASE);
  1521. xdL = xd.length;
  1522. ydL = yd.length;
  1523. // Ensure xd points to the longer array.
  1524. if (xdL < ydL) {
  1525. r = xd;
  1526. xd = yd;
  1527. yd = r;
  1528. rL = xdL;
  1529. xdL = ydL;
  1530. ydL = rL;
  1531. }
  1532. // Initialise the result array with zeros.
  1533. r = [];
  1534. rL = xdL + ydL;
  1535. for (i = rL; i--;) r.push(0);
  1536. // Multiply!
  1537. for (i = ydL; --i >= 0;) {
  1538. carry = 0;
  1539. for (k = xdL + i; k > i;) {
  1540. t = r[k] + yd[i] * xd[k - i - 1] + carry;
  1541. r[k--] = t % BASE | 0;
  1542. carry = t / BASE | 0;
  1543. }
  1544. r[k] = (r[k] + carry) % BASE | 0;
  1545. }
  1546. // Remove trailing zeros.
  1547. for (; !r[--rL];) r.pop();
  1548. if (carry) ++e;
  1549. else r.shift();
  1550. y.d = r;
  1551. y.e = getBase10Exponent(r, e);
  1552. return external ? finalise(y, Ctor.precision, Ctor.rounding) : y;
  1553. };
  1554. /*
  1555. * Return a string representing the value of this Decimal in base 2, round to `sd` significant
  1556. * digits using rounding mode `rm`.
  1557. *
  1558. * If the optional `sd` argument is present then return binary exponential notation.
  1559. *
  1560. * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
  1561. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  1562. *
  1563. */
  1564. P.toBinary = function (sd, rm) {
  1565. return toStringBinary(this, 2, sd, rm);
  1566. };
  1567. /*
  1568. * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp`
  1569. * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted.
  1570. *
  1571. * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal.
  1572. *
  1573. * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
  1574. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  1575. *
  1576. */
  1577. P.toDecimalPlaces = P.toDP = function (dp, rm) {
  1578. var x = this,
  1579. Ctor = x.constructor;
  1580. x = new Ctor(x);
  1581. if (dp === void 0) return x;
  1582. checkInt32(dp, 0, MAX_DIGITS);
  1583. if (rm === void 0) rm = Ctor.rounding;
  1584. else checkInt32(rm, 0, 8);
  1585. return finalise(x, dp + x.e + 1, rm);
  1586. };
  1587. /*
  1588. * Return a string representing the value of this Decimal in exponential notation rounded to
  1589. * `dp` fixed decimal places using rounding mode `rounding`.
  1590. *
  1591. * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
  1592. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  1593. *
  1594. */
  1595. P.toExponential = function (dp, rm) {
  1596. var str,
  1597. x = this,
  1598. Ctor = x.constructor;
  1599. if (dp === void 0) {
  1600. str = finiteToString(x, true);
  1601. } else {
  1602. checkInt32(dp, 0, MAX_DIGITS);
  1603. if (rm === void 0) rm = Ctor.rounding;
  1604. else checkInt32(rm, 0, 8);
  1605. x = finalise(new Ctor(x), dp + 1, rm);
  1606. str = finiteToString(x, true, dp + 1);
  1607. }
  1608. return x.isNeg() && !x.isZero() ? '-' + str : str;
  1609. };
  1610. /*
  1611. * Return a string representing the value of this Decimal in normal (fixed-point) notation to
  1612. * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is
  1613. * omitted.
  1614. *
  1615. * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'.
  1616. *
  1617. * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
  1618. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  1619. *
  1620. * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'.
  1621. * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'.
  1622. * (-0).toFixed(3) is '0.000'.
  1623. * (-0.5).toFixed(0) is '-0'.
  1624. *
  1625. */
  1626. P.toFixed = function (dp, rm) {
  1627. var str, y,
  1628. x = this,
  1629. Ctor = x.constructor;
  1630. if (dp === void 0) {
  1631. str = finiteToString(x);
  1632. } else {
  1633. checkInt32(dp, 0, MAX_DIGITS);
  1634. if (rm === void 0) rm = Ctor.rounding;
  1635. else checkInt32(rm, 0, 8);
  1636. y = finalise(new Ctor(x), dp + x.e + 1, rm);
  1637. str = finiteToString(y, false, dp + y.e + 1);
  1638. }
  1639. // To determine whether to add the minus sign look at the value before it was rounded,
  1640. // i.e. look at `x` rather than `y`.
  1641. return x.isNeg() && !x.isZero() ? '-' + str : str;
  1642. };
  1643. /*
  1644. * Return an array representing the value of this Decimal as a simple fraction with an integer
  1645. * numerator and an integer denominator.
  1646. *
  1647. * The denominator will be a positive non-zero value less than or equal to the specified maximum
  1648. * denominator. If a maximum denominator is not specified, the denominator will be the lowest
  1649. * value necessary to represent the number exactly.
  1650. *
  1651. * [maxD] {number|string|Decimal} Maximum denominator. Integer >= 1 and < Infinity.
  1652. *
  1653. */
  1654. P.toFraction = function (maxD) {
  1655. var d, d0, d1, d2, e, k, n, n0, n1, pr, q, r,
  1656. x = this,
  1657. xd = x.d,
  1658. Ctor = x.constructor;
  1659. if (!xd) return new Ctor(x);
  1660. n1 = d0 = new Ctor(1);
  1661. d1 = n0 = new Ctor(0);
  1662. d = new Ctor(d1);
  1663. e = d.e = getPrecision(xd) - x.e - 1;
  1664. k = e % LOG_BASE;
  1665. d.d[0] = mathpow(10, k < 0 ? LOG_BASE + k : k);
  1666. if (maxD == null) {
  1667. // d is 10**e, the minimum max-denominator needed.
  1668. maxD = e > 0 ? d : n1;
  1669. } else {
  1670. n = new Ctor(maxD);
  1671. if (!n.isInt() || n.lt(n1)) throw Error(invalidArgument + n);
  1672. maxD = n.gt(d) ? (e > 0 ? d : n1) : n;
  1673. }
  1674. external = false;
  1675. n = new Ctor(digitsToString(xd));
  1676. pr = Ctor.precision;
  1677. Ctor.precision = e = xd.length * LOG_BASE * 2;
  1678. for (;;) {
  1679. q = divide(n, d, 0, 1, 1);
  1680. d2 = d0.plus(q.times(d1));
  1681. if (d2.cmp(maxD) == 1) break;
  1682. d0 = d1;
  1683. d1 = d2;
  1684. d2 = n1;
  1685. n1 = n0.plus(q.times(d2));
  1686. n0 = d2;
  1687. d2 = d;
  1688. d = n.minus(q.times(d2));
  1689. n = d2;
  1690. }
  1691. d2 = divide(maxD.minus(d0), d1, 0, 1, 1);
  1692. n0 = n0.plus(d2.times(n1));
  1693. d0 = d0.plus(d2.times(d1));
  1694. n0.s = n1.s = x.s;
  1695. // Determine which fraction is closer to x, n0/d0 or n1/d1?
  1696. r = divide(n1, d1, e, 1).minus(x).abs().cmp(divide(n0, d0, e, 1).minus(x).abs()) < 1
  1697. ? [n1, d1] : [n0, d0];
  1698. Ctor.precision = pr;
  1699. external = true;
  1700. return r;
  1701. };
  1702. /*
  1703. * Return a string representing the value of this Decimal in base 16, round to `sd` significant
  1704. * digits using rounding mode `rm`.
  1705. *
  1706. * If the optional `sd` argument is present then return binary exponential notation.
  1707. *
  1708. * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
  1709. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  1710. *
  1711. */
  1712. P.toHexadecimal = P.toHex = function (sd, rm) {
  1713. return toStringBinary(this, 16, sd, rm);
  1714. };
  1715. /*
  1716. * Returns a new Decimal whose value is the nearest multiple of `y` in the direction of rounding
  1717. * mode `rm`, or `Decimal.rounding` if `rm` is omitted, to the value of this Decimal.
  1718. *
  1719. * The return value will always have the same sign as this Decimal, unless either this Decimal
  1720. * or `y` is NaN, in which case the return value will be also be NaN.
  1721. *
  1722. * The return value is not affected by the value of `precision`.
  1723. *
  1724. * y {number|string|Decimal} The magnitude to round to a multiple of.
  1725. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  1726. *
  1727. * 'toNearest() rounding mode not an integer: {rm}'
  1728. * 'toNearest() rounding mode out of range: {rm}'
  1729. *
  1730. */
  1731. P.toNearest = function (y, rm) {
  1732. var x = this,
  1733. Ctor = x.constructor;
  1734. x = new Ctor(x);
  1735. if (y == null) {
  1736. // If x is not finite, return x.
  1737. if (!x.d) return x;
  1738. y = new Ctor(1);
  1739. rm = Ctor.rounding;
  1740. } else {
  1741. y = new Ctor(y);
  1742. if (rm === void 0) {
  1743. rm = Ctor.rounding;
  1744. } else {
  1745. checkInt32(rm, 0, 8);
  1746. }
  1747. // If x is not finite, return x if y is not NaN, else NaN.
  1748. if (!x.d) return y.s ? x : y;
  1749. // If y is not finite, return Infinity with the sign of x if y is Infinity, else NaN.
  1750. if (!y.d) {
  1751. if (y.s) y.s = x.s;
  1752. return y;
  1753. }
  1754. }
  1755. // If y is not zero, calculate the nearest multiple of y to x.
  1756. if (y.d[0]) {
  1757. external = false;
  1758. x = divide(x, y, 0, rm, 1).times(y);
  1759. external = true;
  1760. finalise(x);
  1761. // If y is zero, return zero with the sign of x.
  1762. } else {
  1763. y.s = x.s;
  1764. x = y;
  1765. }
  1766. return x;
  1767. };
  1768. /*
  1769. * Return the value of this Decimal converted to a number primitive.
  1770. * Zero keeps its sign.
  1771. *
  1772. */
  1773. P.toNumber = function () {
  1774. return +this;
  1775. };
  1776. /*
  1777. * Return a string representing the value of this Decimal in base 8, round to `sd` significant
  1778. * digits using rounding mode `rm`.
  1779. *
  1780. * If the optional `sd` argument is present then return binary exponential notation.
  1781. *
  1782. * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
  1783. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  1784. *
  1785. */
  1786. P.toOctal = function (sd, rm) {
  1787. return toStringBinary(this, 8, sd, rm);
  1788. };
  1789. /*
  1790. * Return a new Decimal whose value is the value of this Decimal raised to the power `y`, rounded
  1791. * to `precision` significant digits using rounding mode `rounding`.
  1792. *
  1793. * ECMAScript compliant.
  1794. *
  1795. * pow(x, NaN) = NaN
  1796. * pow(x, ±0) = 1
  1797. * pow(NaN, non-zero) = NaN
  1798. * pow(abs(x) > 1, +Infinity) = +Infinity
  1799. * pow(abs(x) > 1, -Infinity) = +0
  1800. * pow(abs(x) == 1, ±Infinity) = NaN
  1801. * pow(abs(x) < 1, +Infinity) = +0
  1802. * pow(abs(x) < 1, -Infinity) = +Infinity
  1803. * pow(+Infinity, y > 0) = +Infinity
  1804. * pow(+Infinity, y < 0) = +0
  1805. * pow(-Infinity, odd integer > 0) = -Infinity
  1806. * pow(-Infinity, even integer > 0) = +Infinity
  1807. * pow(-Infinity, odd integer < 0) = -0
  1808. * pow(-Infinity, even integer < 0) = +0
  1809. * pow(+0, y > 0) = +0
  1810. * pow(+0, y < 0) = +Infinity
  1811. * pow(-0, odd integer > 0) = -0
  1812. * pow(-0, even integer > 0) = +0
  1813. * pow(-0, odd integer < 0) = -Infinity
  1814. * pow(-0, even integer < 0) = +Infinity
  1815. * pow(finite x < 0, finite non-integer) = NaN
  1816. *
  1817. * For non-integer or very large exponents pow(x, y) is calculated using
  1818. *
  1819. * x^y = exp(y*ln(x))
  1820. *
  1821. * Assuming the first 15 rounding digits are each equally likely to be any digit 0-9, the
  1822. * probability of an incorrectly rounded result
  1823. * P([49]9{14} | [50]0{14}) = 2 * 0.2 * 10^-14 = 4e-15 = 1/2.5e+14
  1824. * i.e. 1 in 250,000,000,000,000
  1825. *
  1826. * If a result is incorrectly rounded the maximum error will be 1 ulp (unit in last place).
  1827. *
  1828. * y {number|string|Decimal} The power to which to raise this Decimal.
  1829. *
  1830. */
  1831. P.toPower = P.pow = function (y) {
  1832. var e, k, pr, r, rm, s,
  1833. x = this,
  1834. Ctor = x.constructor,
  1835. yn = +(y = new Ctor(y));
  1836. // Either ±Infinity, NaN or ±0?
  1837. if (!x.d || !y.d || !x.d[0] || !y.d[0]) return new Ctor(mathpow(+x, yn));
  1838. x = new Ctor(x);
  1839. if (x.eq(1)) return x;
  1840. pr = Ctor.precision;
  1841. rm = Ctor.rounding;
  1842. if (y.eq(1)) return finalise(x, pr, rm);
  1843. // y exponent
  1844. e = mathfloor(y.e / LOG_BASE);
  1845. // If y is a small integer use the 'exponentiation by squaring' algorithm.
  1846. if (e >= y.d.length - 1 && (k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) {
  1847. r = intPow(Ctor, x, k, pr);
  1848. return y.s < 0 ? new Ctor(1).div(r) : finalise(r, pr, rm);
  1849. }
  1850. s = x.s;
  1851. // if x is negative
  1852. if (s < 0) {
  1853. // if y is not an integer
  1854. if (e < y.d.length - 1) return new Ctor(NaN);
  1855. // Result is positive if x is negative and the last digit of integer y is even.
  1856. if ((y.d[e] & 1) == 0) s = 1;
  1857. // if x.eq(-1)
  1858. if (x.e == 0 && x.d[0] == 1 && x.d.length == 1) {
  1859. x.s = s;
  1860. return x;
  1861. }
  1862. }
  1863. // Estimate result exponent.
  1864. // x^y = 10^e, where e = y * log10(x)
  1865. // log10(x) = log10(x_significand) + x_exponent
  1866. // log10(x_significand) = ln(x_significand) / ln(10)
  1867. k = mathpow(+x, yn);
  1868. e = k == 0 || !isFinite(k)
  1869. ? mathfloor(yn * (Math.log('0.' + digitsToString(x.d)) / Math.LN10 + x.e + 1))
  1870. : new Ctor(k + '').e;
  1871. // Exponent estimate may be incorrect e.g. x: 0.999999999999999999, y: 2.29, e: 0, r.e: -1.
  1872. // Overflow/underflow?
  1873. if (e > Ctor.maxE + 1 || e < Ctor.minE - 1) return new Ctor(e > 0 ? s / 0 : 0);
  1874. external = false;
  1875. Ctor.rounding = x.s = 1;
  1876. // Estimate the extra guard digits needed to ensure five correct rounding digits from
  1877. // naturalLogarithm(x). Example of failure without these extra digits (precision: 10):
  1878. // new Decimal(2.32456).pow('2087987436534566.46411')
  1879. // should be 1.162377823e+764914905173815, but is 1.162355823e+764914905173815
  1880. k = Math.min(12, (e + '').length);
  1881. // r = x^y = exp(y*ln(x))
  1882. r = naturalExponential(y.times(naturalLogarithm(x, pr + k)), pr);
  1883. // r may be Infinity, e.g. (0.9999999999999999).pow(-1e+40)
  1884. if (r.d) {
  1885. // Truncate to the required precision plus five rounding digits.
  1886. r = finalise(r, pr + 5, 1);
  1887. // If the rounding digits are [49]9999 or [50]0000 increase the precision by 10 and recalculate
  1888. // the result.
  1889. if (checkRoundingDigits(r.d, pr, rm)) {
  1890. e = pr + 10;
  1891. // Truncate to the increased precision plus five rounding digits.
  1892. r = finalise(naturalExponential(y.times(naturalLogarithm(x, e + k)), e), e + 5, 1);
  1893. // Check for 14 nines from the 2nd rounding digit (the first rounding digit may be 4 or 9).
  1894. if (+digitsToString(r.d).slice(pr + 1, pr + 15) + 1 == 1e14) {
  1895. r = finalise(r, pr + 1, 0);
  1896. }
  1897. }
  1898. }
  1899. r.s = s;
  1900. external = true;
  1901. Ctor.rounding = rm;
  1902. return finalise(r, pr, rm);
  1903. };
  1904. /*
  1905. * Return a string representing the value of this Decimal rounded to `sd` significant digits
  1906. * using rounding mode `rounding`.
  1907. *
  1908. * Return exponential notation if `sd` is less than the number of digits necessary to represent
  1909. * the integer part of the value in normal notation.
  1910. *
  1911. * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
  1912. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  1913. *
  1914. */
  1915. P.toPrecision = function (sd, rm) {
  1916. var str,
  1917. x = this,
  1918. Ctor = x.constructor;
  1919. if (sd === void 0) {
  1920. str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
  1921. } else {
  1922. checkInt32(sd, 1, MAX_DIGITS);
  1923. if (rm === void 0) rm = Ctor.rounding;
  1924. else checkInt32(rm, 0, 8);
  1925. x = finalise(new Ctor(x), sd, rm);
  1926. str = finiteToString(x, sd <= x.e || x.e <= Ctor.toExpNeg, sd);
  1927. }
  1928. return x.isNeg() && !x.isZero() ? '-' + str : str;
  1929. };
  1930. /*
  1931. * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd`
  1932. * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if
  1933. * omitted.
  1934. *
  1935. * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
  1936. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  1937. *
  1938. * 'toSD() digits out of range: {sd}'
  1939. * 'toSD() digits not an integer: {sd}'
  1940. * 'toSD() rounding mode not an integer: {rm}'
  1941. * 'toSD() rounding mode out of range: {rm}'
  1942. *
  1943. */
  1944. P.toSignificantDigits = P.toSD = function (sd, rm) {
  1945. var x = this,
  1946. Ctor = x.constructor;
  1947. if (sd === void 0) {
  1948. sd = Ctor.precision;
  1949. rm = Ctor.rounding;
  1950. } else {
  1951. checkInt32(sd, 1, MAX_DIGITS);
  1952. if (rm === void 0) rm = Ctor.rounding;
  1953. else checkInt32(rm, 0, 8);
  1954. }
  1955. return finalise(new Ctor(x), sd, rm);
  1956. };
  1957. /*
  1958. * Return a string representing the value of this Decimal.
  1959. *
  1960. * Return exponential notation if this Decimal has a positive exponent equal to or greater than
  1961. * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`.
  1962. *
  1963. */
  1964. P.toString = function () {
  1965. var x = this,
  1966. Ctor = x.constructor,
  1967. str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
  1968. return x.isNeg() && !x.isZero() ? '-' + str : str;
  1969. };
  1970. /*
  1971. * Return a new Decimal whose value is the value of this Decimal truncated to a whole number.
  1972. *
  1973. */
  1974. P.truncated = P.trunc = function () {
  1975. return finalise(new this.constructor(this), this.e + 1, 1);
  1976. };
  1977. /*
  1978. * Return a string representing the value of this Decimal.
  1979. * Unlike `toString`, negative zero will include the minus sign.
  1980. *
  1981. */
  1982. P.valueOf = P.toJSON = function () {
  1983. var x = this,
  1984. Ctor = x.constructor,
  1985. str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
  1986. return x.isNeg() ? '-' + str : str;
  1987. };
  1988. /*
  1989. // Add aliases to match BigDecimal method names.
  1990. // P.add = P.plus;
  1991. P.subtract = P.minus;
  1992. P.multiply = P.times;
  1993. P.divide = P.div;
  1994. P.remainder = P.mod;
  1995. P.compareTo = P.cmp;
  1996. P.negate = P.neg;
  1997. */
  1998. // Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers.
  1999. /*
  2000. * digitsToString P.cubeRoot, P.logarithm, P.squareRoot, P.toFraction, P.toPower,
  2001. * finiteToString, naturalExponential, naturalLogarithm
  2002. * checkInt32 P.toDecimalPlaces, P.toExponential, P.toFixed, P.toNearest,
  2003. * P.toPrecision, P.toSignificantDigits, toStringBinary, random
  2004. * checkRoundingDigits P.logarithm, P.toPower, naturalExponential, naturalLogarithm
  2005. * convertBase toStringBinary, parseOther
  2006. * cos P.cos
  2007. * divide P.atanh, P.cubeRoot, P.dividedBy, P.dividedToIntegerBy,
  2008. * P.logarithm, P.modulo, P.squareRoot, P.tan, P.tanh, P.toFraction,
  2009. * P.toNearest, toStringBinary, naturalExponential, naturalLogarithm,
  2010. * taylorSeries, atan2, parseOther
  2011. * finalise P.absoluteValue, P.atan, P.atanh, P.ceil, P.cos, P.cosh,
  2012. * P.cubeRoot, P.dividedToIntegerBy, P.floor, P.logarithm, P.minus,
  2013. * P.modulo, P.negated, P.plus, P.round, P.sin, P.sinh, P.squareRoot,
  2014. * P.tan, P.times, P.toDecimalPlaces, P.toExponential, P.toFixed,
  2015. * P.toNearest, P.toPower, P.toPrecision, P.toSignificantDigits,
  2016. * P.truncated, divide, getLn10, getPi, naturalExponential,
  2017. * naturalLogarithm, ceil, floor, round, trunc
  2018. * finiteToString P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf,
  2019. * toStringBinary
  2020. * getBase10Exponent P.minus, P.plus, P.times, parseOther
  2021. * getLn10 P.logarithm, naturalLogarithm
  2022. * getPi P.acos, P.asin, P.atan, toLessThanHalfPi, atan2
  2023. * getPrecision P.precision, P.toFraction
  2024. * getZeroString digitsToString, finiteToString
  2025. * intPow P.toPower, parseOther
  2026. * isOdd toLessThanHalfPi
  2027. * maxOrMin max, min
  2028. * naturalExponential P.naturalExponential, P.toPower
  2029. * naturalLogarithm P.acosh, P.asinh, P.atanh, P.logarithm, P.naturalLogarithm,
  2030. * P.toPower, naturalExponential
  2031. * nonFiniteToString finiteToString, toStringBinary
  2032. * parseDecimal Decimal
  2033. * parseOther Decimal
  2034. * sin P.sin
  2035. * taylorSeries P.cosh, P.sinh, cos, sin
  2036. * toLessThanHalfPi P.cos, P.sin
  2037. * toStringBinary P.toBinary, P.toHexadecimal, P.toOctal
  2038. * truncate intPow
  2039. *
  2040. * Throws: P.logarithm, P.precision, P.toFraction, checkInt32, getLn10, getPi,
  2041. * naturalLogarithm, config, parseOther, random, Decimal
  2042. */
  2043. function digitsToString(d) {
  2044. var i, k, ws,
  2045. indexOfLastWord = d.length - 1,
  2046. str = '',
  2047. w = d[0];
  2048. if (indexOfLastWord > 0) {
  2049. str += w;
  2050. for (i = 1; i < indexOfLastWord; i++) {
  2051. ws = d[i] + '';
  2052. k = LOG_BASE - ws.length;
  2053. if (k) str += getZeroString(k);
  2054. str += ws;
  2055. }
  2056. w = d[i];
  2057. ws = w + '';
  2058. k = LOG_BASE - ws.length;
  2059. if (k) str += getZeroString(k);
  2060. } else if (w === 0) {
  2061. return '0';
  2062. }
  2063. // Remove trailing zeros of last w.
  2064. for (; w % 10 === 0;) w /= 10;
  2065. return str + w;
  2066. }
  2067. function checkInt32(i, min, max) {
  2068. if (i !== ~~i || i < min || i > max) {
  2069. throw Error(invalidArgument + i);
  2070. }
  2071. }
  2072. /*
  2073. * Check 5 rounding digits if `repeating` is null, 4 otherwise.
  2074. * `repeating == null` if caller is `log` or `pow`,
  2075. * `repeating != null` if caller is `naturalLogarithm` or `naturalExponential`.
  2076. */
  2077. function checkRoundingDigits(d, i, rm, repeating) {
  2078. var di, k, r, rd;
  2079. // Get the length of the first word of the array d.
  2080. for (k = d[0]; k >= 10; k /= 10) --i;
  2081. // Is the rounding digit in the first word of d?
  2082. if (--i < 0) {
  2083. i += LOG_BASE;
  2084. di = 0;
  2085. } else {
  2086. di = Math.ceil((i + 1) / LOG_BASE);
  2087. i %= LOG_BASE;
  2088. }
  2089. // i is the index (0 - 6) of the rounding digit.
  2090. // E.g. if within the word 3487563 the first rounding digit is 5,
  2091. // then i = 4, k = 1000, rd = 3487563 % 1000 = 563
  2092. k = mathpow(10, LOG_BASE - i);
  2093. rd = d[di] % k | 0;
  2094. if (repeating == null) {
  2095. if (i < 3) {
  2096. if (i == 0) rd = rd / 100 | 0;
  2097. else if (i == 1) rd = rd / 10 | 0;
  2098. r = rm < 4 && rd == 99999 || rm > 3 && rd == 49999 || rd == 50000 || rd == 0;
  2099. } else {
  2100. r = (rm < 4 && rd + 1 == k || rm > 3 && rd + 1 == k / 2) &&
  2101. (d[di + 1] / k / 100 | 0) == mathpow(10, i - 2) - 1 ||
  2102. (rd == k / 2 || rd == 0) && (d[di + 1] / k / 100 | 0) == 0;
  2103. }
  2104. } else {
  2105. if (i < 4) {
  2106. if (i == 0) rd = rd / 1000 | 0;
  2107. else if (i == 1) rd = rd / 100 | 0;
  2108. else if (i == 2) rd = rd / 10 | 0;
  2109. r = (repeating || rm < 4) && rd == 9999 || !repeating && rm > 3 && rd == 4999;
  2110. } else {
  2111. r = ((repeating || rm < 4) && rd + 1 == k ||
  2112. (!repeating && rm > 3) && rd + 1 == k / 2) &&
  2113. (d[di + 1] / k / 1000 | 0) == mathpow(10, i - 3) - 1;
  2114. }
  2115. }
  2116. return r;
  2117. }
  2118. // Convert string of `baseIn` to an array of numbers of `baseOut`.
  2119. // Eg. convertBase('255', 10, 16) returns [15, 15].
  2120. // Eg. convertBase('ff', 16, 10) returns [2, 5, 5].
  2121. function convertBase(str, baseIn, baseOut) {
  2122. var j,
  2123. arr = [0],
  2124. arrL,
  2125. i = 0,
  2126. strL = str.length;
  2127. for (; i < strL;) {
  2128. for (arrL = arr.length; arrL--;) arr[arrL] *= baseIn;
  2129. arr[0] += NUMERALS.indexOf(str.charAt(i++));
  2130. for (j = 0; j < arr.length; j++) {
  2131. if (arr[j] > baseOut - 1) {
  2132. if (arr[j + 1] === void 0) arr[j + 1] = 0;
  2133. arr[j + 1] += arr[j] / baseOut | 0;
  2134. arr[j] %= baseOut;
  2135. }
  2136. }
  2137. }
  2138. return arr.reverse();
  2139. }
  2140. /*
  2141. * cos(x) = 1 - x^2/2! + x^4/4! - ...
  2142. * |x| < pi/2
  2143. *
  2144. */
  2145. function cosine(Ctor, x) {
  2146. var k, y,
  2147. len = x.d.length;
  2148. // Argument reduction: cos(4x) = 8*(cos^4(x) - cos^2(x)) + 1
  2149. // i.e. cos(x) = 8*(cos^4(x/4) - cos^2(x/4)) + 1
  2150. // Estimate the optimum number of times to use the argument reduction.
  2151. if (len < 32) {
  2152. k = Math.ceil(len / 3);
  2153. y = (1 / tinyPow(4, k)).toString();
  2154. } else {
  2155. k = 16;
  2156. y = '2.3283064365386962890625e-10';
  2157. }
  2158. Ctor.precision += k;
  2159. x = taylorSeries(Ctor, 1, x.times(y), new Ctor(1));
  2160. // Reverse argument reduction
  2161. for (var i = k; i--;) {
  2162. var cos2x = x.times(x);
  2163. x = cos2x.times(cos2x).minus(cos2x).times(8).plus(1);
  2164. }
  2165. Ctor.precision -= k;
  2166. return x;
  2167. }
  2168. /*
  2169. * Perform division in the specified base.
  2170. */
  2171. var divide = (function () {
  2172. // Assumes non-zero x and k, and hence non-zero result.
  2173. function multiplyInteger(x, k, base) {
  2174. var temp,
  2175. carry = 0,
  2176. i = x.length;
  2177. for (x = x.slice(); i--;) {
  2178. temp = x[i] * k + carry;
  2179. x[i] = temp % base | 0;
  2180. carry = temp / base | 0;
  2181. }
  2182. if (carry) x.unshift(carry);
  2183. return x;
  2184. }
  2185. function compare(a, b, aL, bL) {
  2186. var i, r;
  2187. if (aL != bL) {
  2188. r = aL > bL ? 1 : -1;
  2189. } else {
  2190. for (i = r = 0; i < aL; i++) {
  2191. if (a[i] != b[i]) {
  2192. r = a[i] > b[i] ? 1 : -1;
  2193. break;
  2194. }
  2195. }
  2196. }
  2197. return r;
  2198. }
  2199. function subtract(a, b, aL, base) {
  2200. var i = 0;
  2201. // Subtract b from a.
  2202. for (; aL--;) {
  2203. a[aL] -= i;
  2204. i = a[aL] < b[aL] ? 1 : 0;
  2205. a[aL] = i * base + a[aL] - b[aL];
  2206. }
  2207. // Remove leading zeros.
  2208. for (; !a[0] && a.length > 1;) a.shift();
  2209. }
  2210. return function (x, y, pr, rm, dp, base) {
  2211. var cmp, e, i, k, logBase, more, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0,
  2212. yL, yz,
  2213. Ctor = x.constructor,
  2214. sign = x.s == y.s ? 1 : -1,
  2215. xd = x.d,
  2216. yd = y.d;
  2217. // Either NaN, Infinity or 0?
  2218. if (!xd || !xd[0] || !yd || !yd[0]) {
  2219. return new Ctor(// Return NaN if either NaN, or both Infinity or 0.
  2220. !x.s || !y.s || (xd ? yd && xd[0] == yd[0] : !yd) ? NaN :
  2221. // Return ±0 if x is 0 or y is ±Infinity, or return ±Infinity as y is 0.
  2222. xd && xd[0] == 0 || !yd ? sign * 0 : sign / 0);
  2223. }
  2224. if (base) {
  2225. logBase = 1;
  2226. e = x.e - y.e;
  2227. } else {
  2228. base = BASE;
  2229. logBase = LOG_BASE;
  2230. e = mathfloor(x.e / logBase) - mathfloor(y.e / logBase);
  2231. }
  2232. yL = yd.length;
  2233. xL = xd.length;
  2234. q = new Ctor(sign);
  2235. qd = q.d = [];
  2236. // Result exponent may be one less than e.
  2237. // The digit array of a Decimal from toStringBinary may have trailing zeros.
  2238. for (i = 0; yd[i] == (xd[i] || 0); i++);
  2239. if (yd[i] > (xd[i] || 0)) e--;
  2240. if (pr == null) {
  2241. sd = pr = Ctor.precision;
  2242. rm = Ctor.rounding;
  2243. } else if (dp) {
  2244. sd = pr + (x.e - y.e) + 1;
  2245. } else {
  2246. sd = pr;
  2247. }
  2248. if (sd < 0) {
  2249. qd.push(1);
  2250. more = true;
  2251. } else {
  2252. // Convert precision in number of base 10 digits to base 1e7 digits.
  2253. sd = sd / logBase + 2 | 0;
  2254. i = 0;
  2255. // divisor < 1e7
  2256. if (yL == 1) {
  2257. k = 0;
  2258. yd = yd[0];
  2259. sd++;
  2260. // k is the carry.
  2261. for (; (i < xL || k) && sd--; i++) {
  2262. t = k * base + (xd[i] || 0);
  2263. qd[i] = t / yd | 0;
  2264. k = t % yd | 0;
  2265. }
  2266. more = k || i < xL;
  2267. // divisor >= 1e7
  2268. } else {
  2269. // Normalise xd and yd so highest order digit of yd is >= base/2
  2270. k = base / (yd[0] + 1) | 0;
  2271. if (k > 1) {
  2272. yd = multiplyInteger(yd, k, base);
  2273. xd = multiplyInteger(xd, k, base);
  2274. yL = yd.length;
  2275. xL = xd.length;
  2276. }
  2277. xi = yL;
  2278. rem = xd.slice(0, yL);
  2279. remL = rem.length;
  2280. // Add zeros to make remainder as long as divisor.
  2281. for (; remL < yL;) rem[remL++] = 0;
  2282. yz = yd.slice();
  2283. yz.unshift(0);
  2284. yd0 = yd[0];
  2285. if (yd[1] >= base / 2) ++yd0;
  2286. do {
  2287. k = 0;
  2288. // Compare divisor and remainder.
  2289. cmp = compare(yd, rem, yL, remL);
  2290. // If divisor < remainder.
  2291. if (cmp < 0) {
  2292. // Calculate trial digit, k.
  2293. rem0 = rem[0];
  2294. if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);
  2295. // k will be how many times the divisor goes into the current remainder.
  2296. k = rem0 / yd0 | 0;
  2297. // Algorithm:
  2298. // 1. product = divisor * trial digit (k)
  2299. // 2. if product > remainder: product -= divisor, k--
  2300. // 3. remainder -= product
  2301. // 4. if product was < remainder at 2:
  2302. // 5. compare new remainder and divisor
  2303. // 6. If remainder > divisor: remainder -= divisor, k++
  2304. if (k > 1) {
  2305. if (k >= base) k = base - 1;
  2306. // product = divisor * trial digit.
  2307. prod = multiplyInteger(yd, k, base);
  2308. prodL = prod.length;
  2309. remL = rem.length;
  2310. // Compare product and remainder.
  2311. cmp = compare(prod, rem, prodL, remL);
  2312. // product > remainder.
  2313. if (cmp == 1) {
  2314. k--;
  2315. // Subtract divisor from product.
  2316. subtract(prod, yL < prodL ? yz : yd, prodL, base);
  2317. }
  2318. } else {
  2319. // cmp is -1.
  2320. // If k is 0, there is no need to compare yd and rem again below, so change cmp to 1
  2321. // to avoid it. If k is 1 there is a need to compare yd and rem again below.
  2322. if (k == 0) cmp = k = 1;
  2323. prod = yd.slice();
  2324. }
  2325. prodL = prod.length;
  2326. if (prodL < remL) prod.unshift(0);
  2327. // Subtract product from remainder.
  2328. subtract(rem, prod, remL, base);
  2329. // If product was < previous remainder.
  2330. if (cmp == -1) {
  2331. remL = rem.length;
  2332. // Compare divisor and new remainder.
  2333. cmp = compare(yd, rem, yL, remL);
  2334. // If divisor < new remainder, subtract divisor from remainder.
  2335. if (cmp < 1) {
  2336. k++;
  2337. // Subtract divisor from remainder.
  2338. subtract(rem, yL < remL ? yz : yd, remL, base);
  2339. }
  2340. }
  2341. remL = rem.length;
  2342. } else if (cmp === 0) {
  2343. k++;
  2344. rem = [0];
  2345. } // if cmp === 1, k will be 0
  2346. // Add the next digit, k, to the result array.
  2347. qd[i++] = k;
  2348. // Update the remainder.
  2349. if (cmp && rem[0]) {
  2350. rem[remL++] = xd[xi] || 0;
  2351. } else {
  2352. rem = [xd[xi]];
  2353. remL = 1;
  2354. }
  2355. } while ((xi++ < xL || rem[0] !== void 0) && sd--);
  2356. more = rem[0] !== void 0;
  2357. }
  2358. // Leading zero?
  2359. if (!qd[0]) qd.shift();
  2360. }
  2361. // logBase is 1 when divide is being used for base conversion.
  2362. if (logBase == 1) {
  2363. q.e = e;
  2364. inexact = more;
  2365. } else {
  2366. // To calculate q.e, first get the number of digits of qd[0].
  2367. for (i = 1, k = qd[0]; k >= 10; k /= 10) i++;
  2368. q.e = i + e * logBase - 1;
  2369. finalise(q, dp ? pr + q.e + 1 : pr, rm, more);
  2370. }
  2371. return q;
  2372. };
  2373. })();
  2374. /*
  2375. * Round `x` to `sd` significant digits using rounding mode `rm`.
  2376. * Check for over/under-flow.
  2377. */
  2378. function finalise(x, sd, rm, isTruncated) {
  2379. var digits, i, j, k, rd, roundUp, w, xd, xdi,
  2380. Ctor = x.constructor;
  2381. // Don't round if sd is null or undefined.
  2382. out: if (sd != null) {
  2383. xd = x.d;
  2384. // Infinity/NaN.
  2385. if (!xd) return x;
  2386. // rd: the rounding digit, i.e. the digit after the digit that may be rounded up.
  2387. // w: the word of xd containing rd, a base 1e7 number.
  2388. // xdi: the index of w within xd.
  2389. // digits: the number of digits of w.
  2390. // i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if
  2391. // they had leading zeros)
  2392. // j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero).
  2393. // Get the length of the first word of the digits array xd.
  2394. for (digits = 1, k = xd[0]; k >= 10; k /= 10) digits++;
  2395. i = sd - digits;
  2396. // Is the rounding digit in the first word of xd?
  2397. if (i < 0) {
  2398. i += LOG_BASE;
  2399. j = sd;
  2400. w = xd[xdi = 0];
  2401. // Get the rounding digit at index j of w.
  2402. rd = w / mathpow(10, digits - j - 1) % 10 | 0;
  2403. } else {
  2404. xdi = Math.ceil((i + 1) / LOG_BASE);
  2405. k = xd.length;
  2406. if (xdi >= k) {
  2407. if (isTruncated) {
  2408. // Needed by `naturalExponential`, `naturalLogarithm` and `squareRoot`.
  2409. for (; k++ <= xdi;) xd.push(0);
  2410. w = rd = 0;
  2411. digits = 1;
  2412. i %= LOG_BASE;
  2413. j = i - LOG_BASE + 1;
  2414. } else {
  2415. break out;
  2416. }
  2417. } else {
  2418. w = k = xd[xdi];
  2419. // Get the number of digits of w.
  2420. for (digits = 1; k >= 10; k /= 10) digits++;
  2421. // Get the index of rd within w.
  2422. i %= LOG_BASE;
  2423. // Get the index of rd within w, adjusted for leading zeros.
  2424. // The number of leading zeros of w is given by LOG_BASE - digits.
  2425. j = i - LOG_BASE + digits;
  2426. // Get the rounding digit at index j of w.
  2427. rd = j < 0 ? 0 : w / mathpow(10, digits - j - 1) % 10 | 0;
  2428. }
  2429. }
  2430. // Are there any non-zero digits after the rounding digit?
  2431. isTruncated = isTruncated || sd < 0 ||
  2432. xd[xdi + 1] !== void 0 || (j < 0 ? w : w % mathpow(10, digits - j - 1));
  2433. // The expression `w % mathpow(10, digits - j - 1)` returns all the digits of w to the right
  2434. // of the digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression
  2435. // will give 714.
  2436. roundUp = rm < 4
  2437. ? (rd || isTruncated) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))
  2438. : rd > 5 || rd == 5 && (rm == 4 || isTruncated || rm == 6 &&
  2439. // Check whether the digit to the left of the rounding digit is odd.
  2440. ((i > 0 ? j > 0 ? w / mathpow(10, digits - j) : 0 : xd[xdi - 1]) % 10) & 1 ||
  2441. rm == (x.s < 0 ? 8 : 7));
  2442. if (sd < 1 || !xd[0]) {
  2443. xd.length = 0;
  2444. if (roundUp) {
  2445. // Convert sd to decimal places.
  2446. sd -= x.e + 1;
  2447. // 1, 0.1, 0.01, 0.001, 0.0001 etc.
  2448. xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE);
  2449. x.e = -sd || 0;
  2450. } else {
  2451. // Zero.
  2452. xd[0] = x.e = 0;
  2453. }
  2454. return x;
  2455. }
  2456. // Remove excess digits.
  2457. if (i == 0) {
  2458. xd.length = xdi;
  2459. k = 1;
  2460. xdi--;
  2461. } else {
  2462. xd.length = xdi + 1;
  2463. k = mathpow(10, LOG_BASE - i);
  2464. // E.g. 56700 becomes 56000 if 7 is the rounding digit.
  2465. // j > 0 means i > number of leading zeros of w.
  2466. xd[xdi] = j > 0 ? (w / mathpow(10, digits - j) % mathpow(10, j) | 0) * k : 0;
  2467. }
  2468. if (roundUp) {
  2469. for (;;) {
  2470. // Is the digit to be rounded up in the first word of xd?
  2471. if (xdi == 0) {
  2472. // i will be the length of xd[0] before k is added.
  2473. for (i = 1, j = xd[0]; j >= 10; j /= 10) i++;
  2474. j = xd[0] += k;
  2475. for (k = 1; j >= 10; j /= 10) k++;
  2476. // if i != k the length has increased.
  2477. if (i != k) {
  2478. x.e++;
  2479. if (xd[0] == BASE) xd[0] = 1;
  2480. }
  2481. break;
  2482. } else {
  2483. xd[xdi] += k;
  2484. if (xd[xdi] != BASE) break;
  2485. xd[xdi--] = 0;
  2486. k = 1;
  2487. }
  2488. }
  2489. }
  2490. // Remove trailing zeros.
  2491. for (i = xd.length; xd[--i] === 0;) xd.pop();
  2492. }
  2493. if (external) {
  2494. // Overflow?
  2495. if (x.e > Ctor.maxE) {
  2496. // Infinity.
  2497. x.d = null;
  2498. x.e = NaN;
  2499. // Underflow?
  2500. } else if (x.e < Ctor.minE) {
  2501. // Zero.
  2502. x.e = 0;
  2503. x.d = [0];
  2504. // Ctor.underflow = true;
  2505. } // else Ctor.underflow = false;
  2506. }
  2507. return x;
  2508. }
  2509. function finiteToString(x, isExp, sd) {
  2510. if (!x.isFinite()) return nonFiniteToString(x);
  2511. var k,
  2512. e = x.e,
  2513. str = digitsToString(x.d),
  2514. len = str.length;
  2515. if (isExp) {
  2516. if (sd && (k = sd - len) > 0) {
  2517. str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k);
  2518. } else if (len > 1) {
  2519. str = str.charAt(0) + '.' + str.slice(1);
  2520. }
  2521. str = str + (x.e < 0 ? 'e' : 'e+') + x.e;
  2522. } else if (e < 0) {
  2523. str = '0.' + getZeroString(-e - 1) + str;
  2524. if (sd && (k = sd - len) > 0) str += getZeroString(k);
  2525. } else if (e >= len) {
  2526. str += getZeroString(e + 1 - len);
  2527. if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k);
  2528. } else {
  2529. if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k);
  2530. if (sd && (k = sd - len) > 0) {
  2531. if (e + 1 === len) str += '.';
  2532. str += getZeroString(k);
  2533. }
  2534. }
  2535. return str;
  2536. }
  2537. // Calculate the base 10 exponent from the base 1e7 exponent.
  2538. function getBase10Exponent(digits, e) {
  2539. var w = digits[0];
  2540. // Add the number of digits of the first word of the digits array.
  2541. for ( e *= LOG_BASE; w >= 10; w /= 10) e++;
  2542. return e;
  2543. }
  2544. function getLn10(Ctor, sd, pr) {
  2545. if (sd > LN10_PRECISION) {
  2546. // Reset global state in case the exception is caught.
  2547. external = true;
  2548. if (pr) Ctor.precision = pr;
  2549. throw Error(precisionLimitExceeded);
  2550. }
  2551. return finalise(new Ctor(LN10), sd, 1, true);
  2552. }
  2553. function getPi(Ctor, sd, rm) {
  2554. if (sd > PI_PRECISION) throw Error(precisionLimitExceeded);
  2555. return finalise(new Ctor(PI), sd, rm, true);
  2556. }
  2557. function getPrecision(digits) {
  2558. var w = digits.length - 1,
  2559. len = w * LOG_BASE + 1;
  2560. w = digits[w];
  2561. // If non-zero...
  2562. if (w) {
  2563. // Subtract the number of trailing zeros of the last word.
  2564. for (; w % 10 == 0; w /= 10) len--;
  2565. // Add the number of digits of the first word.
  2566. for (w = digits[0]; w >= 10; w /= 10) len++;
  2567. }
  2568. return len;
  2569. }
  2570. function getZeroString(k) {
  2571. var zs = '';
  2572. for (; k--;) zs += '0';
  2573. return zs;
  2574. }
  2575. /*
  2576. * Return a new Decimal whose value is the value of Decimal `x` to the power `n`, where `n` is an
  2577. * integer of type number.
  2578. *
  2579. * Implements 'exponentiation by squaring'. Called by `pow` and `parseOther`.
  2580. *
  2581. */
  2582. function intPow(Ctor, x, n, pr) {
  2583. var isTruncated,
  2584. r = new Ctor(1),
  2585. // Max n of 9007199254740991 takes 53 loop iterations.
  2586. // Maximum digits array length; leaves [28, 34] guard digits.
  2587. k = Math.ceil(pr / LOG_BASE + 4);
  2588. external = false;
  2589. for (;;) {
  2590. if (n % 2) {
  2591. r = r.times(x);
  2592. if (truncate(r.d, k)) isTruncated = true;
  2593. }
  2594. n = mathfloor(n / 2);
  2595. if (n === 0) {
  2596. // To ensure correct rounding when r.d is truncated, increment the last word if it is zero.
  2597. n = r.d.length - 1;
  2598. if (isTruncated && r.d[n] === 0) ++r.d[n];
  2599. break;
  2600. }
  2601. x = x.times(x);
  2602. truncate(x.d, k);
  2603. }
  2604. external = true;
  2605. return r;
  2606. }
  2607. function isOdd(n) {
  2608. return n.d[n.d.length - 1] & 1;
  2609. }
  2610. /*
  2611. * Handle `max` and `min`. `ltgt` is 'lt' or 'gt'.
  2612. */
  2613. function maxOrMin(Ctor, args, ltgt) {
  2614. var y,
  2615. x = new Ctor(args[0]),
  2616. i = 0;
  2617. for (; ++i < args.length;) {
  2618. y = new Ctor(args[i]);
  2619. if (!y.s) {
  2620. x = y;
  2621. break;
  2622. } else if (x[ltgt](y)) {
  2623. x = y;
  2624. }
  2625. }
  2626. return x;
  2627. }
  2628. /*
  2629. * Return a new Decimal whose value is the natural exponential of `x` rounded to `sd` significant
  2630. * digits.
  2631. *
  2632. * Taylor/Maclaurin series.
  2633. *
  2634. * exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ...
  2635. *
  2636. * Argument reduction:
  2637. * Repeat x = x / 32, k += 5, until |x| < 0.1
  2638. * exp(x) = exp(x / 2^k)^(2^k)
  2639. *
  2640. * Previously, the argument was initially reduced by
  2641. * exp(x) = exp(r) * 10^k where r = x - k * ln10, k = floor(x / ln10)
  2642. * to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was
  2643. * found to be slower than just dividing repeatedly by 32 as above.
  2644. *
  2645. * Max integer argument: exp('20723265836946413') = 6.3e+9000000000000000
  2646. * Min integer argument: exp('-20723265836946411') = 1.2e-9000000000000000
  2647. * (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324)
  2648. *
  2649. * exp(Infinity) = Infinity
  2650. * exp(-Infinity) = 0
  2651. * exp(NaN) = NaN
  2652. * exp(±0) = 1
  2653. *
  2654. * exp(x) is non-terminating for any finite, non-zero x.
  2655. *
  2656. * The result will always be correctly rounded.
  2657. *
  2658. */
  2659. function naturalExponential(x, sd) {
  2660. var denominator, guard, j, pow, sum, t, wpr,
  2661. rep = 0,
  2662. i = 0,
  2663. k = 0,
  2664. Ctor = x.constructor,
  2665. rm = Ctor.rounding,
  2666. pr = Ctor.precision;
  2667. // 0/NaN/Infinity?
  2668. if (!x.d || !x.d[0] || x.e > 17) {
  2669. return new Ctor(x.d
  2670. ? !x.d[0] ? 1 : x.s < 0 ? 0 : 1 / 0
  2671. : x.s ? x.s < 0 ? 0 : x : 0 / 0);
  2672. }
  2673. if (sd == null) {
  2674. external = false;
  2675. wpr = pr;
  2676. } else {
  2677. wpr = sd;
  2678. }
  2679. t = new Ctor(0.03125);
  2680. // while abs(x) >= 0.1
  2681. while (x.e > -2) {
  2682. // x = x / 2^5
  2683. x = x.times(t);
  2684. k += 5;
  2685. }
  2686. // Use 2 * log10(2^k) + 5 (empirically derived) to estimate the increase in precision
  2687. // necessary to ensure the first 4 rounding digits are correct.
  2688. guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0;
  2689. wpr += guard;
  2690. denominator = pow = sum = new Ctor(1);
  2691. Ctor.precision = wpr;
  2692. for (;;) {
  2693. pow = finalise(pow.times(x), wpr, 1);
  2694. denominator = denominator.times(++i);
  2695. t = sum.plus(divide(pow, denominator, wpr, 1));
  2696. if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
  2697. j = k;
  2698. while (j--) sum = finalise(sum.times(sum), wpr, 1);
  2699. // Check to see if the first 4 rounding digits are [49]999.
  2700. // If so, repeat the summation with a higher precision, otherwise
  2701. // e.g. with precision: 18, rounding: 1
  2702. // exp(18.404272462595034083567793919843761) = 98372560.1229999999 (should be 98372560.123)
  2703. // `wpr - guard` is the index of first rounding digit.
  2704. if (sd == null) {
  2705. if (rep < 3 && checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {
  2706. Ctor.precision = wpr += 10;
  2707. denominator = pow = t = new Ctor(1);
  2708. i = 0;
  2709. rep++;
  2710. } else {
  2711. return finalise(sum, Ctor.precision = pr, rm, external = true);
  2712. }
  2713. } else {
  2714. Ctor.precision = pr;
  2715. return sum;
  2716. }
  2717. }
  2718. sum = t;
  2719. }
  2720. }
  2721. /*
  2722. * Return a new Decimal whose value is the natural logarithm of `x` rounded to `sd` significant
  2723. * digits.
  2724. *
  2725. * ln(-n) = NaN
  2726. * ln(0) = -Infinity
  2727. * ln(-0) = -Infinity
  2728. * ln(1) = 0
  2729. * ln(Infinity) = Infinity
  2730. * ln(-Infinity) = NaN
  2731. * ln(NaN) = NaN
  2732. *
  2733. * ln(n) (n != 1) is non-terminating.
  2734. *
  2735. */
  2736. function naturalLogarithm(y, sd) {
  2737. var c, c0, denominator, e, numerator, rep, sum, t, wpr, x1, x2,
  2738. n = 1,
  2739. guard = 10,
  2740. x = y,
  2741. xd = x.d,
  2742. Ctor = x.constructor,
  2743. rm = Ctor.rounding,
  2744. pr = Ctor.precision;
  2745. // Is x negative or Infinity, NaN, 0 or 1?
  2746. if (x.s < 0 || !xd || !xd[0] || !x.e && xd[0] == 1 && xd.length == 1) {
  2747. return new Ctor(xd && !xd[0] ? -1 / 0 : x.s != 1 ? NaN : xd ? 0 : x);
  2748. }
  2749. if (sd == null) {
  2750. external = false;
  2751. wpr = pr;
  2752. } else {
  2753. wpr = sd;
  2754. }
  2755. Ctor.precision = wpr += guard;
  2756. c = digitsToString(xd);
  2757. c0 = c.charAt(0);
  2758. if (Math.abs(e = x.e) < 1.5e15) {
  2759. // Argument reduction.
  2760. // The series converges faster the closer the argument is to 1, so using
  2761. // ln(a^b) = b * ln(a), ln(a) = ln(a^b) / b
  2762. // multiply the argument by itself until the leading digits of the significand are 7, 8, 9,
  2763. // 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can
  2764. // later be divided by this number, then separate out the power of 10 using
  2765. // ln(a*10^b) = ln(a) + b*ln(10).
  2766. // max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14).
  2767. //while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) {
  2768. // max n is 6 (gives 0.7 - 1.3)
  2769. while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) {
  2770. x = x.times(y);
  2771. c = digitsToString(x.d);
  2772. c0 = c.charAt(0);
  2773. n++;
  2774. }
  2775. e = x.e;
  2776. if (c0 > 1) {
  2777. x = new Ctor('0.' + c);
  2778. e++;
  2779. } else {
  2780. x = new Ctor(c0 + '.' + c.slice(1));
  2781. }
  2782. } else {
  2783. // The argument reduction method above may result in overflow if the argument y is a massive
  2784. // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this
  2785. // function using ln(x*10^e) = ln(x) + e*ln(10).
  2786. t = getLn10(Ctor, wpr + 2, pr).times(e + '');
  2787. x = naturalLogarithm(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t);
  2788. Ctor.precision = pr;
  2789. return sd == null ? finalise(x, pr, rm, external = true) : x;
  2790. }
  2791. // x1 is x reduced to a value near 1.
  2792. x1 = x;
  2793. // Taylor series.
  2794. // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...)
  2795. // where x = (y - 1)/(y + 1) (|x| < 1)
  2796. sum = numerator = x = divide(x.minus(1), x.plus(1), wpr, 1);
  2797. x2 = finalise(x.times(x), wpr, 1);
  2798. denominator = 3;
  2799. for (;;) {
  2800. numerator = finalise(numerator.times(x2), wpr, 1);
  2801. t = sum.plus(divide(numerator, new Ctor(denominator), wpr, 1));
  2802. if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
  2803. sum = sum.times(2);
  2804. // Reverse the argument reduction. Check that e is not 0 because, besides preventing an
  2805. // unnecessary calculation, -0 + 0 = +0 and to ensure correct rounding -0 needs to stay -0.
  2806. if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + ''));
  2807. sum = divide(sum, new Ctor(n), wpr, 1);
  2808. // Is rm > 3 and the first 4 rounding digits 4999, or rm < 4 (or the summation has
  2809. // been repeated previously) and the first 4 rounding digits 9999?
  2810. // If so, restart the summation with a higher precision, otherwise
  2811. // e.g. with precision: 12, rounding: 1
  2812. // ln(135520028.6126091714265381533) = 18.7246299999 when it should be 18.72463.
  2813. // `wpr - guard` is the index of first rounding digit.
  2814. if (sd == null) {
  2815. if (checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {
  2816. Ctor.precision = wpr += guard;
  2817. t = numerator = x = divide(x1.minus(1), x1.plus(1), wpr, 1);
  2818. x2 = finalise(x.times(x), wpr, 1);
  2819. denominator = rep = 1;
  2820. } else {
  2821. return finalise(sum, Ctor.precision = pr, rm, external = true);
  2822. }
  2823. } else {
  2824. Ctor.precision = pr;
  2825. return sum;
  2826. }
  2827. }
  2828. sum = t;
  2829. denominator += 2;
  2830. }
  2831. }
  2832. // ±Infinity, NaN.
  2833. function nonFiniteToString(x) {
  2834. // Unsigned.
  2835. return String(x.s * x.s / 0);
  2836. }
  2837. /*
  2838. * Parse the value of a new Decimal `x` from string `str`.
  2839. */
  2840. function parseDecimal(x, str) {
  2841. var e, i, len;
  2842. // Decimal point?
  2843. if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');
  2844. // Exponential form?
  2845. if ((i = str.search(/e/i)) > 0) {
  2846. // Determine exponent.
  2847. if (e < 0) e = i;
  2848. e += +str.slice(i + 1);
  2849. str = str.substring(0, i);
  2850. } else if (e < 0) {
  2851. // Integer.
  2852. e = str.length;
  2853. }
  2854. // Determine leading zeros.
  2855. for (i = 0; str.charCodeAt(i) === 48; i++);
  2856. // Determine trailing zeros.
  2857. for (len = str.length; str.charCodeAt(len - 1) === 48; --len);
  2858. str = str.slice(i, len);
  2859. if (str) {
  2860. len -= i;
  2861. x.e = e = e - i - 1;
  2862. x.d = [];
  2863. // Transform base
  2864. // e is the base 10 exponent.
  2865. // i is where to slice str to get the first word of the digits array.
  2866. i = (e + 1) % LOG_BASE;
  2867. if (e < 0) i += LOG_BASE;
  2868. if (i < len) {
  2869. if (i) x.d.push(+str.slice(0, i));
  2870. for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE));
  2871. str = str.slice(i);
  2872. i = LOG_BASE - str.length;
  2873. } else {
  2874. i -= len;
  2875. }
  2876. for (; i--;) str += '0';
  2877. x.d.push(+str);
  2878. if (external) {
  2879. // Overflow?
  2880. if (x.e > x.constructor.maxE) {
  2881. // Infinity.
  2882. x.d = null;
  2883. x.e = NaN;
  2884. // Underflow?
  2885. } else if (x.e < x.constructor.minE) {
  2886. // Zero.
  2887. x.e = 0;
  2888. x.d = [0];
  2889. // x.constructor.underflow = true;
  2890. } // else x.constructor.underflow = false;
  2891. }
  2892. } else {
  2893. // Zero.
  2894. x.e = 0;
  2895. x.d = [0];
  2896. }
  2897. return x;
  2898. }
  2899. /*
  2900. * Parse the value of a new Decimal `x` from a string `str`, which is not a decimal value.
  2901. */
  2902. function parseOther(x, str) {
  2903. var base, Ctor, divisor, i, isFloat, len, p, xd, xe;
  2904. if (str === 'Infinity' || str === 'NaN') {
  2905. if (!+str) x.s = NaN;
  2906. x.e = NaN;
  2907. x.d = null;
  2908. return x;
  2909. }
  2910. if (isHex.test(str)) {
  2911. base = 16;
  2912. str = str.toLowerCase();
  2913. } else if (isBinary.test(str)) {
  2914. base = 2;
  2915. } else if (isOctal.test(str)) {
  2916. base = 8;
  2917. } else {
  2918. throw Error(invalidArgument + str);
  2919. }
  2920. // Is there a binary exponent part?
  2921. i = str.search(/p/i);
  2922. if (i > 0) {
  2923. p = +str.slice(i + 1);
  2924. str = str.substring(2, i);
  2925. } else {
  2926. str = str.slice(2);
  2927. }
  2928. // Convert `str` as an integer then divide the result by `base` raised to a power such that the
  2929. // fraction part will be restored.
  2930. i = str.indexOf('.');
  2931. isFloat = i >= 0;
  2932. Ctor = x.constructor;
  2933. if (isFloat) {
  2934. str = str.replace('.', '');
  2935. len = str.length;
  2936. i = len - i;
  2937. // log[10](16) = 1.2041... , log[10](88) = 1.9444....
  2938. divisor = intPow(Ctor, new Ctor(base), i, i * 2);
  2939. }
  2940. xd = convertBase(str, base, BASE);
  2941. xe = xd.length - 1;
  2942. // Remove trailing zeros.
  2943. for (i = xe; xd[i] === 0; --i) xd.pop();
  2944. if (i < 0) return new Ctor(x.s * 0);
  2945. x.e = getBase10Exponent(xd, xe);
  2946. x.d = xd;
  2947. external = false;
  2948. // At what precision to perform the division to ensure exact conversion?
  2949. // maxDecimalIntegerPartDigitCount = ceil(log[10](b) * otherBaseIntegerPartDigitCount)
  2950. // log[10](2) = 0.30103, log[10](8) = 0.90309, log[10](16) = 1.20412
  2951. // E.g. ceil(1.2 * 3) = 4, so up to 4 decimal digits are needed to represent 3 hex int digits.
  2952. // maxDecimalFractionPartDigitCount = {Hex:4|Oct:3|Bin:1} * otherBaseFractionPartDigitCount
  2953. // Therefore using 4 * the number of digits of str will always be enough.
  2954. if (isFloat) x = divide(x, divisor, len * 4);
  2955. // Multiply by the binary exponent part if present.
  2956. if (p) x = x.times(Math.abs(p) < 54 ? mathpow(2, p) : Decimal.pow(2, p));
  2957. external = true;
  2958. return x;
  2959. }
  2960. /*
  2961. * sin(x) = x - x^3/3! + x^5/5! - ...
  2962. * |x| < pi/2
  2963. *
  2964. */
  2965. function sine(Ctor, x) {
  2966. var k,
  2967. len = x.d.length;
  2968. if (len < 3) return taylorSeries(Ctor, 2, x, x);
  2969. // Argument reduction: sin(5x) = 16*sin^5(x) - 20*sin^3(x) + 5*sin(x)
  2970. // i.e. sin(x) = 16*sin^5(x/5) - 20*sin^3(x/5) + 5*sin(x/5)
  2971. // and sin(x) = sin(x/5)(5 + sin^2(x/5)(16sin^2(x/5) - 20))
  2972. // Estimate the optimum number of times to use the argument reduction.
  2973. k = 1.4 * Math.sqrt(len);
  2974. k = k > 16 ? 16 : k | 0;
  2975. x = x.times(1 / tinyPow(5, k));
  2976. x = taylorSeries(Ctor, 2, x, x);
  2977. // Reverse argument reduction
  2978. var sin2_x,
  2979. d5 = new Ctor(5),
  2980. d16 = new Ctor(16),
  2981. d20 = new Ctor(20);
  2982. for (; k--;) {
  2983. sin2_x = x.times(x);
  2984. x = x.times(d5.plus(sin2_x.times(d16.times(sin2_x).minus(d20))));
  2985. }
  2986. return x;
  2987. }
  2988. // Calculate Taylor series for `cos`, `cosh`, `sin` and `sinh`.
  2989. function taylorSeries(Ctor, n, x, y, isHyperbolic) {
  2990. var j, t, u, x2,
  2991. i = 1,
  2992. pr = Ctor.precision,
  2993. k = Math.ceil(pr / LOG_BASE);
  2994. external = false;
  2995. x2 = x.times(x);
  2996. u = new Ctor(y);
  2997. for (;;) {
  2998. t = divide(u.times(x2), new Ctor(n++ * n++), pr, 1);
  2999. u = isHyperbolic ? y.plus(t) : y.minus(t);
  3000. y = divide(t.times(x2), new Ctor(n++ * n++), pr, 1);
  3001. t = u.plus(y);
  3002. if (t.d[k] !== void 0) {
  3003. for (j = k; t.d[j] === u.d[j] && j--;);
  3004. if (j == -1) break;
  3005. }
  3006. j = u;
  3007. u = y;
  3008. y = t;
  3009. t = j;
  3010. i++;
  3011. }
  3012. external = true;
  3013. t.d.length = k + 1;
  3014. return t;
  3015. }
  3016. // Exponent e must be positive and non-zero.
  3017. function tinyPow(b, e) {
  3018. var n = b;
  3019. while (--e) n *= b;
  3020. return n;
  3021. }
  3022. // Return the absolute value of `x` reduced to less than or equal to half pi.
  3023. function toLessThanHalfPi(Ctor, x) {
  3024. var t,
  3025. isNeg = x.s < 0,
  3026. pi = getPi(Ctor, Ctor.precision, 1),
  3027. halfPi = pi.times(0.5);
  3028. x = x.abs();
  3029. if (x.lte(halfPi)) {
  3030. quadrant = isNeg ? 4 : 1;
  3031. return x;
  3032. }
  3033. t = x.divToInt(pi);
  3034. if (t.isZero()) {
  3035. quadrant = isNeg ? 3 : 2;
  3036. } else {
  3037. x = x.minus(t.times(pi));
  3038. // 0 <= x < pi
  3039. if (x.lte(halfPi)) {
  3040. quadrant = isOdd(t) ? (isNeg ? 2 : 3) : (isNeg ? 4 : 1);
  3041. return x;
  3042. }
  3043. quadrant = isOdd(t) ? (isNeg ? 1 : 4) : (isNeg ? 3 : 2);
  3044. }
  3045. return x.minus(pi).abs();
  3046. }
  3047. /*
  3048. * Return the value of Decimal `x` as a string in base `baseOut`.
  3049. *
  3050. * If the optional `sd` argument is present include a binary exponent suffix.
  3051. */
  3052. function toStringBinary(x, baseOut, sd, rm) {
  3053. var base, e, i, k, len, roundUp, str, xd, y,
  3054. Ctor = x.constructor,
  3055. isExp = sd !== void 0;
  3056. if (isExp) {
  3057. checkInt32(sd, 1, MAX_DIGITS);
  3058. if (rm === void 0) rm = Ctor.rounding;
  3059. else checkInt32(rm, 0, 8);
  3060. } else {
  3061. sd = Ctor.precision;
  3062. rm = Ctor.rounding;
  3063. }
  3064. if (!x.isFinite()) {
  3065. str = nonFiniteToString(x);
  3066. } else {
  3067. str = finiteToString(x);
  3068. i = str.indexOf('.');
  3069. // Use exponential notation according to `toExpPos` and `toExpNeg`? No, but if required:
  3070. // maxBinaryExponent = floor((decimalExponent + 1) * log[2](10))
  3071. // minBinaryExponent = floor(decimalExponent * log[2](10))
  3072. // log[2](10) = 3.321928094887362347870319429489390175864
  3073. if (isExp) {
  3074. base = 2;
  3075. if (baseOut == 16) {
  3076. sd = sd * 4 - 3;
  3077. } else if (baseOut == 8) {
  3078. sd = sd * 3 - 2;
  3079. }
  3080. } else {
  3081. base = baseOut;
  3082. }
  3083. // Convert the number as an integer then divide the result by its base raised to a power such
  3084. // that the fraction part will be restored.
  3085. // Non-integer.
  3086. if (i >= 0) {
  3087. str = str.replace('.', '');
  3088. y = new Ctor(1);
  3089. y.e = str.length - i;
  3090. y.d = convertBase(finiteToString(y), 10, base);
  3091. y.e = y.d.length;
  3092. }
  3093. xd = convertBase(str, 10, base);
  3094. e = len = xd.length;
  3095. // Remove trailing zeros.
  3096. for (; xd[--len] == 0;) xd.pop();
  3097. if (!xd[0]) {
  3098. str = isExp ? '0p+0' : '0';
  3099. } else {
  3100. if (i < 0) {
  3101. e--;
  3102. } else {
  3103. x = new Ctor(x);
  3104. x.d = xd;
  3105. x.e = e;
  3106. x = divide(x, y, sd, rm, 0, base);
  3107. xd = x.d;
  3108. e = x.e;
  3109. roundUp = inexact;
  3110. }
  3111. // The rounding digit, i.e. the digit after the digit that may be rounded up.
  3112. i = xd[sd];
  3113. k = base / 2;
  3114. roundUp = roundUp || xd[sd + 1] !== void 0;
  3115. roundUp = rm < 4
  3116. ? (i !== void 0 || roundUp) && (rm === 0 || rm === (x.s < 0 ? 3 : 2))
  3117. : i > k || i === k && (rm === 4 || roundUp || rm === 6 && xd[sd - 1] & 1 ||
  3118. rm === (x.s < 0 ? 8 : 7));
  3119. xd.length = sd;
  3120. if (roundUp) {
  3121. // Rounding up may mean the previous digit has to be rounded up and so on.
  3122. for (; ++xd[--sd] > base - 1;) {
  3123. xd[sd] = 0;
  3124. if (!sd) {
  3125. ++e;
  3126. xd.unshift(1);
  3127. }
  3128. }
  3129. }
  3130. // Determine trailing zeros.
  3131. for (len = xd.length; !xd[len - 1]; --len);
  3132. // E.g. [4, 11, 15] becomes 4bf.
  3133. for (i = 0, str = ''; i < len; i++) str += NUMERALS.charAt(xd[i]);
  3134. // Add binary exponent suffix?
  3135. if (isExp) {
  3136. if (len > 1) {
  3137. if (baseOut == 16 || baseOut == 8) {
  3138. i = baseOut == 16 ? 4 : 3;
  3139. for (--len; len % i; len++) str += '0';
  3140. xd = convertBase(str, base, baseOut);
  3141. for (len = xd.length; !xd[len - 1]; --len);
  3142. // xd[0] will always be be 1
  3143. for (i = 1, str = '1.'; i < len; i++) str += NUMERALS.charAt(xd[i]);
  3144. } else {
  3145. str = str.charAt(0) + '.' + str.slice(1);
  3146. }
  3147. }
  3148. str = str + (e < 0 ? 'p' : 'p+') + e;
  3149. } else if (e < 0) {
  3150. for (; ++e;) str = '0' + str;
  3151. str = '0.' + str;
  3152. } else {
  3153. if (++e > len) for (e -= len; e-- ;) str += '0';
  3154. else if (e < len) str = str.slice(0, e) + '.' + str.slice(e);
  3155. }
  3156. }
  3157. str = (baseOut == 16 ? '0x' : baseOut == 2 ? '0b' : baseOut == 8 ? '0o' : '') + str;
  3158. }
  3159. return x.s < 0 ? '-' + str : str;
  3160. }
  3161. // Does not strip trailing zeros.
  3162. function truncate(arr, len) {
  3163. if (arr.length > len) {
  3164. arr.length = len;
  3165. return true;
  3166. }
  3167. }
  3168. // Decimal methods
  3169. /*
  3170. * abs
  3171. * acos
  3172. * acosh
  3173. * add
  3174. * asin
  3175. * asinh
  3176. * atan
  3177. * atanh
  3178. * atan2
  3179. * cbrt
  3180. * ceil
  3181. * clone
  3182. * config
  3183. * cos
  3184. * cosh
  3185. * div
  3186. * exp
  3187. * floor
  3188. * hypot
  3189. * ln
  3190. * log
  3191. * log2
  3192. * log10
  3193. * max
  3194. * min
  3195. * mod
  3196. * mul
  3197. * pow
  3198. * random
  3199. * round
  3200. * set
  3201. * sign
  3202. * sin
  3203. * sinh
  3204. * sqrt
  3205. * sub
  3206. * tan
  3207. * tanh
  3208. * trunc
  3209. */
  3210. /*
  3211. * Return a new Decimal whose value is the absolute value of `x`.
  3212. *
  3213. * x {number|string|Decimal}
  3214. *
  3215. */
  3216. function abs(x) {
  3217. return new this(x).abs();
  3218. }
  3219. /*
  3220. * Return a new Decimal whose value is the arccosine in radians of `x`.
  3221. *
  3222. * x {number|string|Decimal}
  3223. *
  3224. */
  3225. function acos(x) {
  3226. return new this(x).acos();
  3227. }
  3228. /*
  3229. * Return a new Decimal whose value is the inverse of the hyperbolic cosine of `x`, rounded to
  3230. * `precision` significant digits using rounding mode `rounding`.
  3231. *
  3232. * x {number|string|Decimal} A value in radians.
  3233. *
  3234. */
  3235. function acosh(x) {
  3236. return new this(x).acosh();
  3237. }
  3238. /*
  3239. * Return a new Decimal whose value is the sum of `x` and `y`, rounded to `precision` significant
  3240. * digits using rounding mode `rounding`.
  3241. *
  3242. * x {number|string|Decimal}
  3243. * y {number|string|Decimal}
  3244. *
  3245. */
  3246. function add(x, y) {
  3247. return new this(x).plus(y);
  3248. }
  3249. /*
  3250. * Return a new Decimal whose value is the arcsine in radians of `x`, rounded to `precision`
  3251. * significant digits using rounding mode `rounding`.
  3252. *
  3253. * x {number|string|Decimal}
  3254. *
  3255. */
  3256. function asin(x) {
  3257. return new this(x).asin();
  3258. }
  3259. /*
  3260. * Return a new Decimal whose value is the inverse of the hyperbolic sine of `x`, rounded to
  3261. * `precision` significant digits using rounding mode `rounding`.
  3262. *
  3263. * x {number|string|Decimal} A value in radians.
  3264. *
  3265. */
  3266. function asinh(x) {
  3267. return new this(x).asinh();
  3268. }
  3269. /*
  3270. * Return a new Decimal whose value is the arctangent in radians of `x`, rounded to `precision`
  3271. * significant digits using rounding mode `rounding`.
  3272. *
  3273. * x {number|string|Decimal}
  3274. *
  3275. */
  3276. function atan(x) {
  3277. return new this(x).atan();
  3278. }
  3279. /*
  3280. * Return a new Decimal whose value is the inverse of the hyperbolic tangent of `x`, rounded to
  3281. * `precision` significant digits using rounding mode `rounding`.
  3282. *
  3283. * x {number|string|Decimal} A value in radians.
  3284. *
  3285. */
  3286. function atanh(x) {
  3287. return new this(x).atanh();
  3288. }
  3289. /*
  3290. * Return a new Decimal whose value is the arctangent in radians of `y/x` in the range -pi to pi
  3291. * (inclusive), rounded to `precision` significant digits using rounding mode `rounding`.
  3292. *
  3293. * Domain: [-Infinity, Infinity]
  3294. * Range: [-pi, pi]
  3295. *
  3296. * y {number|string|Decimal} The y-coordinate.
  3297. * x {number|string|Decimal} The x-coordinate.
  3298. *
  3299. * atan2(±0, -0) = ±pi
  3300. * atan2(±0, +0) = ±0
  3301. * atan2(±0, -x) = ±pi for x > 0
  3302. * atan2(±0, x) = ±0 for x > 0
  3303. * atan2(-y, ±0) = -pi/2 for y > 0
  3304. * atan2(y, ±0) = pi/2 for y > 0
  3305. * atan2(±y, -Infinity) = ±pi for finite y > 0
  3306. * atan2(±y, +Infinity) = ±0 for finite y > 0
  3307. * atan2(±Infinity, x) = ±pi/2 for finite x
  3308. * atan2(±Infinity, -Infinity) = ±3*pi/4
  3309. * atan2(±Infinity, +Infinity) = ±pi/4
  3310. * atan2(NaN, x) = NaN
  3311. * atan2(y, NaN) = NaN
  3312. *
  3313. */
  3314. function atan2(y, x) {
  3315. y = new this(y);
  3316. x = new this(x);
  3317. var r,
  3318. pr = this.precision,
  3319. rm = this.rounding,
  3320. wpr = pr + 4;
  3321. // Either NaN
  3322. if (!y.s || !x.s) {
  3323. r = new this(NaN);
  3324. // Both ±Infinity
  3325. } else if (!y.d && !x.d) {
  3326. r = getPi(this, wpr, 1).times(x.s > 0 ? 0.25 : 0.75);
  3327. r.s = y.s;
  3328. // x is ±Infinity or y is ±0
  3329. } else if (!x.d || y.isZero()) {
  3330. r = x.s < 0 ? getPi(this, pr, rm) : new this(0);
  3331. r.s = y.s;
  3332. // y is ±Infinity or x is ±0
  3333. } else if (!y.d || x.isZero()) {
  3334. r = getPi(this, wpr, 1).times(0.5);
  3335. r.s = y.s;
  3336. // Both non-zero and finite
  3337. } else if (x.s < 0) {
  3338. this.precision = wpr;
  3339. this.rounding = 1;
  3340. r = this.atan(divide(y, x, wpr, 1));
  3341. x = getPi(this, wpr, 1);
  3342. this.precision = pr;
  3343. this.rounding = rm;
  3344. r = y.s < 0 ? r.minus(x) : r.plus(x);
  3345. } else {
  3346. r = this.atan(divide(y, x, wpr, 1));
  3347. }
  3348. return r;
  3349. }
  3350. /*
  3351. * Return a new Decimal whose value is the cube root of `x`, rounded to `precision` significant
  3352. * digits using rounding mode `rounding`.
  3353. *
  3354. * x {number|string|Decimal}
  3355. *
  3356. */
  3357. function cbrt(x) {
  3358. return new this(x).cbrt();
  3359. }
  3360. /*
  3361. * Return a new Decimal whose value is `x` rounded to an integer using `ROUND_CEIL`.
  3362. *
  3363. * x {number|string|Decimal}
  3364. *
  3365. */
  3366. function ceil(x) {
  3367. return finalise(x = new this(x), x.e + 1, 2);
  3368. }
  3369. /*
  3370. * Configure global settings for a Decimal constructor.
  3371. *
  3372. * `obj` is an object with one or more of the following properties,
  3373. *
  3374. * precision {number}
  3375. * rounding {number}
  3376. * toExpNeg {number}
  3377. * toExpPos {number}
  3378. * maxE {number}
  3379. * minE {number}
  3380. * modulo {number}
  3381. * crypto {boolean|number}
  3382. * defaults {true}
  3383. *
  3384. * E.g. Decimal.config({ precision: 20, rounding: 4 })
  3385. *
  3386. */
  3387. function config(obj) {
  3388. if (!obj || typeof obj !== 'object') throw Error(decimalError + 'Object expected');
  3389. var i, p, v,
  3390. useDefaults = obj.defaults === true,
  3391. ps = [
  3392. 'precision', 1, MAX_DIGITS,
  3393. 'rounding', 0, 8,
  3394. 'toExpNeg', -EXP_LIMIT, 0,
  3395. 'toExpPos', 0, EXP_LIMIT,
  3396. 'maxE', 0, EXP_LIMIT,
  3397. 'minE', -EXP_LIMIT, 0,
  3398. 'modulo', 0, 9
  3399. ];
  3400. for (i = 0; i < ps.length; i += 3) {
  3401. if (p = ps[i], useDefaults) this[p] = DEFAULTS[p];
  3402. if ((v = obj[p]) !== void 0) {
  3403. if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v;
  3404. else throw Error(invalidArgument + p + ': ' + v);
  3405. }
  3406. }
  3407. if (p = 'crypto', useDefaults) this[p] = DEFAULTS[p];
  3408. if ((v = obj[p]) !== void 0) {
  3409. if (v === true || v === false || v === 0 || v === 1) {
  3410. if (v) {
  3411. if (typeof crypto != 'undefined' && crypto &&
  3412. (crypto.getRandomValues || crypto.randomBytes)) {
  3413. this[p] = true;
  3414. } else {
  3415. throw Error(cryptoUnavailable);
  3416. }
  3417. } else {
  3418. this[p] = false;
  3419. }
  3420. } else {
  3421. throw Error(invalidArgument + p + ': ' + v);
  3422. }
  3423. }
  3424. return this;
  3425. }
  3426. /*
  3427. * Return a new Decimal whose value is the cosine of `x`, rounded to `precision` significant
  3428. * digits using rounding mode `rounding`.
  3429. *
  3430. * x {number|string|Decimal} A value in radians.
  3431. *
  3432. */
  3433. function cos(x) {
  3434. return new this(x).cos();
  3435. }
  3436. /*
  3437. * Return a new Decimal whose value is the hyperbolic cosine of `x`, rounded to precision
  3438. * significant digits using rounding mode `rounding`.
  3439. *
  3440. * x {number|string|Decimal} A value in radians.
  3441. *
  3442. */
  3443. function cosh(x) {
  3444. return new this(x).cosh();
  3445. }
  3446. /*
  3447. * Create and return a Decimal constructor with the same configuration properties as this Decimal
  3448. * constructor.
  3449. *
  3450. */
  3451. function clone(obj) {
  3452. var i, p, ps;
  3453. /*
  3454. * The Decimal constructor and exported function.
  3455. * Return a new Decimal instance.
  3456. *
  3457. * v {number|string|Decimal} A numeric value.
  3458. *
  3459. */
  3460. function Decimal(v) {
  3461. var e, i, t,
  3462. x = this;
  3463. // Decimal called without new.
  3464. if (!(x instanceof Decimal)) return new Decimal(v);
  3465. // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor
  3466. // which points to Object.
  3467. x.constructor = Decimal;
  3468. // Duplicate.
  3469. if (v instanceof Decimal) {
  3470. x.s = v.s;
  3471. if (external) {
  3472. if (!v.d || v.e > Decimal.maxE) {
  3473. // Infinity.
  3474. x.e = NaN;
  3475. x.d = null;
  3476. } else if (v.e < Decimal.minE) {
  3477. // Zero.
  3478. x.e = 0;
  3479. x.d = [0];
  3480. } else {
  3481. x.e = v.e;
  3482. x.d = v.d.slice();
  3483. }
  3484. } else {
  3485. x.e = v.e;
  3486. x.d = v.d ? v.d.slice() : v.d;
  3487. }
  3488. return;
  3489. }
  3490. t = typeof v;
  3491. if (t === 'number') {
  3492. if (v === 0) {
  3493. x.s = 1 / v < 0 ? -1 : 1;
  3494. x.e = 0;
  3495. x.d = [0];
  3496. return;
  3497. }
  3498. if (v < 0) {
  3499. v = -v;
  3500. x.s = -1;
  3501. } else {
  3502. x.s = 1;
  3503. }
  3504. // Fast path for small integers.
  3505. if (v === ~~v && v < 1e7) {
  3506. for (e = 0, i = v; i >= 10; i /= 10) e++;
  3507. if (external) {
  3508. if (e > Decimal.maxE) {
  3509. x.e = NaN;
  3510. x.d = null;
  3511. } else if (e < Decimal.minE) {
  3512. x.e = 0;
  3513. x.d = [0];
  3514. } else {
  3515. x.e = e;
  3516. x.d = [v];
  3517. }
  3518. } else {
  3519. x.e = e;
  3520. x.d = [v];
  3521. }
  3522. return;
  3523. // Infinity, NaN.
  3524. } else if (v * 0 !== 0) {
  3525. if (!v) x.s = NaN;
  3526. x.e = NaN;
  3527. x.d = null;
  3528. return;
  3529. }
  3530. return parseDecimal(x, v.toString());
  3531. } else if (t !== 'string') {
  3532. throw Error(invalidArgument + v);
  3533. }
  3534. // Minus sign?
  3535. if ((i = v.charCodeAt(0)) === 45) {
  3536. v = v.slice(1);
  3537. x.s = -1;
  3538. } else {
  3539. // Plus sign?
  3540. if (i === 43) v = v.slice(1);
  3541. x.s = 1;
  3542. }
  3543. return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v);
  3544. }
  3545. Decimal.prototype = P;
  3546. Decimal.ROUND_UP = 0;
  3547. Decimal.ROUND_DOWN = 1;
  3548. Decimal.ROUND_CEIL = 2;
  3549. Decimal.ROUND_FLOOR = 3;
  3550. Decimal.ROUND_HALF_UP = 4;
  3551. Decimal.ROUND_HALF_DOWN = 5;
  3552. Decimal.ROUND_HALF_EVEN = 6;
  3553. Decimal.ROUND_HALF_CEIL = 7;
  3554. Decimal.ROUND_HALF_FLOOR = 8;
  3555. Decimal.EUCLID = 9;
  3556. Decimal.config = Decimal.set = config;
  3557. Decimal.clone = clone;
  3558. Decimal.isDecimal = isDecimalInstance;
  3559. Decimal.abs = abs;
  3560. Decimal.acos = acos;
  3561. Decimal.acosh = acosh; // ES6
  3562. Decimal.add = add;
  3563. Decimal.asin = asin;
  3564. Decimal.asinh = asinh; // ES6
  3565. Decimal.atan = atan;
  3566. Decimal.atanh = atanh; // ES6
  3567. Decimal.atan2 = atan2;
  3568. Decimal.cbrt = cbrt; // ES6
  3569. Decimal.ceil = ceil;
  3570. Decimal.cos = cos;
  3571. Decimal.cosh = cosh; // ES6
  3572. Decimal.div = div;
  3573. Decimal.exp = exp;
  3574. Decimal.floor = floor;
  3575. Decimal.hypot = hypot; // ES6
  3576. Decimal.ln = ln;
  3577. Decimal.log = log;
  3578. Decimal.log10 = log10; // ES6
  3579. Decimal.log2 = log2; // ES6
  3580. Decimal.max = max;
  3581. Decimal.min = min;
  3582. Decimal.mod = mod;
  3583. Decimal.mul = mul;
  3584. Decimal.pow = pow;
  3585. Decimal.random = random;
  3586. Decimal.round = round;
  3587. Decimal.sign = sign; // ES6
  3588. Decimal.sin = sin;
  3589. Decimal.sinh = sinh; // ES6
  3590. Decimal.sqrt = sqrt;
  3591. Decimal.sub = sub;
  3592. Decimal.tan = tan;
  3593. Decimal.tanh = tanh; // ES6
  3594. Decimal.trunc = trunc; // ES6
  3595. if (obj === void 0) obj = {};
  3596. if (obj) {
  3597. if (obj.defaults !== true) {
  3598. ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'maxE', 'minE', 'modulo', 'crypto'];
  3599. for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p];
  3600. }
  3601. }
  3602. Decimal.config(obj);
  3603. return Decimal;
  3604. }
  3605. /*
  3606. * Return a new Decimal whose value is `x` divided by `y`, rounded to `precision` significant
  3607. * digits using rounding mode `rounding`.
  3608. *
  3609. * x {number|string|Decimal}
  3610. * y {number|string|Decimal}
  3611. *
  3612. */
  3613. function div(x, y) {
  3614. return new this(x).div(y);
  3615. }
  3616. /*
  3617. * Return a new Decimal whose value is the natural exponential of `x`, rounded to `precision`
  3618. * significant digits using rounding mode `rounding`.
  3619. *
  3620. * x {number|string|Decimal} The power to which to raise the base of the natural log.
  3621. *
  3622. */
  3623. function exp(x) {
  3624. return new this(x).exp();
  3625. }
  3626. /*
  3627. * Return a new Decimal whose value is `x` round to an integer using `ROUND_FLOOR`.
  3628. *
  3629. * x {number|string|Decimal}
  3630. *
  3631. */
  3632. function floor(x) {
  3633. return finalise(x = new this(x), x.e + 1, 3);
  3634. }
  3635. /*
  3636. * Return a new Decimal whose value is the square root of the sum of the squares of the arguments,
  3637. * rounded to `precision` significant digits using rounding mode `rounding`.
  3638. *
  3639. * hypot(a, b, ...) = sqrt(a^2 + b^2 + ...)
  3640. *
  3641. * arguments {number|string|Decimal}
  3642. *
  3643. */
  3644. function hypot() {
  3645. var i, n,
  3646. t = new this(0);
  3647. external = false;
  3648. for (i = 0; i < arguments.length;) {
  3649. n = new this(arguments[i++]);
  3650. if (!n.d) {
  3651. if (n.s) {
  3652. external = true;
  3653. return new this(1 / 0);
  3654. }
  3655. t = n;
  3656. } else if (t.d) {
  3657. t = t.plus(n.times(n));
  3658. }
  3659. }
  3660. external = true;
  3661. return t.sqrt();
  3662. }
  3663. /*
  3664. * Return true if object is a Decimal instance (where Decimal is any Decimal constructor),
  3665. * otherwise return false.
  3666. *
  3667. */
  3668. function isDecimalInstance(obj) {
  3669. return obj instanceof Decimal || obj && obj.name === '[object Decimal]' || false;
  3670. }
  3671. /*
  3672. * Return a new Decimal whose value is the natural logarithm of `x`, rounded to `precision`
  3673. * significant digits using rounding mode `rounding`.
  3674. *
  3675. * x {number|string|Decimal}
  3676. *
  3677. */
  3678. function ln(x) {
  3679. return new this(x).ln();
  3680. }
  3681. /*
  3682. * Return a new Decimal whose value is the log of `x` to the base `y`, or to base 10 if no base
  3683. * is specified, rounded to `precision` significant digits using rounding mode `rounding`.
  3684. *
  3685. * log[y](x)
  3686. *
  3687. * x {number|string|Decimal} The argument of the logarithm.
  3688. * y {number|string|Decimal} The base of the logarithm.
  3689. *
  3690. */
  3691. function log(x, y) {
  3692. return new this(x).log(y);
  3693. }
  3694. /*
  3695. * Return a new Decimal whose value is the base 2 logarithm of `x`, rounded to `precision`
  3696. * significant digits using rounding mode `rounding`.
  3697. *
  3698. * x {number|string|Decimal}
  3699. *
  3700. */
  3701. function log2(x) {
  3702. return new this(x).log(2);
  3703. }
  3704. /*
  3705. * Return a new Decimal whose value is the base 10 logarithm of `x`, rounded to `precision`
  3706. * significant digits using rounding mode `rounding`.
  3707. *
  3708. * x {number|string|Decimal}
  3709. *
  3710. */
  3711. function log10(x) {
  3712. return new this(x).log(10);
  3713. }
  3714. /*
  3715. * Return a new Decimal whose value is the maximum of the arguments.
  3716. *
  3717. * arguments {number|string|Decimal}
  3718. *
  3719. */
  3720. function max() {
  3721. return maxOrMin(this, arguments, 'lt');
  3722. }
  3723. /*
  3724. * Return a new Decimal whose value is the minimum of the arguments.
  3725. *
  3726. * arguments {number|string|Decimal}
  3727. *
  3728. */
  3729. function min() {
  3730. return maxOrMin(this, arguments, 'gt');
  3731. }
  3732. /*
  3733. * Return a new Decimal whose value is `x` modulo `y`, rounded to `precision` significant digits
  3734. * using rounding mode `rounding`.
  3735. *
  3736. * x {number|string|Decimal}
  3737. * y {number|string|Decimal}
  3738. *
  3739. */
  3740. function mod(x, y) {
  3741. return new this(x).mod(y);
  3742. }
  3743. /*
  3744. * Return a new Decimal whose value is `x` multiplied by `y`, rounded to `precision` significant
  3745. * digits using rounding mode `rounding`.
  3746. *
  3747. * x {number|string|Decimal}
  3748. * y {number|string|Decimal}
  3749. *
  3750. */
  3751. function mul(x, y) {
  3752. return new this(x).mul(y);
  3753. }
  3754. /*
  3755. * Return a new Decimal whose value is `x` raised to the power `y`, rounded to precision
  3756. * significant digits using rounding mode `rounding`.
  3757. *
  3758. * x {number|string|Decimal} The base.
  3759. * y {number|string|Decimal} The exponent.
  3760. *
  3761. */
  3762. function pow(x, y) {
  3763. return new this(x).pow(y);
  3764. }
  3765. /*
  3766. * Returns a new Decimal with a random value equal to or greater than 0 and less than 1, and with
  3767. * `sd`, or `Decimal.precision` if `sd` is omitted, significant digits (or less if trailing zeros
  3768. * are produced).
  3769. *
  3770. * [sd] {number} Significant digits. Integer, 0 to MAX_DIGITS inclusive.
  3771. *
  3772. */
  3773. function random(sd) {
  3774. var d, e, k, n,
  3775. i = 0,
  3776. r = new this(1),
  3777. rd = [];
  3778. if (sd === void 0) sd = this.precision;
  3779. else checkInt32(sd, 1, MAX_DIGITS);
  3780. k = Math.ceil(sd / LOG_BASE);
  3781. if (!this.crypto) {
  3782. for (; i < k;) rd[i++] = Math.random() * 1e7 | 0;
  3783. // Browsers supporting crypto.getRandomValues.
  3784. } else if (crypto.getRandomValues) {
  3785. d = crypto.getRandomValues(new Uint32Array(k));
  3786. for (; i < k;) {
  3787. n = d[i];
  3788. // 0 <= n < 4294967296
  3789. // Probability n >= 4.29e9, is 4967296 / 4294967296 = 0.00116 (1 in 865).
  3790. if (n >= 4.29e9) {
  3791. d[i] = crypto.getRandomValues(new Uint32Array(1))[0];
  3792. } else {
  3793. // 0 <= n <= 4289999999
  3794. // 0 <= (n % 1e7) <= 9999999
  3795. rd[i++] = n % 1e7;
  3796. }
  3797. }
  3798. // Node.js supporting crypto.randomBytes.
  3799. } else if (crypto.randomBytes) {
  3800. // buffer
  3801. d = crypto.randomBytes(k *= 4);
  3802. for (; i < k;) {
  3803. // 0 <= n < 2147483648
  3804. n = d[i] + (d[i + 1] << 8) + (d[i + 2] << 16) + ((d[i + 3] & 0x7f) << 24);
  3805. // Probability n >= 2.14e9, is 7483648 / 2147483648 = 0.0035 (1 in 286).
  3806. if (n >= 2.14e9) {
  3807. crypto.randomBytes(4).copy(d, i);
  3808. } else {
  3809. // 0 <= n <= 2139999999
  3810. // 0 <= (n % 1e7) <= 9999999
  3811. rd.push(n % 1e7);
  3812. i += 4;
  3813. }
  3814. }
  3815. i = k / 4;
  3816. } else {
  3817. throw Error(cryptoUnavailable);
  3818. }
  3819. k = rd[--i];
  3820. sd %= LOG_BASE;
  3821. // Convert trailing digits to zeros according to sd.
  3822. if (k && sd) {
  3823. n = mathpow(10, LOG_BASE - sd);
  3824. rd[i] = (k / n | 0) * n;
  3825. }
  3826. // Remove trailing words which are zero.
  3827. for (; rd[i] === 0; i--) rd.pop();
  3828. // Zero?
  3829. if (i < 0) {
  3830. e = 0;
  3831. rd = [0];
  3832. } else {
  3833. e = -1;
  3834. // Remove leading words which are zero and adjust exponent accordingly.
  3835. for (; rd[0] === 0; e -= LOG_BASE) rd.shift();
  3836. // Count the digits of the first word of rd to determine leading zeros.
  3837. for (k = 1, n = rd[0]; n >= 10; n /= 10) k++;
  3838. // Adjust the exponent for leading zeros of the first word of rd.
  3839. if (k < LOG_BASE) e -= LOG_BASE - k;
  3840. }
  3841. r.e = e;
  3842. r.d = rd;
  3843. return r;
  3844. }
  3845. /*
  3846. * Return a new Decimal whose value is `x` rounded to an integer using rounding mode `rounding`.
  3847. *
  3848. * To emulate `Math.round`, set rounding to 7 (ROUND_HALF_CEIL).
  3849. *
  3850. * x {number|string|Decimal}
  3851. *
  3852. */
  3853. function round(x) {
  3854. return finalise(x = new this(x), x.e + 1, this.rounding);
  3855. }
  3856. /*
  3857. * Return
  3858. * 1 if x > 0,
  3859. * -1 if x < 0,
  3860. * 0 if x is 0,
  3861. * -0 if x is -0,
  3862. * NaN otherwise
  3863. *
  3864. * x {number|string|Decimal}
  3865. *
  3866. */
  3867. function sign(x) {
  3868. x = new this(x);
  3869. return x.d ? (x.d[0] ? x.s : 0 * x.s) : x.s || NaN;
  3870. }
  3871. /*
  3872. * Return a new Decimal whose value is the sine of `x`, rounded to `precision` significant digits
  3873. * using rounding mode `rounding`.
  3874. *
  3875. * x {number|string|Decimal} A value in radians.
  3876. *
  3877. */
  3878. function sin(x) {
  3879. return new this(x).sin();
  3880. }
  3881. /*
  3882. * Return a new Decimal whose value is the hyperbolic sine of `x`, rounded to `precision`
  3883. * significant digits using rounding mode `rounding`.
  3884. *
  3885. * x {number|string|Decimal} A value in radians.
  3886. *
  3887. */
  3888. function sinh(x) {
  3889. return new this(x).sinh();
  3890. }
  3891. /*
  3892. * Return a new Decimal whose value is the square root of `x`, rounded to `precision` significant
  3893. * digits using rounding mode `rounding`.
  3894. *
  3895. * x {number|string|Decimal}
  3896. *
  3897. */
  3898. function sqrt(x) {
  3899. return new this(x).sqrt();
  3900. }
  3901. /*
  3902. * Return a new Decimal whose value is `x` minus `y`, rounded to `precision` significant digits
  3903. * using rounding mode `rounding`.
  3904. *
  3905. * x {number|string|Decimal}
  3906. * y {number|string|Decimal}
  3907. *
  3908. */
  3909. function sub(x, y) {
  3910. return new this(x).sub(y);
  3911. }
  3912. /*
  3913. * Return a new Decimal whose value is the tangent of `x`, rounded to `precision` significant
  3914. * digits using rounding mode `rounding`.
  3915. *
  3916. * x {number|string|Decimal} A value in radians.
  3917. *
  3918. */
  3919. function tan(x) {
  3920. return new this(x).tan();
  3921. }
  3922. /*
  3923. * Return a new Decimal whose value is the hyperbolic tangent of `x`, rounded to `precision`
  3924. * significant digits using rounding mode `rounding`.
  3925. *
  3926. * x {number|string|Decimal} A value in radians.
  3927. *
  3928. */
  3929. function tanh(x) {
  3930. return new this(x).tanh();
  3931. }
  3932. /*
  3933. * Return a new Decimal whose value is `x` truncated to an integer.
  3934. *
  3935. * x {number|string|Decimal}
  3936. *
  3937. */
  3938. function trunc(x) {
  3939. return finalise(x = new this(x), x.e + 1, 1);
  3940. }
  3941. // Create and configure initial Decimal constructor.
  3942. Decimal = clone(DEFAULTS);
  3943. Decimal['default'] = Decimal.Decimal = Decimal;
  3944. // Create the internal constants from their string values.
  3945. LN10 = new Decimal(LN10);
  3946. PI = new Decimal(PI);
  3947. // Export.
  3948. // AMD.
  3949. if (typeof define == 'function' && define.amd) {
  3950. define(function () {
  3951. return Decimal;
  3952. });
  3953. // Node and other environments that support module.exports.
  3954. } else if (typeof module != 'undefined' && module.exports) {
  3955. if (typeof Symbol == 'function' && typeof Symbol.iterator == 'symbol') {
  3956. P[Symbol.for('nodejs.util.inspect.custom')] = P.toString;
  3957. P[Symbol.toStringTag] = 'Decimal';
  3958. }
  3959. module.exports = Decimal;
  3960. // Browser.
  3961. } else {
  3962. if (!globalScope) {
  3963. globalScope = typeof self != 'undefined' && self && self.self == self ? self : window;
  3964. }
  3965. noConflict = globalScope.Decimal;
  3966. Decimal.noConflict = function () {
  3967. globalScope.Decimal = noConflict;
  3968. return Decimal;
  3969. };
  3970. globalScope.Decimal = Decimal;
  3971. }
  3972. })(this);