UNPKG

@numio/bigmath

Version:

@numio/bigmath is an arbitrary-precision arithmetic library. It can be used for basic operations with decimal numbers (integers and float)

24 lines (23 loc) 945 B
import { isLeftGreaterInner } from "../compare/utils.js"; import { divInner } from "../operations/div/utils.js"; import { PipeInner } from "../pipe/utils.js"; import { calcInner } from "../shared/utils.js"; export const cbrtInner = (value, prec = [1n, 13], max = 100) => { if (value[0] < 0n) { throw new Error("Invalid input: Cannot take the cube root of a negative value."); } let guess = value; for (let i = 0; i < max; i++) { const mul = calcInner([guess, guess], (a, b) => a * b); const { bi: nextGuess } = new PipeInner().add([ calcInner([guess, [2n, 0]], (a, b) => a * b), divInner([value, mul], 20), ]).div([[3n, 0]]); const { bi } = new PipeInner().sub([nextGuess, guess]).abs(); if (isLeftGreaterInner({ left: prec, right: bi })) { return [nextGuess, prec[1]]; } guess = nextGuess; } return [guess, prec[1]]; };