-
Notifications
You must be signed in to change notification settings - Fork 475
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support for nth root #156
Comments
Yes, I will consider it. Related. |
How's this consideration going? :D This would be handy. |
The nth root can be found using Decimal.prototype.nthRoot = function (n) {
return this.pow(new Decimal(1).div(n));
} Or more properly: Decimal.prototype.nthRoot = function (n, guardDigits = 6) {
const x = this;
const D = x.constructor;
const one = new D(1);
n = new D(n);
if (n.lt(one) || !n.isInteger()) {
throw Error('n must be a positive integer');
};
if (x.isZero()) return new D(x);
const p = D.precision;
const r = D.rounding;
D.precision = p + guardDigits;
D.rounding = D.ROUND_DOWN;
const y = one.div(n);
D.precision = p;
D.rounding = r;
return x.pow(y);
};
const x = new Decimal(27);
console.log( x.nthRoot(3).toString() ); // '3' Using Newton's method would be faster, in the same way as using Note that the above implementations are for demonstration purposes and have not been tested. |
It would be good to have a
nthRoot
method to calculate any integer root of a number exactly, as for a root like 6,pow(1/6)
leads to a slight loss of precision.The text was updated successfully, but these errors were encountered: