Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

decimal.mjs 119KB

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