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)

21 lines (20 loc) 737 B
import { isLeftGreaterInner } from "../compare/utils.js"; import { PipeInner } from "../pipe/utils.js"; export const sqrtInner = (value, prec = [1n, 13], max = 100) => { if (value[0] < 0n) { throw new Error("Invalid input: Cannot take the square root of a negative value."); } let guess = value; for (let i = 0; i < max; i++) { const { bi: nextGuess } = new PipeInner() .div([value, guess]) .add([guess]) .mul([[5n, 1]]); const { bi } = new PipeInner().sub([nextGuess, guess]).abs(); if (isLeftGreaterInner({ left: prec, right: bi })) { return [nextGuess, prec[1]]; } guess = nextGuess; } return [guess, prec[1]]; };