decimal.js 129 KB

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