111 * are discarded. When rounding increases the magnitude of the
112 * returned result, it is possible for a new digit position to be
113 * created by a carry propagating to a leading {@literal "9"} digit.
114 * For example, rounding the value 999.9 to three digits rounding up
115 * would be numerically equal to one thousand, represented as
116 * 100×10<sup>1</sup>. In such cases, the new {@literal "1"} is
117 * the leading digit position of the returned result.
118 *
119 * <p>Besides a logical exact result, each arithmetic operation has a
120 * preferred scale for representing a result. The preferred
121 * scale for each operation is listed in the table below.
122 *
123 * <table border>
124 * <caption><b>Preferred Scales for Results of Arithmetic Operations
125 * </b></caption>
126 * <tr><th>Operation</th><th>Preferred Scale of Result</th></tr>
127 * <tr><td>Add</td><td>max(addend.scale(), augend.scale())</td>
128 * <tr><td>Subtract</td><td>max(minuend.scale(), subtrahend.scale())</td>
129 * <tr><td>Multiply</td><td>multiplier.scale() + multiplicand.scale()</td>
130 * <tr><td>Divide</td><td>dividend.scale() - divisor.scale()</td>
131 * </table>
132 *
133 * These scales are the ones used by the methods which return exact
134 * arithmetic results; except that an exact divide may have to use a
135 * larger scale since the exact result may have more digits. For
136 * example, {@code 1/32} is {@code 0.03125}.
137 *
138 * <p>Before rounding, the scale of the logical exact intermediate
139 * result is the preferred scale for that operation. If the exact
140 * numerical result cannot be represented in {@code precision}
141 * digits, rounding selects the set of digits to return and the scale
142 * of the result is reduced from the scale of the intermediate result
143 * to the least scale which can represent the {@code precision}
144 * digits actually returned. If the exact result can be represented
145 * with at most {@code precision} digits, the representation
146 * of the result with the scale closest to the preferred scale is
147 * returned. In particular, an exactly representable quotient may be
148 * represented in fewer than {@code precision} digits by removing
149 * trailing zeros and decreasing the scale. For example, rounding to
150 * three digits using the {@linkplain RoundingMode#FLOOR floor}
329 */
330 public static final BigDecimal ZERO =
331 ZERO_THROUGH_TEN[0];
332
333 /**
334 * The value 1, with a scale of 0.
335 *
336 * @since 1.5
337 */
338 public static final BigDecimal ONE =
339 ZERO_THROUGH_TEN[1];
340
341 /**
342 * The value 10, with a scale of 0.
343 *
344 * @since 1.5
345 */
346 public static final BigDecimal TEN =
347 ZERO_THROUGH_TEN[10];
348
349 // Constructors
350
351 /**
352 * Trusted package private constructor.
353 * Trusted simply means if val is INFLATED, intVal could not be null and
354 * if intVal is null, val could not be INFLATED.
355 */
356 BigDecimal(BigInteger intVal, long val, int scale, int prec) {
357 this.scale = scale;
358 this.precision = prec;
359 this.intCompact = val;
360 this.intVal = intVal;
361 }
362
363 /**
364 * Translates a character array representation of a
365 * {@code BigDecimal} into a {@code BigDecimal}, accepting the
366 * same sequence of characters as the {@link #BigDecimal(String)}
367 * constructor, while allowing a sub-array to be specified.
368 *
1976 * initial element and the remainder is the final element.
1977 * @throws ArithmeticException if {@code divisor==0}
1978 * @throws ArithmeticException if the result is inexact but the
1979 * rounding mode is {@code UNNECESSARY}, or {@code mc.precision}
1980 * {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would
1981 * require a precision of more than {@code mc.precision} digits.
1982 * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
1983 * @see #remainder(java.math.BigDecimal, java.math.MathContext)
1984 * @since 1.5
1985 */
1986 public BigDecimal[] divideAndRemainder(BigDecimal divisor, MathContext mc) {
1987 if (mc.precision == 0)
1988 return divideAndRemainder(divisor);
1989
1990 BigDecimal[] result = new BigDecimal[2];
1991 BigDecimal lhs = this;
1992
1993 result[0] = lhs.divideToIntegralValue(divisor, mc);
1994 result[1] = lhs.subtract(result[0].multiply(divisor));
1995 return result;
1996 }
1997
1998 /**
1999 * Returns a {@code BigDecimal} whose value is
2000 * <code>(this<sup>n</sup>)</code>, The power is computed exactly, to
2001 * unlimited precision.
2002 *
2003 * <p>The parameter {@code n} must be in the range 0 through
2004 * 999999999, inclusive. {@code ZERO.pow(0)} returns {@link
2005 * #ONE}.
2006 *
2007 * Note that future releases may expand the allowable exponent
2008 * range of this method.
2009 *
2010 * @param n power to raise this {@code BigDecimal} to.
2011 * @return <code>this<sup>n</sup></code>
2012 * @throws ArithmeticException if {@code n} is out of range.
2013 * @since 1.5
2014 */
2015 public BigDecimal pow(int n) {
|
111 * are discarded. When rounding increases the magnitude of the
112 * returned result, it is possible for a new digit position to be
113 * created by a carry propagating to a leading {@literal "9"} digit.
114 * For example, rounding the value 999.9 to three digits rounding up
115 * would be numerically equal to one thousand, represented as
116 * 100×10<sup>1</sup>. In such cases, the new {@literal "1"} is
117 * the leading digit position of the returned result.
118 *
119 * <p>Besides a logical exact result, each arithmetic operation has a
120 * preferred scale for representing a result. The preferred
121 * scale for each operation is listed in the table below.
122 *
123 * <table border>
124 * <caption><b>Preferred Scales for Results of Arithmetic Operations
125 * </b></caption>
126 * <tr><th>Operation</th><th>Preferred Scale of Result</th></tr>
127 * <tr><td>Add</td><td>max(addend.scale(), augend.scale())</td>
128 * <tr><td>Subtract</td><td>max(minuend.scale(), subtrahend.scale())</td>
129 * <tr><td>Multiply</td><td>multiplier.scale() + multiplicand.scale()</td>
130 * <tr><td>Divide</td><td>dividend.scale() - divisor.scale()</td>
131 * <tr><td>Square root</td><td>radicand.scale()/2</td>
132 * </table>
133 *
134 * These scales are the ones used by the methods which return exact
135 * arithmetic results; except that an exact divide may have to use a
136 * larger scale since the exact result may have more digits. For
137 * example, {@code 1/32} is {@code 0.03125}.
138 *
139 * <p>Before rounding, the scale of the logical exact intermediate
140 * result is the preferred scale for that operation. If the exact
141 * numerical result cannot be represented in {@code precision}
142 * digits, rounding selects the set of digits to return and the scale
143 * of the result is reduced from the scale of the intermediate result
144 * to the least scale which can represent the {@code precision}
145 * digits actually returned. If the exact result can be represented
146 * with at most {@code precision} digits, the representation
147 * of the result with the scale closest to the preferred scale is
148 * returned. In particular, an exactly representable quotient may be
149 * represented in fewer than {@code precision} digits by removing
150 * trailing zeros and decreasing the scale. For example, rounding to
151 * three digits using the {@linkplain RoundingMode#FLOOR floor}
330 */
331 public static final BigDecimal ZERO =
332 ZERO_THROUGH_TEN[0];
333
334 /**
335 * The value 1, with a scale of 0.
336 *
337 * @since 1.5
338 */
339 public static final BigDecimal ONE =
340 ZERO_THROUGH_TEN[1];
341
342 /**
343 * The value 10, with a scale of 0.
344 *
345 * @since 1.5
346 */
347 public static final BigDecimal TEN =
348 ZERO_THROUGH_TEN[10];
349
350 /**
351 * The value 0.1, with a scale of 1.
352 */
353 private static final BigDecimal ONE_TENTH = valueOf(1L, 1);
354
355 /**
356 * The value 0.5, with a scale of 1.
357 */
358 private static final BigDecimal ONE_HALF = valueOf(5L, 1);
359
360 // Constructors
361
362 /**
363 * Trusted package private constructor.
364 * Trusted simply means if val is INFLATED, intVal could not be null and
365 * if intVal is null, val could not be INFLATED.
366 */
367 BigDecimal(BigInteger intVal, long val, int scale, int prec) {
368 this.scale = scale;
369 this.precision = prec;
370 this.intCompact = val;
371 this.intVal = intVal;
372 }
373
374 /**
375 * Translates a character array representation of a
376 * {@code BigDecimal} into a {@code BigDecimal}, accepting the
377 * same sequence of characters as the {@link #BigDecimal(String)}
378 * constructor, while allowing a sub-array to be specified.
379 *
1987 * initial element and the remainder is the final element.
1988 * @throws ArithmeticException if {@code divisor==0}
1989 * @throws ArithmeticException if the result is inexact but the
1990 * rounding mode is {@code UNNECESSARY}, or {@code mc.precision}
1991 * {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would
1992 * require a precision of more than {@code mc.precision} digits.
1993 * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
1994 * @see #remainder(java.math.BigDecimal, java.math.MathContext)
1995 * @since 1.5
1996 */
1997 public BigDecimal[] divideAndRemainder(BigDecimal divisor, MathContext mc) {
1998 if (mc.precision == 0)
1999 return divideAndRemainder(divisor);
2000
2001 BigDecimal[] result = new BigDecimal[2];
2002 BigDecimal lhs = this;
2003
2004 result[0] = lhs.divideToIntegralValue(divisor, mc);
2005 result[1] = lhs.subtract(result[0].multiply(divisor));
2006 return result;
2007 }
2008
2009 /**
2010 * Returns an approximation to the square root of {@code this}
2011 * with rounding according to the context settings.
2012 *
2013 * <p>The preferred scale of the returned result is equal to
2014 * {@code this.scale()/2}. The value of the returned result is
2015 * always within one ulp of the exact decimal value for the
2016 * precision in question. If the rounding mode is {@link
2017 * RoundingMode#HALF_UP HALF_UP}, {@link RoundingMode#HALF_DOWN
2018 * HALF_DOWN}, or {@link RoundingMode#HALF_EVEN HALF_EVEN}, the
2019 * result is within one half an ulp of the exact decimal value.
2020 *
2021 * <p>Special case:
2022 * <ul>
2023 * <li> The square root of a number numerically equal to {@code
2024 * ZERO} is numerically equal to {@code ZERO} with a preferred
2025 * scale according to the general rule above. In particular, for
2026 * {@code ZERO}}, {@code ZERO.sqrt(mc).equals(ZERO)} is true with
2027 * any {@code MathContext} as an argument.
2028 * </ul>
2029 *
2030 * @param mc the context to use.
2031 * @return the square root of {@code this}.
2032 * @throws ArithmeticException if {@code this} is less than zero.
2033 * @throws ArithmeticException if an exact result is requested
2034 * ({@code mc.getPrecision()==0}) and there is no finite decimal
2035 * expansion of the exact result
2036 * @throws ArithmeticException if
2037 * {@code (mc.getRoundingMode()==RoundingMode.UNNECESSARY}) and
2038 * the exact result cannot fit in {@code mc.getPrecision()}
2039 * digits.
2040 * @since 9
2041 */
2042 public BigDecimal sqrt(MathContext mc) {
2043 int signum = signum();
2044 if (signum == 1) {
2045 /*
2046 * The following code draws on the algorithm presented in
2047 * "Properly Rounded Variable Precision Square Root," Hull and
2048 * Abrham, ACM Transactions on Mathematical Software, Vol 11,
2049 * No. 3, September 1985, Pages 229-237.
2050 *
2051 * The BigDecimal computational model differs from the one
2052 * presented in the paper in several ways: first BigDecimal
2053 * numbers aren't necessarily normalized, second many more
2054 * rounding modes are supported, including UNNECESSARY, and
2055 * exact results can be requested.
2056 *
2057 * The main steps of the algorithm below are as follow, first
2058 * argument reduce the value to the numerical range [1, 10)
2059 * using the following relations:
2060 *
2061 * x = y * 10 ^ exp
2062 * sqrt(x) = sqrt(y) * 10^(exp / 2) if exp is even
2063 * sqrt(x) = sqrt(y/10) * 10 ^((exp+1)/2) is exp is odd
2064 *
2065 * Then use Newton's iteration on the reduced value to compute
2066 * the numerical digits of the desired result.
2067 *
2068 * Finally, scale back to the desired exponent range and
2069 * perform any adjustment to get the preferred scale in the
2070 * representation.
2071 */
2072
2073 // The code below favors relative simplicity over checking
2074 // for special cases that could run faster.
2075
2076 int preferredScale = this.scale()/2;
2077 BigDecimal zeroWithFinalPreferredScale = valueOf(0L, preferredScale);
2078
2079 // First phase of numerical normalization, strip trailing
2080 // zeros and check for even powers of 10.
2081 BigDecimal stripped = this.stripTrailingZeros();
2082 int strippedScale = stripped.scale();
2083
2084 // Numerically sqrt(10^2N) = 10^N
2085 if (stripped.isPowerOfTen() &&
2086 strippedScale % 2 == 0) {
2087 BigDecimal result = valueOf(1L, strippedScale/2);
2088 if (result.scale() != preferredScale) {
2089 // Adjust to requested precision and preferred
2090 // scale as appropriate.
2091 result = result.add(zeroWithFinalPreferredScale, mc);
2092 }
2093 return result;
2094 }
2095
2096 // After stripTrailingZeros, the representation is normalized as
2097 //
2098 // unscaledValue * 10^(-scale)
2099 //
2100 // where unscaledValue is an integer with the mimimum
2101 // precision for the cohort of the numerical value. To
2102 // allow binary floating-point hardware to be used to get
2103 // approximately a 15 digit approximation to the square
2104 // root, it is helpful to instead normalize this as so
2105 // that the significand portion is to right of the decimal
2106 // point by roughly (scale() - precision() +1).
2107
2108 // Now the precision / scale adjustment
2109 int scaleAdjust = 0;
2110 int scale = stripped.scale() - stripped.precision() + 1;
2111 if (scale % 2 == 0) {
2112 scaleAdjust = scale;
2113 } else {
2114 scaleAdjust = scale - 1;
2115 }
2116
2117 BigDecimal working = stripped.scaleByPowerOfTen(scaleAdjust);
2118
2119 assert // Verify 0.1 <= working < 10
2120 ONE_TENTH.compareTo(working) <= 0 && working.compareTo(TEN) < 0;
2121
2122 // Use good ole' Math.sqrt to get the initial guess for
2123 // the Newton iteration, good to at least 15 decimal
2124 // digits. This approach does incur the cost of a
2125 //
2126 // BigDecimal -> double -> BigDecimal
2127 //
2128 // conversion cycle, but it avoids the need for several
2129 // Newton iterations in BigDecimal arithmetic to get the
2130 // working answer to 15 digits of precision. If many fewer
2131 // than 15 digits were needed, it might be faster to do
2132 // the loop entirely in BigDecimal arithmetic.
2133 //
2134 // (A double value might have as much many as 17 decimal
2135 // digits of precision; it depends on the relative density
2136 // of binary and decimal numbers at different regions of
2137 // the number line.)
2138 //
2139 // (It would be possible to check for certain special
2140 // cases to avoid doing any Newton iterations. For
2141 // example, if the BigDecimal -> double conversion was
2142 // known to be exact and the rounding mode had a
2143 // low-enough precision, the post-Newton rounding logic
2144 // could be applied directly.)
2145
2146 BigDecimal guess = new BigDecimal(Math.sqrt(working.doubleValue()));
2147 int guessPrecision = 15;
2148 int originalPrecision = mc.getPrecision();
2149 int targetPrecision;
2150
2151 // If an exact value is requested, it must only need about
2152 // half of the input digits to represent since multiplying
2153 // an N digit number by itself yield a 2N-1 digit or 2N
2154 // digit result.
2155 if (originalPrecision == 0) {
2156 targetPrecision = stripped.precision()/2 + 1;
2157 } else {
2158 targetPrecision = originalPrecision;
2159 }
2160
2161 // When setting the precision to use inside the Newton
2162 // iteration loop, take care to avoid the case where the
2163 // precision of the input exceeds the requested precision
2164 // and rounding the input value too soon.
2165 BigDecimal approx = guess;
2166 int workingPrecision = working.precision();
2167 do {
2168 int tmpPrecision = Math.max(Math.max(guessPrecision, targetPrecision + 2),
2169 workingPrecision);
2170 MathContext mcTmp = new MathContext(tmpPrecision, RoundingMode.HALF_EVEN);
2171 // approx = 0.5 * (approx + fraction / approx)
2172 approx = ONE_HALF.multiply(approx.add(working.divide(approx, mcTmp), mcTmp));
2173 guessPrecision *= 2;
2174 } while (guessPrecision < targetPrecision + 2);
2175
2176 BigDecimal result;
2177 RoundingMode targetRm = mc.getRoundingMode();
2178 if (targetRm == RoundingMode.UNNECESSARY || originalPrecision == 0) {
2179 RoundingMode tmpRm =
2180 (targetRm == RoundingMode.UNNECESSARY) ? RoundingMode.DOWN : targetRm;
2181 MathContext mcTmp = new MathContext(targetPrecision, tmpRm);
2182 result = approx.scaleByPowerOfTen(-scaleAdjust/2).round(mcTmp);
2183
2184 // If result*result != this numerically, the square
2185 // root isn't exact
2186 if (this.subtract(result.multiply(result)).compareTo(ZERO) != 0) {
2187 throw new ArithmeticException("Computed square root not exact.");
2188 }
2189 } else {
2190 result = approx.scaleByPowerOfTen(-scaleAdjust/2).round(mc);
2191 }
2192
2193 if (result.scale() != preferredScale) {
2194 // The preferred scale of an add is
2195 // max(addend.scale(), augend.scale()). Therefore, if
2196 // the scale of the result is first minimized using
2197 // stripTrailingZeros(), adding a zero of the
2198 // preferred scale rounding the correct precision will
2199 // perform the proper scale vs precision tradeoffs.
2200 result = result.stripTrailingZeros().
2201 add(zeroWithFinalPreferredScale,
2202 new MathContext(originalPrecision, RoundingMode.UNNECESSARY));
2203 }
2204 assert squareRootResultAssertions(result, mc);
2205 return result;
2206 } else {
2207 switch (signum) {
2208 case -1:
2209 throw new ArithmeticException("Attempted square root " +
2210 "of negative BigDecimal");
2211 case 0:
2212 return valueOf(0L, scale()/2);
2213
2214 default:
2215 throw new AssertionError("Bad value from signum");
2216 }
2217 }
2218 }
2219
2220 private boolean isPowerOfTen() {
2221 return BigInteger.ONE.equals(this.unscaledValue());
2222 }
2223
2224 /**
2225 * For nonzero values, check numerical correctness properties of
2226 * the computed result for the chosen rounding mode .
2227 *
2228 * For the directed roundings, for DOWN and FLOOR, result^2 must
2229 * be {@code <=} the input and (result+ulp)^2 must be {@code >} the
2230 * input. Conversely, for UP and CEIL, result^2 must be {@code >=} the
2231 * input and (result-ulp)^2 must be {@code <} the input.
2232 */
2233 private boolean squareRootResultAssertions(BigDecimal result, MathContext mc) {
2234 if (result.signum() == 0) {
2235 return squareRootZeroResultAssertions(result, mc);
2236 } else {
2237 RoundingMode rm = mc.getRoundingMode();
2238 BigDecimal ulp = result.ulp();
2239 BigDecimal neighborUp = result.add(ulp);
2240 // Make neighbor down accurate even for powers of ten
2241 if (this.isPowerOfTen()) {
2242 ulp = ulp.divide(TEN);
2243 }
2244 BigDecimal neighborDown = result.subtract(ulp);
2245
2246 // Both the starting value and result should be nonzero and positive.
2247 if (result.signum() != 1 ||
2248 this.signum() != 1) {
2249 return false;
2250 }
2251
2252 switch (rm) {
2253 case DOWN:
2254 case FLOOR:
2255 return
2256 result.multiply(result).compareTo(this) <= 0 &&
2257 neighborUp.multiply(neighborUp).compareTo(this) > 0;
2258
2259 case UP:
2260 case CEILING:
2261 return
2262 result.multiply(result).compareTo(this) >= 0 &&
2263 neighborDown.multiply(neighborDown).compareTo(this) < 0;
2264
2265 case HALF_DOWN:
2266 case HALF_EVEN:
2267 case HALF_UP:
2268 BigDecimal err = result.multiply(result).subtract(this).abs();
2269 BigDecimal errUp = neighborUp.multiply(neighborUp).subtract(this);
2270 BigDecimal errDown = this.subtract(neighborDown.multiply(neighborDown));
2271 // All error values should be positive so don't need to
2272 // compare absolute values.
2273
2274 int err_comp_errUp = err.compareTo(errUp);
2275 int err_comp_errDown = err.compareTo(errDown);
2276
2277 return
2278 errUp.signum() == 1 &&
2279 errDown.signum() == 1 &&
2280
2281 err_comp_errUp <= 0 &&
2282 err_comp_errDown <= 0 &&
2283
2284 ((err_comp_errUp == 0 ) ? err_comp_errDown < 0 : true) &&
2285 ((err_comp_errDown == 0 ) ? err_comp_errUp < 0 : true);
2286 // && could check for digit conditions for ties too
2287
2288 default: // Definition of UNNECESSARY already verified.
2289 return true;
2290 }
2291 }
2292 }
2293
2294 private boolean squareRootZeroResultAssertions(BigDecimal result, MathContext mc) {
2295 return this.compareTo(ZERO) == 0;
2296 }
2297
2298 /**
2299 * Returns a {@code BigDecimal} whose value is
2300 * <code>(this<sup>n</sup>)</code>, The power is computed exactly, to
2301 * unlimited precision.
2302 *
2303 * <p>The parameter {@code n} must be in the range 0 through
2304 * 999999999, inclusive. {@code ZERO.pow(0)} returns {@link
2305 * #ONE}.
2306 *
2307 * Note that future releases may expand the allowable exponent
2308 * range of this method.
2309 *
2310 * @param n power to raise this {@code BigDecimal} to.
2311 * @return <code>this<sup>n</sup></code>
2312 * @throws ArithmeticException if {@code n} is out of range.
2313 * @since 1.5
2314 */
2315 public BigDecimal pow(int n) {
|