Skip to content

Commit

Permalink
Merge branch 'feat/bigint-sqrt'
Browse files Browse the repository at this point in the history
  • Loading branch information
tubackkhoa committed Nov 29, 2023
2 parents 0767b2d + 2a50511 commit ef318e7
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions packages/oraidex-common/src/bigdecimal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,36 @@ export class BigDecimal {
return this;
}

static rootNth(value: DecimalLike, k = 2n) {
const big = new BigDecimal(value);

// re-calculate bigInt
const bigValue = big.bigInt * 10n ** BigInt(big._decimals);
if (bigValue < 0n) {
throw "negative number is not supported";
}

let o = 0n;
let x = bigValue;
let limit = 100;

while (x ** k !== k && x !== o && --limit) {
o = x;
x = ((k - 1n) * x + bigValue / x ** (k - 1n)) / k;
}

big.bigInt = x;
return big;
}

static sqrt(value: DecimalLike) {
return BigDecimal.rootNth(value);
}

sqrt() {
return BigDecimal.rootNth(this);
}

add(other: DecimalLike) {
return this.clone().iadd(other);
}
Expand Down

0 comments on commit ef318e7

Please sign in to comment.