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.js 128KB

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