UNPKG

@raydium-io/raydium-sdk-v2

Version:

An SDK for building applications on top of Raydium.

1 lines 503 kB
{"version":3,"sources":["../../../../src/raydium/clmm/utils/constants.ts","../../../../src/raydium/clmm/utils/tick.ts","../../../../node_modules/decimal.js/decimal.mjs","../../../../src/raydium/clmm/utils/math.ts","../../../../src/common/transfer.ts","../../../../src/common/accountInfo.ts","../../../../src/common/logger.ts","../../../../src/common/bignumber.ts","../../../../src/module/amount.ts","../../../../src/module/formatter.ts","../../../../src/module/fraction.ts","../../../../src/common/constant.ts","../../../../src/raydium/token/constant.ts","../../../../src/module/token.ts","../../../../src/common/pubKey.ts","../../../../src/module/currency.ts","../../../../src/module/percent.ts","../../../../src/module/price.ts","../../../../src/common/lodash.ts","../../../../src/common/pda.ts","../../../../src/common/txTool/txUtils.ts","../../../../src/common/programId.ts","../../../../src/common/txTool/lookupTable.ts","../../../../src/common/txTool/txTool.ts","../../../../src/common/utility.ts","../../../../src/common/fee.ts","../../../../src/raydium/clmm/utils/util.ts","../../../../src/raydium/clmm/utils/pda.ts","../../../../src/raydium/clmm/utils/pool.ts","../../../../src/marshmallow/index.ts","../../../../src/marshmallow/buffer-layout.ts","../../../../src/raydium/clmm/layout.ts","../../../../src/raydium/clmm/utils/position.ts","../../../../src/raydium/clmm/utils/tickQuery.ts","../../../../src/raydium/clmm/utils/tickarrayBitmap.ts"],"sourcesContent":["import BN from \"bn.js\";\n\nexport const ZERO = new BN(0);\nexport const ONE = new BN(1);\nexport const NEGATIVE_ONE = new BN(-1);\n\nexport const Q64 = new BN(1).shln(64);\nexport const Q128 = new BN(1).shln(128);\n\nexport const MaxU64 = Q64.sub(ONE);\n\nexport const U64Resolution = 64;\n\nexport const MaxUint128 = Q128.subn(1);\n\nexport const MIN_TICK = -443636;\nexport const MAX_TICK = -MIN_TICK;\n\nexport const MIN_SQRT_PRICE_X64: BN = new BN(\"4295048016\");\nexport const MAX_SQRT_PRICE_X64: BN = new BN(\"79226673521066979257578248091\");\n\nexport const MIN_SQRT_PRICE_X64_ADD_ONE: BN = new BN(\"4295048017\");\nexport const MAX_SQRT_PRICE_X64_SUB_ONE: BN = new BN(\"79226673521066979257578248090\");\n\n// export const MIN_TICK_ARRAY_START_INDEX = -307200;\n// export const MAX_TICK_ARRAY_START_INDEX = 306600;\n\nexport const BIT_PRECISION = 16;\nexport const LOG_B_2_X32 = \"59543866431248\";\nexport const LOG_B_P_ERR_MARGIN_LOWER_X64 = \"184467440737095516\";\nexport const LOG_B_P_ERR_MARGIN_UPPER_X64 = \"15793534762490258745\";\n\nexport const FEE_RATE_DENOMINATOR = new BN(10).pow(new BN(6));\n\nexport enum Fee {\n rate_500 = 500, // 500 / 10e6 = 0.0005\n rate_3000 = 3000, // 3000/ 10e6 = 0.003\n rate_10000 = 10000, // 10000 /10e6 = 0.01\n}\nexport const TICK_SPACINGS: { [amount in Fee]: number } = {\n [Fee.rate_500]: 10,\n [Fee.rate_3000]: 60,\n [Fee.rate_10000]: 200,\n};\n\nexport const mockCreatePoolInfo = {\n version: 6,\n liquidity: ZERO,\n tickCurrent: 0,\n feeGrowthGlobalX64A: ZERO,\n feeGrowthGlobalX64B: ZERO,\n protocolFeesTokenA: ZERO,\n protocolFeesTokenB: ZERO,\n swapInAmountTokenA: ZERO,\n swapOutAmountTokenB: ZERO,\n swapInAmountTokenB: ZERO,\n swapOutAmountTokenA: ZERO,\n tickArrayBitmap: [],\n\n rewardInfos: [],\n\n day: {\n volume: 0,\n volumeFee: 0,\n feeA: 0,\n feeB: 0,\n feeApr: 0,\n rewardApr: { A: 0, B: 0, C: 0 },\n apr: 0,\n priceMax: 0,\n priceMin: 0,\n },\n week: {\n volume: 0,\n volumeFee: 0,\n feeA: 0,\n feeB: 0,\n feeApr: 0,\n rewardApr: { A: 0, B: 0, C: 0 },\n apr: 0,\n priceMax: 0,\n priceMin: 0,\n },\n month: {\n volume: 0,\n volumeFee: 0,\n feeA: 0,\n feeB: 0,\n feeApr: 0,\n rewardApr: { A: 0, B: 0, C: 0 },\n apr: 0,\n priceMax: 0,\n priceMin: 0,\n },\n tvl: 0,\n};\n\nexport const mockV3CreatePoolInfo = {\n tvl: 0,\n volumeQuote: 0,\n mintAmountA: 0,\n mintAmountB: 0,\n rewardDefaultInfos: [],\n farmUpcomingCount: 0,\n farmOngoingCount: 0,\n farmFinishedCount: 0,\n\n day: {\n volume: 0,\n volumeQuote: 0,\n volumeFee: 0,\n apr: 0,\n feeApr: 0,\n priceMin: 0,\n priceMax: 0,\n rewardApr: [0],\n },\n week: {\n volume: 0,\n volumeQuote: 0,\n volumeFee: 0,\n apr: 0,\n feeApr: 0,\n priceMin: 0,\n priceMax: 0,\n rewardApr: [0],\n },\n month: {\n volume: 0,\n volumeQuote: 0,\n volumeFee: 0,\n apr: 0,\n feeApr: 0,\n priceMin: 0,\n priceMax: 0,\n rewardApr: [0],\n },\n pooltype: [],\n};\n\nexport const U64_IGNORE_RANGE = new BN(\"18446744073700000000\");\n","import { PublicKey } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\nimport Decimal from \"decimal.js\";\n\nimport { ApiV3PoolInfoConcentratedItem } from \"../../../api/type\";\nimport { ClmmPoolInfo } from \"../type\";\nimport { MAX_TICK, MIN_TICK } from \"./constants\";\nimport { SqrtPriceMath, TickMath } from \"./math\";\nimport { getPdaTickArrayAddress } from \"./pda\";\nimport { TickQuery } from \"./tickQuery\";\nimport { TickArrayBitmapExtensionLayout } from \"../layout\";\n\nexport const TICK_ARRAY_SIZE = 60;\nexport const TICK_ARRAY_BITMAP_SIZE = 512;\n\nexport interface ReturnTypeGetTickPrice {\n tick: number;\n price: Decimal;\n tickSqrtPriceX64: BN;\n}\n\nexport interface ReturnTypeGetPriceAndTick {\n tick: number;\n price: Decimal;\n}\n\nexport type Tick = {\n tick: number;\n liquidityNet: BN;\n liquidityGross: BN;\n feeGrowthOutsideX64A: BN;\n feeGrowthOutsideX64B: BN;\n rewardGrowthsOutsideX64: BN[];\n};\n\nexport type TickArray = {\n address: PublicKey;\n poolId: PublicKey;\n startTickIndex: number;\n ticks: Tick[];\n initializedTickCount: number;\n};\n\nexport type TickState = {\n tick: number;\n liquidityNet: BN;\n liquidityGross: BN;\n feeGrowthOutsideX64A: BN;\n feeGrowthOutsideX64B: BN;\n tickCumulativeOutside: BN;\n secondsPerLiquidityOutsideX64: BN;\n secondsOutside: number;\n rewardGrowthsOutside: BN[];\n};\n\nexport type TickArrayState = {\n ammPool: PublicKey;\n startTickIndex: number;\n ticks: TickState[];\n initializedTickCount: number;\n};\n\nexport class TickUtils {\n public static getTickArrayAddressByTick(\n programId: PublicKey,\n poolId: PublicKey,\n tickIndex: number,\n tickSpacing: number,\n ): PublicKey {\n const startIndex = TickUtils.getTickArrayStartIndexByTick(tickIndex, tickSpacing);\n const { publicKey: tickArrayAddress } = getPdaTickArrayAddress(programId, poolId, startIndex);\n return tickArrayAddress;\n }\n\n public static getTickOffsetInArray(tickIndex: number, tickSpacing: number): number {\n if (tickIndex % tickSpacing != 0) {\n throw new Error(\"tickIndex % tickSpacing not equal 0\");\n }\n const startTickIndex = TickUtils.getTickArrayStartIndexByTick(tickIndex, tickSpacing);\n const offsetInArray = Math.floor((tickIndex - startTickIndex) / tickSpacing);\n if (offsetInArray < 0 || offsetInArray >= TICK_ARRAY_SIZE) {\n throw new Error(\"tick offset in array overflow\");\n }\n return offsetInArray;\n }\n\n public static getTickArrayBitIndex(tickIndex: number, tickSpacing: number): number {\n const ticksInArray = TickQuery.tickCount(tickSpacing);\n\n let startIndex: number = tickIndex / ticksInArray;\n if (tickIndex < 0 && tickIndex % ticksInArray != 0) {\n startIndex = Math.ceil(startIndex) - 1;\n } else {\n startIndex = Math.floor(startIndex);\n }\n return startIndex;\n }\n\n public static getTickArrayStartIndexByTick(tickIndex: number, tickSpacing: number): number {\n return this.getTickArrayBitIndex(tickIndex, tickSpacing) * TickQuery.tickCount(tickSpacing);\n }\n\n public static getTickArrayOffsetInBitmapByTick(tick: number, tickSpacing: number): number {\n const multiplier = tickSpacing * TICK_ARRAY_SIZE;\n const compressed = Math.floor(tick / multiplier) + 512;\n return Math.abs(compressed);\n }\n\n public static checkTickArrayIsInitialized(\n bitmap: BN,\n tick: number,\n tickSpacing: number,\n ): {\n isInitialized: boolean;\n startIndex: number;\n } {\n const multiplier = tickSpacing * TICK_ARRAY_SIZE;\n const compressed = Math.floor(tick / multiplier) + 512;\n const bitPos = Math.abs(compressed);\n return {\n isInitialized: bitmap.testn(bitPos),\n startIndex: (bitPos - 512) * multiplier,\n };\n }\n\n public static getNextTickArrayStartIndex(\n lastTickArrayStartIndex: number,\n tickSpacing: number,\n zeroForOne: boolean,\n ): number {\n return zeroForOne\n ? lastTickArrayStartIndex - tickSpacing * TICK_ARRAY_SIZE\n : lastTickArrayStartIndex + tickSpacing * TICK_ARRAY_SIZE;\n }\n\n public static mergeTickArrayBitmap(bns: BN[]): BN {\n let b = new BN(0);\n for (let i = 0; i < bns.length; i++) {\n b = b.add(bns[i].shln(64 * i));\n }\n return b;\n }\n\n public static getInitializedTickArrayInRange(\n tickArrayBitmap: BN[],\n exTickArrayBitmap: ReturnType<typeof TickArrayBitmapExtensionLayout.decode>,\n tickSpacing: number,\n tickArrayStartIndex: number,\n expectedCount: number,\n ): number[] {\n const tickArrayOffset = Math.floor(tickArrayStartIndex / (tickSpacing * TICK_ARRAY_SIZE));\n return [\n // find right of currenct offset\n ...TickUtils.searchLowBitFromStart(\n tickArrayBitmap,\n exTickArrayBitmap,\n tickArrayOffset - 1,\n expectedCount,\n tickSpacing,\n ),\n\n // find left of current offset\n ...TickUtils.searchHightBitFromStart(\n tickArrayBitmap,\n exTickArrayBitmap,\n tickArrayOffset,\n expectedCount,\n tickSpacing,\n ),\n ];\n }\n\n public static getAllInitializedTickArrayStartIndex(\n tickArrayBitmap: BN[],\n exTickArrayBitmap: ReturnType<typeof TickArrayBitmapExtensionLayout.decode>,\n tickSpacing: number,\n ): number[] {\n // find from offset 0 to 1024\n return TickUtils.searchHightBitFromStart(\n tickArrayBitmap,\n exTickArrayBitmap,\n -7680,\n TICK_ARRAY_BITMAP_SIZE,\n tickSpacing,\n );\n }\n\n public static getAllInitializedTickArrayInfo(\n programId: PublicKey,\n poolId: PublicKey,\n tickArrayBitmap: BN[],\n exTickArrayBitmap: ReturnType<typeof TickArrayBitmapExtensionLayout.decode>,\n tickSpacing: number,\n ): {\n tickArrayStartIndex: number;\n tickArrayAddress: PublicKey;\n }[] {\n const result: {\n tickArrayStartIndex: number;\n tickArrayAddress: PublicKey;\n }[] = [];\n const allInitializedTickArrayIndex: number[] = TickUtils.getAllInitializedTickArrayStartIndex(\n tickArrayBitmap,\n exTickArrayBitmap,\n tickSpacing,\n );\n for (const startIndex of allInitializedTickArrayIndex) {\n const { publicKey: address } = getPdaTickArrayAddress(programId, poolId, startIndex);\n result.push({\n tickArrayStartIndex: startIndex,\n tickArrayAddress: address,\n });\n }\n return result;\n }\n\n public static getAllInitializedTickInTickArray(tickArray: TickArrayState): TickState[] {\n return tickArray.ticks.filter((i) => i.liquidityGross.gtn(0));\n }\n\n public static searchLowBitFromStart(\n tickArrayBitmap: BN[],\n exTickArrayBitmap: ReturnType<typeof TickArrayBitmapExtensionLayout.decode>,\n currentTickArrayBitStartIndex: number,\n expectedCount: number,\n tickSpacing: number,\n ): number[] {\n const tickArrayBitmaps = [\n ...[...exTickArrayBitmap.negativeTickArrayBitmap].reverse(),\n tickArrayBitmap.slice(0, 8),\n tickArrayBitmap.slice(8, 16),\n ...exTickArrayBitmap.positiveTickArrayBitmap,\n ].map((i) => TickUtils.mergeTickArrayBitmap(i));\n const result: number[] = [];\n while (currentTickArrayBitStartIndex >= -7680) {\n const arrayIndex = Math.floor((currentTickArrayBitStartIndex + 7680) / 512);\n const searchIndex = (currentTickArrayBitStartIndex + 7680) % 512;\n\n if (tickArrayBitmaps[arrayIndex].testn(searchIndex)) result.push(currentTickArrayBitStartIndex);\n\n currentTickArrayBitStartIndex--;\n if (result.length === expectedCount) break;\n }\n\n const tickCount = TickQuery.tickCount(tickSpacing);\n return result.map((i) => i * tickCount);\n }\n\n public static searchHightBitFromStart(\n tickArrayBitmap: BN[],\n exTickArrayBitmap: ReturnType<typeof TickArrayBitmapExtensionLayout.decode>,\n currentTickArrayBitStartIndex: number,\n expectedCount: number,\n tickSpacing: number,\n ): number[] {\n const tickArrayBitmaps = [\n ...[...exTickArrayBitmap.negativeTickArrayBitmap].reverse(),\n tickArrayBitmap.slice(0, 8),\n tickArrayBitmap.slice(8, 16),\n ...exTickArrayBitmap.positiveTickArrayBitmap,\n ].map((i) => TickUtils.mergeTickArrayBitmap(i));\n const result: number[] = [];\n while (currentTickArrayBitStartIndex < 7680) {\n const arrayIndex = Math.floor((currentTickArrayBitStartIndex + 7680) / 512);\n const searchIndex = (currentTickArrayBitStartIndex + 7680) % 512;\n\n if (tickArrayBitmaps[arrayIndex].testn(searchIndex)) result.push(currentTickArrayBitStartIndex);\n\n currentTickArrayBitStartIndex++;\n if (result.length === expectedCount) break;\n }\n\n const tickCount = TickQuery.tickCount(tickSpacing);\n return result.map((i) => i * tickCount);\n }\n\n public static checkIsOutOfBoundary(tick: number): boolean {\n return tick < MIN_TICK || tick > MAX_TICK;\n }\n\n public static nextInitTick(\n tickArrayCurrent: TickArray,\n currentTickIndex: number,\n tickSpacing: number,\n zeroForOne: boolean,\n t: boolean,\n ): Tick | null {\n const currentTickArrayStartIndex = TickQuery.getArrayStartIndex(currentTickIndex, tickSpacing);\n if (currentTickArrayStartIndex != tickArrayCurrent.startTickIndex) {\n return null;\n }\n let offsetInArray = Math.floor((currentTickIndex - tickArrayCurrent.startTickIndex) / tickSpacing);\n\n if (zeroForOne) {\n while (offsetInArray >= 0) {\n if (tickArrayCurrent.ticks[offsetInArray].liquidityGross.gtn(0)) {\n return tickArrayCurrent.ticks[offsetInArray];\n }\n offsetInArray = offsetInArray - 1;\n }\n } else {\n if (!t) offsetInArray = offsetInArray + 1;\n while (offsetInArray < TICK_ARRAY_SIZE) {\n if (tickArrayCurrent.ticks[offsetInArray].liquidityGross.gtn(0)) {\n return tickArrayCurrent.ticks[offsetInArray];\n }\n offsetInArray = offsetInArray + 1;\n }\n }\n return null;\n }\n\n public static firstInitializedTick(tickArrayCurrent: TickArray, zeroForOne: boolean): Tick {\n if (zeroForOne) {\n let i = TICK_ARRAY_SIZE - 1;\n while (i >= 0) {\n if (tickArrayCurrent.ticks[i].liquidityGross.gtn(0)) {\n return tickArrayCurrent.ticks[i];\n }\n i = i - 1;\n }\n } else {\n let i = 0;\n while (i < TICK_ARRAY_SIZE) {\n if (tickArrayCurrent.ticks[i].liquidityGross.gtn(0)) {\n return tickArrayCurrent.ticks[i];\n }\n i = i + 1;\n }\n }\n\n throw Error(`firstInitializedTick check error: ${tickArrayCurrent} - ${zeroForOne}`);\n }\n\n public static _getTickPriceLegacy({\n poolInfo,\n tick,\n baseIn,\n }: {\n poolInfo: ClmmPoolInfo;\n tick: number;\n baseIn: boolean;\n }): ReturnTypeGetTickPrice {\n const tickSqrtPriceX64 = SqrtPriceMath.getSqrtPriceX64FromTick(tick);\n const tickPrice = SqrtPriceMath.sqrtPriceX64ToPrice(\n tickSqrtPriceX64,\n poolInfo.mintA.decimals,\n poolInfo.mintB.decimals,\n );\n\n return baseIn\n ? { tick, price: tickPrice, tickSqrtPriceX64 }\n : { tick, price: new Decimal(1).div(tickPrice), tickSqrtPriceX64 };\n }\n\n public static _getPriceAndTickLegacy({\n poolInfo,\n price,\n baseIn,\n }: {\n poolInfo: ClmmPoolInfo;\n price: Decimal;\n baseIn: boolean;\n }): ReturnTypeGetPriceAndTick {\n const _price = baseIn ? price : new Decimal(1).div(price);\n\n const tick = TickMath.getTickWithPriceAndTickspacing(\n _price,\n poolInfo.ammConfig.tickSpacing,\n poolInfo.mintA.decimals,\n poolInfo.mintB.decimals,\n );\n const tickSqrtPriceX64 = SqrtPriceMath.getSqrtPriceX64FromTick(tick);\n const tickPrice = SqrtPriceMath.sqrtPriceX64ToPrice(\n tickSqrtPriceX64,\n poolInfo.mintA.decimals,\n poolInfo.mintB.decimals,\n );\n\n return baseIn ? { tick, price: tickPrice } : { tick, price: new Decimal(1).div(tickPrice) };\n }\n\n public static getTickPrice({\n poolInfo,\n tick,\n baseIn,\n }: {\n poolInfo: ApiV3PoolInfoConcentratedItem;\n tick: number;\n baseIn: boolean;\n }): ReturnTypeGetTickPrice {\n const tickSqrtPriceX64 = SqrtPriceMath.getSqrtPriceX64FromTick(tick);\n const tickPrice = SqrtPriceMath.sqrtPriceX64ToPrice(\n tickSqrtPriceX64,\n poolInfo.mintA.decimals,\n poolInfo.mintB.decimals,\n );\n\n return baseIn\n ? { tick, price: tickPrice, tickSqrtPriceX64 }\n : { tick, price: new Decimal(1).div(tickPrice), tickSqrtPriceX64 };\n }\n\n public static getPriceAndTick({\n poolInfo,\n price,\n baseIn,\n }: {\n poolInfo: ApiV3PoolInfoConcentratedItem;\n price: Decimal;\n baseIn: boolean;\n }): ReturnTypeGetPriceAndTick {\n const _price = baseIn ? price : new Decimal(1).div(price);\n\n const tick = TickMath.getTickWithPriceAndTickspacing(\n _price,\n poolInfo.config.tickSpacing,\n poolInfo.mintA.decimals,\n poolInfo.mintB.decimals,\n );\n const tickSqrtPriceX64 = SqrtPriceMath.getSqrtPriceX64FromTick(tick);\n const tickPrice = SqrtPriceMath.sqrtPriceX64ToPrice(\n tickSqrtPriceX64,\n poolInfo.mintA.decimals,\n poolInfo.mintB.decimals,\n );\n\n return baseIn ? { tick, price: tickPrice } : { tick, price: new Decimal(1).div(tickPrice) };\n }\n}\n","/*\r\n * decimal.js v10.3.1\r\n * An arbitrary-precision Decimal type for JavaScript.\r\n * https://github.com/MikeMcl/decimal.js\r\n * Copyright (c) 2021 Michael Mclaughlin <M8ch88l@gmail.com>\r\n * MIT Licence\r\n */\r\n\r\n\r\n// ----------------------------------- EDITABLE DEFAULTS ------------------------------------ //\r\n\r\n\r\n // The maximum exponent magnitude.\r\n // The limit on the value of `toExpNeg`, `toExpPos`, `minE` and `maxE`.\r\nvar EXP_LIMIT = 9e15, // 0 to 9e15\r\n\r\n // The limit on the value of `precision`, and on the value of the first argument to\r\n // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`.\r\n MAX_DIGITS = 1e9, // 0 to 1e9\r\n\r\n // Base conversion alphabet.\r\n NUMERALS = '0123456789abcdef',\r\n\r\n // The natural logarithm of 10 (1025 digits).\r\n LN10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058',\r\n\r\n // Pi (1025 digits).\r\n PI = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789',\r\n\r\n\r\n // The initial configuration properties of the Decimal constructor.\r\n DEFAULTS = {\r\n\r\n // These values must be integers within the stated ranges (inclusive).\r\n // Most of these values can be changed at run-time using the `Decimal.config` method.\r\n\r\n // The maximum number of significant digits of the result of a calculation or base conversion.\r\n // E.g. `Decimal.config({ precision: 20 });`\r\n precision: 20, // 1 to MAX_DIGITS\r\n\r\n // The rounding mode used when rounding to `precision`.\r\n //\r\n // ROUND_UP 0 Away from zero.\r\n // ROUND_DOWN 1 Towards zero.\r\n // ROUND_CEIL 2 Towards +Infinity.\r\n // ROUND_FLOOR 3 Towards -Infinity.\r\n // ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up.\r\n // ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.\r\n // ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.\r\n // ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.\r\n // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.\r\n //\r\n // E.g.\r\n // `Decimal.rounding = 4;`\r\n // `Decimal.rounding = Decimal.ROUND_HALF_UP;`\r\n rounding: 4, // 0 to 8\r\n\r\n // The modulo mode used when calculating the modulus: a mod n.\r\n // The quotient (q = a / n) is calculated according to the corresponding rounding mode.\r\n // The remainder (r) is calculated as: r = a - n * q.\r\n //\r\n // UP 0 The remainder is positive if the dividend is negative, else is negative.\r\n // DOWN 1 The remainder has the same sign as the dividend (JavaScript %).\r\n // FLOOR 3 The remainder has the same sign as the divisor (Python %).\r\n // HALF_EVEN 6 The IEEE 754 remainder function.\r\n // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). Always positive.\r\n //\r\n // Truncated division (1), floored division (3), the IEEE 754 remainder (6), and Euclidian\r\n // division (9) are commonly used for the modulus operation. The other rounding modes can also\r\n // be used, but they may not give useful results.\r\n modulo: 1, // 0 to 9\r\n\r\n // The exponent value at and beneath which `toString` returns exponential notation.\r\n // JavaScript numbers: -7\r\n toExpNeg: -7, // 0 to -EXP_LIMIT\r\n\r\n // The exponent value at and above which `toString` returns exponential notation.\r\n // JavaScript numbers: 21\r\n toExpPos: 21, // 0 to EXP_LIMIT\r\n\r\n // The minimum exponent value, beneath which underflow to zero occurs.\r\n // JavaScript numbers: -324 (5e-324)\r\n minE: -EXP_LIMIT, // -1 to -EXP_LIMIT\r\n\r\n // The maximum exponent value, above which overflow to Infinity occurs.\r\n // JavaScript numbers: 308 (1.7976931348623157e+308)\r\n maxE: EXP_LIMIT, // 1 to EXP_LIMIT\r\n\r\n // Whether to use cryptographically-secure random number generation, if available.\r\n crypto: false // true/false\r\n },\r\n\r\n\r\n// ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- //\r\n\r\n\r\n inexact, quadrant,\r\n external = true,\r\n\r\n decimalError = '[DecimalError] ',\r\n invalidArgument = decimalError + 'Invalid argument: ',\r\n precisionLimitExceeded = decimalError + 'Precision limit exceeded',\r\n cryptoUnavailable = decimalError + 'crypto unavailable',\r\n tag = '[object Decimal]',\r\n\r\n mathfloor = Math.floor,\r\n mathpow = Math.pow,\r\n\r\n isBinary = /^0b([01]+(\\.[01]*)?|\\.[01]+)(p[+-]?\\d+)?$/i,\r\n isHex = /^0x([0-9a-f]+(\\.[0-9a-f]*)?|\\.[0-9a-f]+)(p[+-]?\\d+)?$/i,\r\n isOctal = /^0o([0-7]+(\\.[0-7]*)?|\\.[0-7]+)(p[+-]?\\d+)?$/i,\r\n isDecimal = /^(\\d+(\\.\\d*)?|\\.\\d+)(e[+-]?\\d+)?$/i,\r\n\r\n BASE = 1e7,\r\n LOG_BASE = 7,\r\n MAX_SAFE_INTEGER = 9007199254740991,\r\n\r\n LN10_PRECISION = LN10.length - 1,\r\n PI_PRECISION = PI.length - 1,\r\n\r\n // Decimal.prototype object\r\n P = { toStringTag: tag };\r\n\r\n\r\n// Decimal prototype methods\r\n\r\n\r\n/*\r\n * absoluteValue abs\r\n * ceil\r\n * clampedTo clamp\r\n * comparedTo cmp\r\n * cosine cos\r\n * cubeRoot cbrt\r\n * decimalPlaces dp\r\n * dividedBy div\r\n * dividedToIntegerBy divToInt\r\n * equals eq\r\n * floor\r\n * greaterThan gt\r\n * greaterThanOrEqualTo gte\r\n * hyperbolicCosine cosh\r\n * hyperbolicSine sinh\r\n * hyperbolicTangent tanh\r\n * inverseCosine acos\r\n * inverseHyperbolicCosine acosh\r\n * inverseHyperbolicSine asinh\r\n * inverseHyperbolicTangent atanh\r\n * inverseSine asin\r\n * inverseTangent atan\r\n * isFinite\r\n * isInteger isInt\r\n * isNaN\r\n * isNegative isNeg\r\n * isPositive isPos\r\n * isZero\r\n * lessThan lt\r\n * lessThanOrEqualTo lte\r\n * logarithm log\r\n * [maximum] [max]\r\n * [minimum] [min]\r\n * minus sub\r\n * modulo mod\r\n * naturalExponential exp\r\n * naturalLogarithm ln\r\n * negated neg\r\n * plus add\r\n * precision sd\r\n * round\r\n * sine sin\r\n * squareRoot sqrt\r\n * tangent tan\r\n * times mul\r\n * toBinary\r\n * toDecimalPlaces toDP\r\n * toExponential\r\n * toFixed\r\n * toFraction\r\n * toHexadecimal toHex\r\n * toNearest\r\n * toNumber\r\n * toOctal\r\n * toPower pow\r\n * toPrecision\r\n * toSignificantDigits toSD\r\n * toString\r\n * truncated trunc\r\n * valueOf toJSON\r\n */\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the absolute value of this Decimal.\r\n *\r\n */\r\nP.absoluteValue = P.abs = function () {\r\n var x = new this.constructor(this);\r\n if (x.s < 0) x.s = 1;\r\n return finalise(x);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the\r\n * direction of positive Infinity.\r\n *\r\n */\r\nP.ceil = function () {\r\n return finalise(new this.constructor(this), this.e + 1, 2);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal clamped to the range\r\n * delineated by `min` and `max`.\r\n *\r\n * min {number|string|Decimal}\r\n * max {number|string|Decimal}\r\n *\r\n */\r\nP.clampedTo = P.clamp = function (min, max) {\r\n var k,\r\n x = this,\r\n Ctor = x.constructor;\r\n min = new Ctor(min);\r\n max = new Ctor(max);\r\n if (!min.s || !max.s) return new Ctor(NaN);\r\n if (min.gt(max)) throw Error(invalidArgument + max);\r\n k = x.cmp(min);\r\n return k < 0 ? min : x.cmp(max) > 0 ? max : new Ctor(x);\r\n};\r\n\r\n\r\n/*\r\n * Return\r\n * 1 if the value of this Decimal is greater than the value of `y`,\r\n * -1 if the value of this Decimal is less than the value of `y`,\r\n * 0 if they have the same value,\r\n * NaN if the value of either Decimal is NaN.\r\n *\r\n */\r\nP.comparedTo = P.cmp = function (y) {\r\n var i, j, xdL, ydL,\r\n x = this,\r\n xd = x.d,\r\n yd = (y = new x.constructor(y)).d,\r\n xs = x.s,\r\n ys = y.s;\r\n\r\n // Either NaN or ±Infinity?\r\n if (!xd || !yd) {\r\n return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1;\r\n }\r\n\r\n // Either zero?\r\n if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0;\r\n\r\n // Signs differ?\r\n if (xs !== ys) return xs;\r\n\r\n // Compare exponents.\r\n if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1;\r\n\r\n xdL = xd.length;\r\n ydL = yd.length;\r\n\r\n // Compare digit by digit.\r\n for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) {\r\n if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1;\r\n }\r\n\r\n // Compare lengths.\r\n return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1;\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the cosine of the value in radians of this Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-1, 1]\r\n *\r\n * cos(0) = 1\r\n * cos(-0) = 1\r\n * cos(Infinity) = NaN\r\n * cos(-Infinity) = NaN\r\n * cos(NaN) = NaN\r\n *\r\n */\r\nP.cosine = P.cos = function () {\r\n var pr, rm,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.d) return new Ctor(NaN);\r\n\r\n // cos(0) = cos(-0) = 1\r\n if (!x.d[0]) return new Ctor(1);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;\r\n Ctor.rounding = 1;\r\n\r\n x = cosine(Ctor, toLessThanHalfPi(Ctor, x));\r\n\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return finalise(quadrant == 2 || quadrant == 3 ? x.neg() : x, pr, rm, true);\r\n};\r\n\r\n\r\n/*\r\n *\r\n * Return a new Decimal whose value is the cube root of the value of this Decimal, rounded to\r\n * `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * cbrt(0) = 0\r\n * cbrt(-0) = -0\r\n * cbrt(1) = 1\r\n * cbrt(-1) = -1\r\n * cbrt(N) = N\r\n * cbrt(-I) = -I\r\n * cbrt(I) = I\r\n *\r\n * Math.cbrt(x) = (x < 0 ? -Math.pow(-x, 1/3) : Math.pow(x, 1/3))\r\n *\r\n */\r\nP.cubeRoot = P.cbrt = function () {\r\n var e, m, n, r, rep, s, sd, t, t3, t3plusx,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.isFinite() || x.isZero()) return new Ctor(x);\r\n external = false;\r\n\r\n // Initial estimate.\r\n s = x.s * mathpow(x.s * x, 1 / 3);\r\n\r\n // Math.cbrt underflow/overflow?\r\n // Pass x to Math.pow as integer, then adjust the exponent of the result.\r\n if (!s || Math.abs(s) == 1 / 0) {\r\n n = digitsToString(x.d);\r\n e = x.e;\r\n\r\n // Adjust n exponent so it is a multiple of 3 away from x exponent.\r\n if (s = (e - n.length + 1) % 3) n += (s == 1 || s == -2 ? '0' : '00');\r\n s = mathpow(n, 1 / 3);\r\n\r\n // Rarely, e may be one less than the result exponent value.\r\n e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2));\r\n\r\n if (s == 1 / 0) {\r\n n = '5e' + e;\r\n } else {\r\n n = s.toExponential();\r\n n = n.slice(0, n.indexOf('e') + 1) + e;\r\n }\r\n\r\n r = new Ctor(n);\r\n r.s = x.s;\r\n } else {\r\n r = new Ctor(s.toString());\r\n }\r\n\r\n sd = (e = Ctor.precision) + 3;\r\n\r\n // Halley's method.\r\n // TODO? Compare Newton's method.\r\n for (;;) {\r\n t = r;\r\n t3 = t.times(t).times(t);\r\n t3plusx = t3.plus(x);\r\n r = divide(t3plusx.plus(x).times(t), t3plusx.plus(t3), sd + 2, 1);\r\n\r\n // TODO? Replace with for-loop and checkRoundingDigits.\r\n if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {\r\n n = n.slice(sd - 3, sd + 1);\r\n\r\n // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or 4999\r\n // , i.e. approaching a rounding boundary, continue the iteration.\r\n if (n == '9999' || !rep && n == '4999') {\r\n\r\n // On the first iteration only, check to see if rounding up gives the exact result as the\r\n // nines may infinitely repeat.\r\n if (!rep) {\r\n finalise(t, e + 1, 0);\r\n\r\n if (t.times(t).times(t).eq(x)) {\r\n r = t;\r\n break;\r\n }\r\n }\r\n\r\n sd += 4;\r\n rep = 1;\r\n } else {\r\n\r\n // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.\r\n // If not, then there are further digits and m will be truthy.\r\n if (!+n || !+n.slice(1) && n.charAt(0) == '5') {\r\n\r\n // Truncate to the first rounding digit.\r\n finalise(r, e + 1, 1);\r\n m = !r.times(r).times(r).eq(x);\r\n }\r\n\r\n break;\r\n }\r\n }\r\n }\r\n\r\n external = true;\r\n\r\n return finalise(r, e, Ctor.rounding, m);\r\n};\r\n\r\n\r\n/*\r\n * Return the number of decimal places of the value of this Decimal.\r\n *\r\n */\r\nP.decimalPlaces = P.dp = function () {\r\n var w,\r\n d = this.d,\r\n n = NaN;\r\n\r\n if (d) {\r\n w = d.length - 1;\r\n n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE;\r\n\r\n // Subtract the number of trailing zeros of the last word.\r\n w = d[w];\r\n if (w) for (; w % 10 == 0; w /= 10) n--;\r\n if (n < 0) n = 0;\r\n }\r\n\r\n return n;\r\n};\r\n\r\n\r\n/*\r\n * n / 0 = I\r\n * n / N = N\r\n * n / I = 0\r\n * 0 / n = 0\r\n * 0 / 0 = N\r\n * 0 / N = N\r\n * 0 / I = 0\r\n * N / n = N\r\n * N / 0 = N\r\n * N / N = N\r\n * N / I = N\r\n * I / n = I\r\n * I / 0 = I\r\n * I / N = N\r\n * I / I = N\r\n *\r\n * Return a new Decimal whose value is the value of this Decimal divided by `y`, rounded to\r\n * `precision` significant digits using rounding mode `rounding`.\r\n *\r\n */\r\nP.dividedBy = P.div = function (y) {\r\n return divide(this, new this.constructor(y));\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the integer part of dividing the value of this Decimal\r\n * by the value of `y`, rounded to `precision` significant digits using rounding mode `rounding`.\r\n *\r\n */\r\nP.dividedToIntegerBy = P.divToInt = function (y) {\r\n var x = this,\r\n Ctor = x.constructor;\r\n return finalise(divide(x, new Ctor(y), 0, 1, 1), Ctor.precision, Ctor.rounding);\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false.\r\n *\r\n */\r\nP.equals = P.eq = function (y) {\r\n return this.cmp(y) === 0;\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the\r\n * direction of negative Infinity.\r\n *\r\n */\r\nP.floor = function () {\r\n return finalise(new this.constructor(this), this.e + 1, 3);\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is greater than the value of `y`, otherwise return\r\n * false.\r\n *\r\n */\r\nP.greaterThan = P.gt = function (y) {\r\n return this.cmp(y) > 0;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is greater than or equal to the value of `y`,\r\n * otherwise return false.\r\n *\r\n */\r\nP.greaterThanOrEqualTo = P.gte = function (y) {\r\n var k = this.cmp(y);\r\n return k == 1 || k === 0;\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the hyperbolic cosine of the value in radians of this\r\n * Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [1, Infinity]\r\n *\r\n * cosh(x) = 1 + x^2/2! + x^4/4! + x^6/6! + ...\r\n *\r\n * cosh(0) = 1\r\n * cosh(-0) = 1\r\n * cosh(Infinity) = Infinity\r\n * cosh(-Infinity) = Infinity\r\n * cosh(NaN) = NaN\r\n *\r\n * x time taken (ms) result\r\n * 1000 9 9.8503555700852349694e+433\r\n * 10000 25 4.4034091128314607936e+4342\r\n * 100000 171 1.4033316802130615897e+43429\r\n * 1000000 3817 1.5166076984010437725e+434294\r\n * 10000000 abandoned after 2 minute wait\r\n *\r\n * TODO? Compare performance of cosh(x) = 0.5 * (exp(x) + exp(-x))\r\n *\r\n */\r\nP.hyperbolicCosine = P.cosh = function () {\r\n var k, n, pr, rm, len,\r\n x = this,\r\n Ctor = x.constructor,\r\n one = new Ctor(1);\r\n\r\n if (!x.isFinite()) return new Ctor(x.s ? 1 / 0 : NaN);\r\n if (x.isZero()) return one;\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;\r\n Ctor.rounding = 1;\r\n len = x.d.length;\r\n\r\n // Argument reduction: cos(4x) = 1 - 8cos^2(x) + 8cos^4(x) + 1\r\n // i.e. cos(x) = 1 - cos^2(x/4)(8 - 8cos^2(x/4))\r\n\r\n // Estimate the optimum number of times to use the argument reduction.\r\n // TODO? Estimation reused from cosine() and may not be optimal here.\r\n if (len < 32) {\r\n k = Math.ceil(len / 3);\r\n n = (1 / tinyPow(4, k)).toString();\r\n } else {\r\n k = 16;\r\n n = '2.3283064365386962890625e-10';\r\n }\r\n\r\n x = taylorSeries(Ctor, 1, x.times(n), new Ctor(1), true);\r\n\r\n // Reverse argument reduction\r\n var cosh2_x,\r\n i = k,\r\n d8 = new Ctor(8);\r\n for (; i--;) {\r\n cosh2_x = x.times(x);\r\n x = one.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8))));\r\n }\r\n\r\n return finalise(x, Ctor.precision = pr, Ctor.rounding = rm, true);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the hyperbolic sine of the value in radians of this\r\n * Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-Infinity, Infinity]\r\n *\r\n * sinh(x) = x + x^3/3! + x^5/5! + x^7/7! + ...\r\n *\r\n * sinh(0) = 0\r\n * sinh(-0) = -0\r\n * sinh(Infinity) = Infinity\r\n * sinh(-Infinity) = -Infinity\r\n * sinh(NaN) = NaN\r\n *\r\n * x time taken (ms)\r\n * 10 2 ms\r\n * 100 5 ms\r\n * 1000 14 ms\r\n * 10000 82 ms\r\n * 100000 886 ms 1.4033316802130615897e+43429\r\n * 200000 2613 ms\r\n * 300000 5407 ms\r\n * 400000 8824 ms\r\n * 500000 13026 ms 8.7080643612718084129e+217146\r\n * 1000000 48543 ms\r\n *\r\n * TODO? Compare performance of sinh(x) = 0.5 * (exp(x) - exp(-x))\r\n *\r\n */\r\nP.hyperbolicSine = P.sinh = function () {\r\n var k, pr, rm, len,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.isFinite() || x.isZero()) return new Ctor(x);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;\r\n Ctor.rounding = 1;\r\n len = x.d.length;\r\n\r\n if (len < 3) {\r\n x = taylorSeries(Ctor, 2, x, x, true);\r\n } else {\r\n\r\n // Alternative argument reduction: sinh(3x) = sinh(x)(3 + 4sinh^2(x))\r\n // i.e. sinh(x) = sinh(x/3)(3 + 4sinh^2(x/3))\r\n // 3 multiplications and 1 addition\r\n\r\n // Argument reduction: sinh(5x) = sinh(x)(5 + sinh^2(x)(20 + 16sinh^2(x)))\r\n // i.e. sinh(x) = sinh(x/5)(5 + sinh^2(x/5)(20 + 16sinh^2(x/5)))\r\n // 4 multiplications and 2 additions\r\n\r\n // Estimate the optimum number of times to use the argument reduction.\r\n k = 1.4 * Math.sqrt(len);\r\n k = k > 16 ? 16 : k | 0;\r\n\r\n x = x.times(1 / tinyPow(5, k));\r\n x = taylorSeries(Ctor, 2, x, x, true);\r\n\r\n // Reverse argument reduction\r\n var sinh2_x,\r\n d5 = new Ctor(5),\r\n d16 = new Ctor(16),\r\n d20 = new Ctor(20);\r\n for (; k--;) {\r\n sinh2_x = x.times(x);\r\n x = x.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20))));\r\n }\r\n }\r\n\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return finalise(x, pr, rm, true);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the hyperbolic tangent of the value in radians of this\r\n * Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-1, 1]\r\n *\r\n * tanh(x) = sinh(x) / cosh(x)\r\n *\r\n * tanh(0) = 0\r\n * tanh(-0) = -0\r\n * tanh(Infinity) = 1\r\n * tanh(-Infinity) = -1\r\n * tanh(NaN) = NaN\r\n *\r\n */\r\nP.hyperbolicTangent = P.tanh = function () {\r\n var pr, rm,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.isFinite()) return new Ctor(x.s);\r\n if (x.isZero()) return new Ctor(x);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + 7;\r\n Ctor.rounding = 1;\r\n\r\n return divide(x.sinh(), x.cosh(), Ctor.precision = pr, Ctor.rounding = rm);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the arccosine (inverse cosine) in radians of the value of\r\n * this Decimal.\r\n *\r\n * Domain: [-1, 1]\r\n * Range: [0, pi]\r\n *\r\n * acos(x) = pi/2 - asin(x)\r\n *\r\n * acos(0) = pi/2\r\n * acos(-0) = pi/2\r\n * acos(1) = 0\r\n * acos(-1) = pi\r\n * acos(1/2) = pi/3\r\n * acos(-1/2) = 2*pi/3\r\n * acos(|x| > 1) = NaN\r\n * acos(NaN) = NaN\r\n *\r\n */\r\nP.inverseCosine = P.acos = function () {\r\n var halfPi,\r\n x = this,\r\n Ctor = x.constructor,\r\n k = x.abs().cmp(1),\r\n pr = Ctor.precision,\r\n rm = Ctor.rounding;\r\n\r\n if (k !== -1) {\r\n return k === 0\r\n // |x| is 1\r\n ? x.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0)\r\n // |x| > 1 or x is NaN\r\n : new Ctor(NaN);\r\n }\r\n\r\n if (x.isZero()) return getPi(Ctor, pr + 4, rm).times(0.5);\r\n\r\n // TODO? Special case acos(0.5) = pi/3 and acos(-0.5) = 2*pi/3\r\n\r\n Ctor.precision = pr + 6;\r\n Ctor.rounding = 1;\r\n\r\n x = x.asin();\r\n halfPi = getPi(Ctor, pr + 4, rm).times(0.5);\r\n\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return halfPi.minus(x);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the inverse of the hyperbolic cosine in radians of the\r\n * value of this Decimal.\r\n *\r\n * Domain: [1, Infinity]\r\n * Range: [0, Infinity]\r\n *\r\n * acosh(x) = ln(x + sqrt(x^2 - 1))\r\n *\r\n * acosh(x < 1) = NaN\r\n * acosh(NaN) = NaN\r\n * acosh(Infinity) = Infinity\r\n * acosh(-Infinity) = NaN\r\n * acosh(0) = NaN\r\n * acosh(-0) = NaN\r\n * acosh(1) = 0\r\n * acosh(-1) = NaN\r\n *\r\n */\r\nP.inverseHyperbolicCosine = P.acosh = function () {\r\n var pr, rm,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (x.lte(1)) return new Ctor(x.eq(1) ? 0 : NaN);\r\n if (!x.isFinite()) return new Ctor(x);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + Math.max(Math.abs(x.e), x.sd()) + 4;\r\n Ctor.rounding = 1;\r\n external = false;\r\n\r\n x = x.times(x).minus(1).sqrt().plus(x);\r\n\r\n external = true;\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return x.ln();\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the inverse of the hyperbolic sine in radians of the value\r\n * of this Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-Infinity, Infinity]\r\n *\r\n * asinh(x) = ln(x + sqrt(x^2 + 1))\r\n *\r\n * asinh(NaN) = NaN\r\n * asinh(Infinity) = Infinity\r\n * asinh(-Infinity) = -Infinity\r\n * asinh(0) = 0\r\n * asinh(-0) = -0\r\n *\r\n */\r\nP.inverseHyperbolicSine = P.asinh = function () {\r\n var pr, rm,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.isFinite() || x.isZero()) return new Ctor(x);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + 2 * Math.max(Math.abs(x.e), x.sd()) + 6;\r\n Ctor.rounding = 1;\r\n external = false;\r\n\r\n x = x.times(x).plus(1).sqrt().plus(x);\r\n\r\n external = true;\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return x.ln();\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the inverse of the hyperbolic tangent in radians of the\r\n * value of this Decimal.\r\n *\r\n * Domain: [-1, 1]\r\n * Range: [-Infinity, Infinity]\r\n *\r\n * atanh(x) = 0.5 * ln((1 + x) / (1 - x))\r\n *\r\n * atanh(|x| > 1) = NaN\r\n * atanh(NaN) = NaN\r\n * atanh(Infinity) = NaN\r\n * atanh(-Infinity) = NaN\r\n * atanh(0) = 0\r\n * atanh(-0) = -0\r\n * atanh(1) = Infinity\r\n * atanh(-1) = -Infinity\r\n *\r\n */\r\nP.inverseHyperbolicTangent = P.atanh = function () {\r\n var pr, rm, wpr, xsd,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.isFinite()) return new Ctor(NaN);\r\n if (x.e >= 0) return new Ctor(x.abs().eq(1) ? x.s / 0 : x.isZero() ? x : NaN);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n xsd = x.sd();\r\n\r\n if (Math.max(xsd, pr) < 2 * -x.e - 1) return finalise(new Ctor(x), pr, rm, true);\r\n\r\n Ctor.precision = wpr = xsd - x.e;\r\n\r\n x = divide(x.plus(1), new Ctor(1).minus(x), wpr + pr, 1);\r\n\r\n Ctor.precision = pr + 4;\r\n Ctor.rounding = 1;\r\n\r\n x = x.ln();\r\n\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return x.times(0.5);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the arcsine (inverse sine) in radians of the value of this\r\n * Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-pi/2, pi/2]\r\n *\r\n * asin(x) = 2*atan(x/(1 + sqrt(1 - x^2)))\r\n *\r\n * asin(0) = 0\r\n * asin(-0) = -0\r\n * asin(1/2) = pi/6\r\n * asin(-1/2) = -pi/6\r\n * asin(1) = pi/2\r\n * asin(-1) = -pi/2\r\n * asin(|x| > 1) = NaN\r\n * asin(NaN) = NaN\r\n *\r\n * TODO? Compare performance of Taylor series.\r\n *\r\n */\r\nP.inverseSine = P.asin = function () {\r\n var halfPi, k,\r\n pr, rm,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (x.isZero()) return new Ctor(x);\r\n\r\n k = x.abs().cmp(1);\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n\r\n if (k !== -1) {\r\n\r\n // |x| is 1\r\n if (k === 0) {\r\n halfPi = getPi(Ctor, pr + 4, rm).times(0.5);\r\n halfPi.s = x.s;\r\n return halfPi;\r\n }\r\n\r\n // |x| > 1 or x is NaN\r\n return new Ctor(NaN);\r\n }\r\n\r\n // TODO? Special case asin(1/2) = pi/6 and asin(-1/2) = -pi/6\r\n\r\n Ctor.precision = pr + 6;\r\n Ctor.rounding = 1;\r\n\r\n x = x.div(new Ctor(1).minus(x.times(x)).sqrt().plus(1)).atan();\r\n\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return x.times(2);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the arctangent (inverse tangent) in radians of the value\r\n * of this Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-pi/2, pi/2]\r\n *\r\n * atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...\r\n *\r\n * atan(0) = 0\r\n * atan(-0) = -0\r\n * atan(1) = pi/4\r\n * atan(-1) = -pi/4\r\n * atan(Infinity) = pi/2\r\n * atan(-Infinity) = -pi/2\r\n * atan(NaN) = NaN\r\n *\r\n */\r\nP.inverseTangent = P.atan = function () {\r\n var i, j, k, n, px, t, r, wpr, x2,\r\n x = this,\r\n Ctor = x.constructor,\r\n pr = Ctor.precision,\r\n rm = Ctor.rounding;\r\n\r\n if (!x.isFinite()) {\r\n if (!x.s) return new Ctor(NaN);\r\n if (pr + 4 <= PI_PRECISION) {\r\n r = getPi(Ctor, pr + 4, rm).times(0.5);\r\n r.s = x.s;\r\n return r;\r\n }\r\n } else if (x.isZero()) {\r\n return new Ctor(x);\r\n } else if (x.abs().eq(1) && pr + 4 <= PI_PRECISION) {\r\n r = getPi(Ctor, pr + 4, rm).times(0.25);\r\n r.s = x.s;\r\n return r;\r\n }\r\n\r\n Ctor.precision = wpr = pr + 10;\r\n Ctor.rounding = 1;\r\n\r\n // TODO? if (x >= 1 && pr <= PI_PRECISION) atan(x) = halfPi * x.s - atan(1 / x);\r\n\r\n // Argument reduction\r\n // Ensure |x| < 0.42\r\n // atan(x) = 2 * atan(x / (1 + sqrt(1 + x^2)))\r\n\r\n k = Math.min(28, wpr / LOG_BASE + 2 | 0);\r\n\r\n for (i = k; i; --i) x = x.div(x.times(x).plus(1).sqrt().plus(1));\r\n\r\n external = false;\r\n\r\n j = Math.ceil(wpr / LOG_BASE);\r\n n = 1;\r\n x2 = x.times(x);\r\n r = new Ctor(x);\r\n px = x;\r\n\r\n // atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...\r\n for (; i !== -1;) {\r\n px = px.times(x2);\r\n t = r.minus(px.div(n += 2));\r\n\r\n px = px.times(x2);\r\n r = t.plus(px.div(n += 2));\r\n\r\n if (r.d[j] !== void 0) for (i = j; r.d[i] === t.d[i] && i--;);\r\n }\r\n\r\n if (k) r = r.times(2 << (k - 1));\r\n\r\n external = true;\r\n\r\n return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true);\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is a finite number, otherwise return false.\r\n *\r\n */\r\nP.isFinite = function () {\r\n return !!this.d;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is an integer, otherwise return false.\r\n *\r\n */\r\nP.isInteger = P.isInt = function () {\r\n return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is NaN, otherwise return false.\r\n *\r\n */\r\nP.isNaN = function () {\r\n return !this.s;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is negative, otherwise return false.\r\n *\r\n */\r\nP.isNegative = P.isNeg = function () {\r\n return this.s < 0;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is positive, otherwise return false.\r\n *\r\n */\r\nP.isPositive = P.isPos = function () {\r\n return this.s > 0;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is 0 or -0, otherwise return false.\r\n *\r\n */\r\nP.isZero = function () {\r\n return !!this.d && this.d[0] === 0;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of thi