decimal.js 114 KB

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