Summary
Add nthRoot()
method in class BigDecimal
.
Problem
The class BigDecimal
already provides methods pow()
and sqrt()
for power and square root calculation, so, for symmetry, it would be useful introducing a method to compute integer nth roots too.
Solution
Implement nthRoot()
method in class BigDecimal
.
Specification
/**
* Returns an approximation to the {@code n}<sup>th</sup> root of {@code this}
* with rounding according to the context settings.
*
* <p>The preferred scale of the returned result is equal to
* {@code this.scale()/n}. The value of the returned result is
* always within 1.1 ulps of the exact decimal value for the
* precision in question, and if {@code n > 0}, the result is within
* one ulp of the exact decimal value. If the rounding mode is {@link
* RoundingMode#HALF_UP HALF_UP}, {@link RoundingMode#HALF_DOWN
* HALF_DOWN}, or {@link RoundingMode#HALF_EVEN HALF_EVEN}, the
* result is within 0.55 ulps of the exact decimal value, and if {@code n > 0},
* the result is within one half an ulp of the exact decimal value.
*
* <p>Special case:
* <ul>
* <li> The {@code n}<sup>th</sup> root of a number numerically equal to {@code
* ZERO} is numerically equal to {@code ZERO} with a preferred
* scale according to the general rule above. In particular, for
* {@code ZERO}, {@code ZERO.nthRoot(n, mc).equals(ZERO)} is true with
* any {@code MathContext} as an argument.
* </ul>
*
* @param n the root degree
* @param mc the context to use.
* @return the {@code n}<sup>th</sup> root of {@code this}.
* @throws ArithmeticException if {@code n == 0 || n == Integer.MIN_VALUE}.
* @throws ArithmeticException if {@code n} is even and {@code this} is negative.
* @throws ArithmeticException if {@code n} is negative and {@code this} is zero.
* @throws ArithmeticException if an exact result is requested
* ({@code mc.getPrecision() == 0}) and there is no finite decimal
* expansion of the exact result
* @throws ArithmeticException if
* {@code (mc.getRoundingMode() == RoundingMode.UNNECESSARY}) and
* the exact result cannot fit in {@code mc.getPrecision()} digits.
* @see #sqrt(MathContext)
* @see BigInteger#nthRoot(int)
* @since 26
* @apiNote Note that calling {@code nthRoot(2, mc)} is equivalent to calling {@code sqrt(mc)}.
*/
public BigDecimal nthRoot(int n, MathContext mc)
- csr of
-
JDK-8366478 BigDecimal roots
-
- Open
-