decimal.mjs 120 KB

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