Save This Page
Home » openjdk-7 » java » math » [javadoc | source]
    1   /*
    2    * Portions Copyright 1996-2007 Sun Microsystems, Inc.  All Rights Reserved.
    3    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    4    *
    5    * This code is free software; you can redistribute it and/or modify it
    6    * under the terms of the GNU General Public License version 2 only, as
    7    * published by the Free Software Foundation.  Sun designates this
    8    * particular file as subject to the "Classpath" exception as provided
    9    * by Sun in the LICENSE file that accompanied this code.
   10    *
   11    * This code is distributed in the hope that it will be useful, but WITHOUT
   12    * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   13    * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   14    * version 2 for more details (a copy is included in the LICENSE file that
   15    * accompanied this code).
   16    *
   17    * You should have received a copy of the GNU General Public License version
   18    * 2 along with this work; if not, write to the Free Software Foundation,
   19    * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   20    *
   21    * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   22    * CA 95054 USA or visit www.sun.com if you need additional information or
   23    * have any questions.
   24    */
   25   
   26   /*
   27    * Portions Copyright IBM Corporation, 2001. All Rights Reserved.
   28    */
   29   
   30   package java.math;
   31   
   32   /**
   33    * Immutable, arbitrary-precision signed decimal numbers.  A
   34    * {@code BigDecimal} consists of an arbitrary precision integer
   35    * <i>unscaled value</i> and a 32-bit integer <i>scale</i>.  If zero
   36    * or positive, the scale is the number of digits to the right of the
   37    * decimal point.  If negative, the unscaled value of the number is
   38    * multiplied by ten to the power of the negation of the scale.  The
   39    * value of the number represented by the {@code BigDecimal} is
   40    * therefore <tt>(unscaledValue &times; 10<sup>-scale</sup>)</tt>.
   41    *
   42    * <p>The {@code BigDecimal} class provides operations for
   43    * arithmetic, scale manipulation, rounding, comparison, hashing, and
   44    * format conversion.  The {@link #toString} method provides a
   45    * canonical representation of a {@code BigDecimal}.
   46    *
   47    * <p>The {@code BigDecimal} class gives its user complete control
   48    * over rounding behavior.  If no rounding mode is specified and the
   49    * exact result cannot be represented, an exception is thrown;
   50    * otherwise, calculations can be carried out to a chosen precision
   51    * and rounding mode by supplying an appropriate {@link MathContext}
   52    * object to the operation.  In either case, eight <em>rounding
   53    * modes</em> are provided for the control of rounding.  Using the
   54    * integer fields in this class (such as {@link #ROUND_HALF_UP}) to
   55    * represent rounding mode is largely obsolete; the enumeration values
   56    * of the {@code RoundingMode} {@code enum}, (such as {@link
   57    * RoundingMode#HALF_UP}) should be used instead.
   58    *
   59    * <p>When a {@code MathContext} object is supplied with a precision
   60    * setting of 0 (for example, {@link MathContext#UNLIMITED}),
   61    * arithmetic operations are exact, as are the arithmetic methods
   62    * which take no {@code MathContext} object.  (This is the only
   63    * behavior that was supported in releases prior to 5.)  As a
   64    * corollary of computing the exact result, the rounding mode setting
   65    * of a {@code MathContext} object with a precision setting of 0 is
   66    * not used and thus irrelevant.  In the case of divide, the exact
   67    * quotient could have an infinitely long decimal expansion; for
   68    * example, 1 divided by 3.  If the quotient has a nonterminating
   69    * decimal expansion and the operation is specified to return an exact
   70    * result, an {@code ArithmeticException} is thrown.  Otherwise, the
   71    * exact result of the division is returned, as done for other
   72    * operations.
   73    *
   74    * <p>When the precision setting is not 0, the rules of
   75    * {@code BigDecimal} arithmetic are broadly compatible with selected
   76    * modes of operation of the arithmetic defined in ANSI X3.274-1996
   77    * and ANSI X3.274-1996/AM 1-2000 (section 7.4).  Unlike those
   78    * standards, {@code BigDecimal} includes many rounding modes, which
   79    * were mandatory for division in {@code BigDecimal} releases prior
   80    * to 5.  Any conflicts between these ANSI standards and the
   81    * {@code BigDecimal} specification are resolved in favor of
   82    * {@code BigDecimal}.
   83    *
   84    * <p>Since the same numerical value can have different
   85    * representations (with different scales), the rules of arithmetic
   86    * and rounding must specify both the numerical result and the scale
   87    * used in the result's representation.
   88    *
   89    *
   90    * <p>In general the rounding modes and precision setting determine
   91    * how operations return results with a limited number of digits when
   92    * the exact result has more digits (perhaps infinitely many in the
   93    * case of division) than the number of digits returned.
   94    *
   95    * First, the
   96    * total number of digits to return is specified by the
   97    * {@code MathContext}'s {@code precision} setting; this determines
   98    * the result's <i>precision</i>.  The digit count starts from the
   99    * leftmost nonzero digit of the exact result.  The rounding mode
  100    * determines how any discarded trailing digits affect the returned
  101    * result.
  102    *
  103    * <p>For all arithmetic operators , the operation is carried out as
  104    * though an exact intermediate result were first calculated and then
  105    * rounded to the number of digits specified by the precision setting
  106    * (if necessary), using the selected rounding mode.  If the exact
  107    * result is not returned, some digit positions of the exact result
  108    * are discarded.  When rounding increases the magnitude of the
  109    * returned result, it is possible for a new digit position to be
  110    * created by a carry propagating to a leading {@literal "9"} digit.
  111    * For example, rounding the value 999.9 to three digits rounding up
  112    * would be numerically equal to one thousand, represented as
  113    * 100&times;10<sup>1</sup>.  In such cases, the new {@literal "1"} is
  114    * the leading digit position of the returned result.
  115    *
  116    * <p>Besides a logical exact result, each arithmetic operation has a
  117    * preferred scale for representing a result.  The preferred
  118    * scale for each operation is listed in the table below.
  119    *
  120    * <table border>
  121    * <caption top><h3>Preferred Scales for Results of Arithmetic Operations
  122    * </h3></caption>
  123    * <tr><th>Operation</th><th>Preferred Scale of Result</th></tr>
  124    * <tr><td>Add</td><td>max(addend.scale(), augend.scale())</td>
  125    * <tr><td>Subtract</td><td>max(minuend.scale(), subtrahend.scale())</td>
  126    * <tr><td>Multiply</td><td>multiplier.scale() + multiplicand.scale()</td>
  127    * <tr><td>Divide</td><td>dividend.scale() - divisor.scale()</td>
  128    * </table>
  129    *
  130    * These scales are the ones used by the methods which return exact
  131    * arithmetic results; except that an exact divide may have to use a
  132    * larger scale since the exact result may have more digits.  For
  133    * example, {@code 1/32} is {@code 0.03125}.
  134    *
  135    * <p>Before rounding, the scale of the logical exact intermediate
  136    * result is the preferred scale for that operation.  If the exact
  137    * numerical result cannot be represented in {@code precision}
  138    * digits, rounding selects the set of digits to return and the scale
  139    * of the result is reduced from the scale of the intermediate result
  140    * to the least scale which can represent the {@code precision}
  141    * digits actually returned.  If the exact result can be represented
  142    * with at most {@code precision} digits, the representation
  143    * of the result with the scale closest to the preferred scale is
  144    * returned.  In particular, an exactly representable quotient may be
  145    * represented in fewer than {@code precision} digits by removing
  146    * trailing zeros and decreasing the scale.  For example, rounding to
  147    * three digits using the {@linkplain RoundingMode#FLOOR floor}
  148    * rounding mode, <br>
  149    *
  150    * {@code 19/100 = 0.19   // integer=19,  scale=2} <br>
  151    *
  152    * but<br>
  153    *
  154    * {@code 21/110 = 0.190  // integer=190, scale=3} <br>
  155    *
  156    * <p>Note that for add, subtract, and multiply, the reduction in
  157    * scale will equal the number of digit positions of the exact result
  158    * which are discarded. If the rounding causes a carry propagation to
  159    * create a new high-order digit position, an additional digit of the
  160    * result is discarded than when no new digit position is created.
  161    *
  162    * <p>Other methods may have slightly different rounding semantics.
  163    * For example, the result of the {@code pow} method using the
  164    * {@linkplain #pow(int, MathContext) specified algorithm} can
  165    * occasionally differ from the rounded mathematical result by more
  166    * than one unit in the last place, one <i>{@linkplain #ulp() ulp}</i>.
  167    *
  168    * <p>Two types of operations are provided for manipulating the scale
  169    * of a {@code BigDecimal}: scaling/rounding operations and decimal
  170    * point motion operations.  Scaling/rounding operations ({@link
  171    * #setScale setScale} and {@link #round round}) return a
  172    * {@code BigDecimal} whose value is approximately (or exactly) equal
  173    * to that of the operand, but whose scale or precision is the
  174    * specified value; that is, they increase or decrease the precision
  175    * of the stored number with minimal effect on its value.  Decimal
  176    * point motion operations ({@link #movePointLeft movePointLeft} and
  177    * {@link #movePointRight movePointRight}) return a
  178    * {@code BigDecimal} created from the operand by moving the decimal
  179    * point a specified distance in the specified direction.
  180    *
  181    * <p>For the sake of brevity and clarity, pseudo-code is used
  182    * throughout the descriptions of {@code BigDecimal} methods.  The
  183    * pseudo-code expression {@code (i + j)} is shorthand for "a
  184    * {@code BigDecimal} whose value is that of the {@code BigDecimal}
  185    * {@code i} added to that of the {@code BigDecimal}
  186    * {@code j}." The pseudo-code expression {@code (i == j)} is
  187    * shorthand for "{@code true} if and only if the
  188    * {@code BigDecimal} {@code i} represents the same value as the
  189    * {@code BigDecimal} {@code j}." Other pseudo-code expressions
  190    * are interpreted similarly.  Square brackets are used to represent
  191    * the particular {@code BigInteger} and scale pair defining a
  192    * {@code BigDecimal} value; for example [19, 2] is the
  193    * {@code BigDecimal} numerically equal to 0.19 having a scale of 2.
  194    *
  195    * <p>Note: care should be exercised if {@code BigDecimal} objects
  196    * are used as keys in a {@link java.util.SortedMap SortedMap} or
  197    * elements in a {@link java.util.SortedSet SortedSet} since
  198    * {@code BigDecimal}'s <i>natural ordering</i> is <i>inconsistent
  199    * with equals</i>.  See {@link Comparable}, {@link
  200    * java.util.SortedMap} or {@link java.util.SortedSet} for more
  201    * information.
  202    *
  203    * <p>All methods and constructors for this class throw
  204    * {@code NullPointerException} when passed a {@code null} object
  205    * reference for any input parameter.
  206    *
  207    * @see     BigInteger
  208    * @see     MathContext
  209    * @see     RoundingMode
  210    * @see     java.util.SortedMap
  211    * @see     java.util.SortedSet
  212    * @author  Josh Bloch
  213    * @author  Mike Cowlishaw
  214    * @author  Joseph D. Darcy
  215    */
  216   public class BigDecimal extends Number implements Comparable<BigDecimal> {
  217       /**
  218        * The unscaled value of this BigDecimal, as returned by {@link
  219        * #unscaledValue}.
  220        *
  221        * @serial
  222        * @see #unscaledValue
  223        */
  224       private volatile BigInteger intVal;
  225   
  226       /**
  227        * The scale of this BigDecimal, as returned by {@link #scale}.
  228        *
  229        * @serial
  230        * @see #scale
  231        */
  232       private int scale = 0;  // Note: this may have any value, so
  233                               // calculations must be done in longs
  234       /**
  235        * The number of decimal digits in this BigDecimal, or 0 if the
  236        * number of digits are not known (lookaside information).  If
  237        * nonzero, the value is guaranteed correct.  Use the precision()
  238        * method to obtain and set the value if it might be 0.  This
  239        * field is mutable until set nonzero.
  240        *
  241        * @since  1.5
  242        */
  243       private volatile transient int precision = 0;
  244   
  245       /**
  246        * Used to store the canonical string representation, if computed.
  247        */
  248       private volatile transient String stringCache = null;
  249   
  250       /**
  251        * Sentinel value for {@link #intCompact} indicating the
  252        * significand information is only available from {@code intVal}.
  253        */
  254       private static final long INFLATED = Long.MIN_VALUE;
  255   
  256       /**
  257        * If the absolute value of the significand of this BigDecimal is
  258        * less than or equal to {@code Long.MAX_VALUE}, the value can be
  259        * compactly stored in this field and used in computations.
  260        */
  261       private transient long intCompact = INFLATED;
  262   
  263       // All 18-digit base ten strings fit into a long; not all 19-digit
  264       // strings will
  265       private static final int MAX_COMPACT_DIGITS = 18;
  266   
  267       private static final int MAX_BIGINT_BITS = 62;
  268   
  269       /* Appease the serialization gods */
  270       private static final long serialVersionUID = 6108874887143696463L;
  271   
  272       // Cache of common small BigDecimal values.
  273       private static final BigDecimal zeroThroughTen[] = {
  274           new BigDecimal(BigInteger.ZERO,         0,  0),
  275           new BigDecimal(BigInteger.ONE,          1,  0),
  276           new BigDecimal(BigInteger.valueOf(2),   2,  0),
  277           new BigDecimal(BigInteger.valueOf(3),   3,  0),
  278           new BigDecimal(BigInteger.valueOf(4),   4,  0),
  279           new BigDecimal(BigInteger.valueOf(5),   5,  0),
  280           new BigDecimal(BigInteger.valueOf(6),   6,  0),
  281           new BigDecimal(BigInteger.valueOf(7),   7,  0),
  282           new BigDecimal(BigInteger.valueOf(8),   8,  0),
  283           new BigDecimal(BigInteger.valueOf(9),   9,  0),
  284           new BigDecimal(BigInteger.TEN,          10, 0),
  285       };
  286   
  287       // Constants
  288       /**
  289        * The value 0, with a scale of 0.
  290        *
  291        * @since  1.5
  292        */
  293       public static final BigDecimal ZERO =
  294           zeroThroughTen[0];
  295   
  296       /**
  297        * The value 1, with a scale of 0.
  298        *
  299        * @since  1.5
  300        */
  301       public static final BigDecimal ONE =
  302           zeroThroughTen[1];
  303   
  304       /**
  305        * The value 10, with a scale of 0.
  306        *
  307        * @since  1.5
  308        */
  309       public static final BigDecimal TEN =
  310           zeroThroughTen[10];
  311   
  312       // Constructors
  313   
  314       /**
  315        * Translates a character array representation of a
  316        * {@code BigDecimal} into a {@code BigDecimal}, accepting the
  317        * same sequence of characters as the {@link #BigDecimal(String)}
  318        * constructor, while allowing a sub-array to be specified.
  319        *
  320        * <p>Note that if the sequence of characters is already available
  321        * within a character array, using this constructor is faster than
  322        * converting the {@code char} array to string and using the
  323        * {@code BigDecimal(String)} constructor .
  324        *
  325        * @param  in {@code char} array that is the source of characters.
  326        * @param  offset first character in the array to inspect.
  327        * @param  len number of characters to consider.
  328        * @throws NumberFormatException if {@code in} is not a valid
  329        *         representation of a {@code BigDecimal} or the defined subarray
  330        *         is not wholly within {@code in}.
  331        * @since  1.5
  332        */
  333       public BigDecimal(char[] in, int offset, int len) {
  334           // This is the primary string to BigDecimal constructor; all
  335           // incoming strings end up here; it uses explicit (inline)
  336           // parsing for speed and generates at most one intermediate
  337           // (temporary) object (a char[] array).
  338   
  339           // use array bounds checking to handle too-long, len == 0,
  340           // bad offset, etc.
  341           try {
  342               // handle the sign
  343               boolean isneg = false;          // assume positive
  344               if (in[offset] == '-') {
  345                   isneg = true;               // leading minus means negative
  346                   offset++;
  347                   len--;
  348               } else if (in[offset] == '+') { // leading + allowed
  349                   offset++;
  350                   len--;
  351               }
  352   
  353               // should now be at numeric part of the significand
  354               int dotoff = -1;                 // '.' offset, -1 if none
  355               int cfirst = offset;             // record start of integer
  356               long exp = 0;                    // exponent
  357               if (len > in.length)             // protect against huge length
  358                   throw new NumberFormatException();
  359               char coeff[] = new char[len];    // integer significand array
  360               char c;                          // work
  361   
  362               for (; len > 0; offset++, len--) {
  363                   c = in[offset];
  364                   if ((c >= '0' && c <= '9') || Character.isDigit(c)) {
  365                       // have digit
  366                       coeff[precision] = c;
  367                       precision++;             // count of digits
  368                       continue;
  369                   }
  370                   if (c == '.') {
  371                       // have dot
  372                       if (dotoff >= 0)         // two dots
  373                           throw new NumberFormatException();
  374                       dotoff = offset;
  375                       continue;
  376                   }
  377                   // exponent expected
  378                   if ((c != 'e') && (c != 'E'))
  379                       throw new NumberFormatException();
  380                   offset++;
  381                   c = in[offset];
  382                   len--;
  383                   boolean negexp = false;
  384                   // optional sign
  385                   if (c == '-' || c == '+') {
  386                       negexp = (c == '-');
  387                       offset++;
  388                       c = in[offset];
  389                       len--;
  390                   }
  391                   if (len <= 0)    // no exponent digits
  392                       throw new NumberFormatException();
  393                   // skip leading zeros in the exponent
  394                   while (len > 10 && Character.digit(c, 10) == 0) {
  395                           offset++;
  396                           c = in[offset];
  397                           len--;
  398                   }
  399                   if (len > 10)  // too many nonzero exponent digits
  400                       throw new NumberFormatException();
  401                   // c now holds first digit of exponent
  402                   for (;; len--) {
  403                       int v;
  404                       if (c >= '0' && c <= '9') {
  405                           v = c - '0';
  406                       } else {
  407                           v = Character.digit(c, 10);
  408                           if (v < 0)            // not a digit
  409                               throw new NumberFormatException();
  410                       }
  411                       exp = exp * 10 + v;
  412                       if (len == 1)
  413                           break;               // that was final character
  414                       offset++;
  415                       c = in[offset];
  416                   }
  417                   if (negexp)                  // apply sign
  418                       exp = -exp;
  419                   // Next test is required for backwards compatibility
  420                   if ((int)exp != exp)         // overflow
  421                       throw new NumberFormatException();
  422                   break;                       // [saves a test]
  423                   }
  424               // here when no characters left
  425               if (precision == 0)              // no digits found
  426                   throw new NumberFormatException();
  427   
  428               if (dotoff >= 0) {               // had dot; set scale
  429                   scale = precision - (dotoff - cfirst);
  430                   // [cannot overflow]
  431               }
  432               if (exp != 0) {                  // had significant exponent
  433                   try {
  434                       scale = checkScale(-exp + scale); // adjust
  435                   } catch (ArithmeticException e) {
  436                       throw new NumberFormatException("Scale out of range.");
  437                   }
  438               }
  439   
  440               // Remove leading zeros from precision (digits count)
  441               int first = 0;
  442               for (; (coeff[first] == '0' || Character.digit(coeff[first], 10) == 0) &&
  443                        precision > 1;
  444                    first++)
  445                   precision--;
  446   
  447               // Set the significand ..
  448               // Copy significand to exact-sized array, with sign if
  449               // negative
  450               // Later use: BigInteger(coeff, first, precision) for
  451               //   both cases, by allowing an extra char at the front of
  452               //   coeff.
  453               char quick[];
  454               if (!isneg) {
  455                   quick = new char[precision];
  456                   System.arraycopy(coeff, first, quick, 0, precision);
  457               } else {
  458                   quick = new char[precision+1];
  459                   quick[0] = '-';
  460                   System.arraycopy(coeff, first, quick, 1, precision);
  461               }
  462               if (precision <= MAX_COMPACT_DIGITS)
  463                   intCompact = Long.parseLong(new String(quick));
  464               else
  465                   intVal = new BigInteger(quick);
  466               // System.out.println(" new: " +intVal+" ["+scale+"] "+precision);
  467           } catch (ArrayIndexOutOfBoundsException e) {
  468               throw new NumberFormatException();
  469           } catch (NegativeArraySizeException e) {
  470               throw new NumberFormatException();
  471           }
  472       }
  473   
  474       /**
  475        * Translates a character array representation of a
  476        * {@code BigDecimal} into a {@code BigDecimal}, accepting the
  477        * same sequence of characters as the {@link #BigDecimal(String)}
  478        * constructor, while allowing a sub-array to be specified and
  479        * with rounding according to the context settings.
  480        *
  481        * <p>Note that if the sequence of characters is already available
  482        * within a character array, using this constructor is faster than
  483        * converting the {@code char} array to string and using the
  484        * {@code BigDecimal(String)} constructor .
  485        *
  486        * @param  in {@code char} array that is the source of characters.
  487        * @param  offset first character in the array to inspect.
  488        * @param  len number of characters to consider..
  489        * @param  mc the context to use.
  490        * @throws ArithmeticException if the result is inexact but the
  491        *         rounding mode is {@code UNNECESSARY}.
  492        * @throws NumberFormatException if {@code in} is not a valid
  493        *         representation of a {@code BigDecimal} or the defined subarray
  494        *         is not wholly within {@code in}.
  495        * @since  1.5
  496        */
  497       public BigDecimal(char[] in, int offset, int len, MathContext mc) {
  498           this(in, offset, len);
  499           if (mc.precision > 0)
  500               roundThis(mc);
  501       }
  502   
  503       /**
  504        * Translates a character array representation of a
  505        * {@code BigDecimal} into a {@code BigDecimal}, accepting the
  506        * same sequence of characters as the {@link #BigDecimal(String)}
  507        * constructor.
  508        *
  509        * <p>Note that if the sequence of characters is already available
  510        * as a character array, using this constructor is faster than
  511        * converting the {@code char} array to string and using the
  512        * {@code BigDecimal(String)} constructor .
  513        *
  514        * @param in {@code char} array that is the source of characters.
  515        * @throws NumberFormatException if {@code in} is not a valid
  516        *         representation of a {@code BigDecimal}.
  517        * @since  1.5
  518        */
  519       public BigDecimal(char[] in) {
  520           this(in, 0, in.length);
  521       }
  522   
  523       /**
  524        * Translates a character array representation of a
  525        * {@code BigDecimal} into a {@code BigDecimal}, accepting the
  526        * same sequence of characters as the {@link #BigDecimal(String)}
  527        * constructor and with rounding according to the context
  528        * settings.
  529        *
  530        * <p>Note that if the sequence of characters is already available
  531        * as a character array, using this constructor is faster than
  532        * converting the {@code char} array to string and using the
  533        * {@code BigDecimal(String)} constructor .
  534        *
  535        * @param  in {@code char} array that is the source of characters.
  536        * @param  mc the context to use.
  537        * @throws ArithmeticException if the result is inexact but the
  538        *         rounding mode is {@code UNNECESSARY}.
  539        * @throws NumberFormatException if {@code in} is not a valid
  540        *         representation of a {@code BigDecimal}.
  541        * @since  1.5
  542        */
  543       public BigDecimal(char[] in, MathContext mc) {
  544           this(in, 0, in.length, mc);
  545       }
  546   
  547       /**
  548        * Translates the string representation of a {@code BigDecimal}
  549        * into a {@code BigDecimal}.  The string representation consists
  550        * of an optional sign, {@code '+'} (<tt> '&#92;u002B'</tt>) or
  551        * {@code '-'} (<tt>'&#92;u002D'</tt>), followed by a sequence of
  552        * zero or more decimal digits ("the integer"), optionally
  553        * followed by a fraction, optionally followed by an exponent.
  554        *
  555        * <p>The fraction consists of a decimal point followed by zero
  556        * or more decimal digits.  The string must contain at least one
  557        * digit in either the integer or the fraction.  The number formed
  558        * by the sign, the integer and the fraction is referred to as the
  559        * <i>significand</i>.
  560        *
  561        * <p>The exponent consists of the character {@code 'e'}
  562        * (<tt>'&#92;u0065'</tt>) or {@code 'E'} (<tt>'&#92;u0045'</tt>)
  563        * followed by one or more decimal digits.  The value of the
  564        * exponent must lie between -{@link Integer#MAX_VALUE} ({@link
  565        * Integer#MIN_VALUE}+1) and {@link Integer#MAX_VALUE}, inclusive.
  566        *
  567        * <p>More formally, the strings this constructor accepts are
  568        * described by the following grammar:
  569        * <blockquote>
  570        * <dl>
  571        * <dt><i>BigDecimalString:</i>
  572        * <dd><i>Sign<sub>opt</sub> Significand Exponent<sub>opt</sub></i>
  573        * <p>
  574        * <dt><i>Sign:</i>
  575        * <dd>{@code +}
  576        * <dd>{@code -}
  577        * <p>
  578        * <dt><i>Significand:</i>
  579        * <dd><i>IntegerPart</i> {@code .} <i>FractionPart<sub>opt</sub></i>
  580        * <dd>{@code .} <i>FractionPart</i>
  581        * <dd><i>IntegerPart</i>
  582        * <p>
  583        * <dt><i>IntegerPart:
  584        * <dd>Digits</i>
  585        * <p>
  586        * <dt><i>FractionPart:
  587        * <dd>Digits</i>
  588        * <p>
  589        * <dt><i>Exponent:
  590        * <dd>ExponentIndicator SignedInteger</i>
  591        * <p>
  592        * <dt><i>ExponentIndicator:</i>
  593        * <dd>{@code e}
  594        * <dd>{@code E}
  595        * <p>
  596        * <dt><i>SignedInteger:
  597        * <dd>Sign<sub>opt</sub> Digits</i>
  598        * <p>
  599        * <dt><i>Digits:
  600        * <dd>Digit
  601        * <dd>Digits Digit</i>
  602        * <p>
  603        * <dt><i>Digit:</i>
  604        * <dd>any character for which {@link Character#isDigit}
  605        * returns {@code true}, including 0, 1, 2 ...
  606        * </dl>
  607        * </blockquote>
  608        *
  609        * <p>The scale of the returned {@code BigDecimal} will be the
  610        * number of digits in the fraction, or zero if the string
  611        * contains no decimal point, subject to adjustment for any
  612        * exponent; if the string contains an exponent, the exponent is
  613        * subtracted from the scale.  The value of the resulting scale
  614        * must lie between {@code Integer.MIN_VALUE} and
  615        * {@code Integer.MAX_VALUE}, inclusive.
  616        *
  617        * <p>The character-to-digit mapping is provided by {@link
  618        * java.lang.Character#digit} set to convert to radix 10.  The
  619        * String may not contain any extraneous characters (whitespace,
  620        * for example).
  621        *
  622        * <p><b>Examples:</b><br>
  623        * The value of the returned {@code BigDecimal} is equal to
  624        * <i>significand</i> &times; 10<sup>&nbsp;<i>exponent</i></sup>.
  625        * For each string on the left, the resulting representation
  626        * [{@code BigInteger}, {@code scale}] is shown on the right.
  627        * <pre>
  628        * "0"            [0,0]
  629        * "0.00"         [0,2]
  630        * "123"          [123,0]
  631        * "-123"         [-123,0]
  632        * "1.23E3"       [123,-1]
  633        * "1.23E+3"      [123,-1]
  634        * "12.3E+7"      [123,-6]
  635        * "12.0"         [120,1]
  636        * "12.3"         [123,1]
  637        * "0.00123"      [123,5]
  638        * "-1.23E-12"    [-123,14]
  639        * "1234.5E-4"    [12345,5]
  640        * "0E+7"         [0,-7]
  641        * "-0"           [0,0]
  642        * </pre>
  643        *
  644        * <p>Note: For values other than {@code float} and
  645        * {@code double} NaN and &plusmn;Infinity, this constructor is
  646        * compatible with the values returned by {@link Float#toString}
  647        * and {@link Double#toString}.  This is generally the preferred
  648        * way to convert a {@code float} or {@code double} into a
  649        * BigDecimal, as it doesn't suffer from the unpredictability of
  650        * the {@link #BigDecimal(double)} constructor.
  651        *
  652        * @param val String representation of {@code BigDecimal}.
  653        *
  654        * @throws NumberFormatException if {@code val} is not a valid
  655        *         representation of a {@code BigDecimal}.
  656        */
  657       public BigDecimal(String val) {
  658           this(val.toCharArray(), 0, val.length());
  659       }
  660   
  661       /**
  662        * Translates the string representation of a {@code BigDecimal}
  663        * into a {@code BigDecimal}, accepting the same strings as the
  664        * {@link #BigDecimal(String)} constructor, with rounding
  665        * according to the context settings.
  666        *
  667        * @param  val string representation of a {@code BigDecimal}.
  668        * @param  mc the context to use.
  669        * @throws ArithmeticException if the result is inexact but the
  670        *         rounding mode is {@code UNNECESSARY}.
  671        * @throws NumberFormatException if {@code val} is not a valid
  672        *         representation of a BigDecimal.
  673        * @since  1.5
  674        */
  675       public BigDecimal(String val, MathContext mc) {
  676           this(val.toCharArray(), 0, val.length());
  677           if (mc.precision > 0)
  678               roundThis(mc);
  679       }
  680   
  681       /**
  682        * Translates a {@code double} into a {@code BigDecimal} which
  683        * is the exact decimal representation of the {@code double}'s
  684        * binary floating-point value.  The scale of the returned
  685        * {@code BigDecimal} is the smallest value such that
  686        * <tt>(10<sup>scale</sup> &times; val)</tt> is an integer.
  687        * <p>
  688        * <b>Notes:</b>
  689        * <ol>
  690        * <li>
  691        * The results of this constructor can be somewhat unpredictable.
  692        * One might assume that writing {@code new BigDecimal(0.1)} in
  693        * Java creates a {@code BigDecimal} which is exactly equal to
  694        * 0.1 (an unscaled value of 1, with a scale of 1), but it is
  695        * actually equal to
  696        * 0.1000000000000000055511151231257827021181583404541015625.
  697        * This is because 0.1 cannot be represented exactly as a
  698        * {@code double} (or, for that matter, as a binary fraction of
  699        * any finite length).  Thus, the value that is being passed
  700        * <i>in</i> to the constructor is not exactly equal to 0.1,
  701        * appearances notwithstanding.
  702        *
  703        * <li>
  704        * The {@code String} constructor, on the other hand, is
  705        * perfectly predictable: writing {@code new BigDecimal("0.1")}
  706        * creates a {@code BigDecimal} which is <i>exactly</i> equal to
  707        * 0.1, as one would expect.  Therefore, it is generally
  708        * recommended that the {@linkplain #BigDecimal(String)
  709        * <tt>String</tt> constructor} be used in preference to this one.
  710        *
  711        * <li>
  712        * When a {@code double} must be used as a source for a
  713        * {@code BigDecimal}, note that this constructor provides an
  714        * exact conversion; it does not give the same result as
  715        * converting the {@code double} to a {@code String} using the
  716        * {@link Double#toString(double)} method and then using the
  717        * {@link #BigDecimal(String)} constructor.  To get that result,
  718        * use the {@code static} {@link #valueOf(double)} method.
  719        * </ol>
  720        *
  721        * @param val {@code double} value to be converted to
  722        *        {@code BigDecimal}.
  723        * @throws NumberFormatException if {@code val} is infinite or NaN.
  724        */
  725       public BigDecimal(double val) {
  726           if (Double.isInfinite(val) || Double.isNaN(val))
  727               throw new NumberFormatException("Infinite or NaN");
  728   
  729           // Translate the double into sign, exponent and significand, according
  730           // to the formulae in JLS, Section 20.10.22.
  731           long valBits = Double.doubleToLongBits(val);
  732           int sign = ((valBits >> 63)==0 ? 1 : -1);
  733           int exponent = (int) ((valBits >> 52) & 0x7ffL);
  734           long significand = (exponent==0 ? (valBits & ((1L<<52) - 1)) << 1
  735                               : (valBits & ((1L<<52) - 1)) | (1L<<52));
  736           exponent -= 1075;
  737           // At this point, val == sign * significand * 2**exponent.
  738   
  739           /*
  740            * Special case zero to supress nonterminating normalization
  741            * and bogus scale calculation.
  742            */
  743           if (significand == 0) {
  744               intVal = BigInteger.ZERO;
  745               intCompact = 0;
  746               precision = 1;
  747               return;
  748           }
  749   
  750           // Normalize
  751           while((significand & 1) == 0) {    //  i.e., significand is even
  752               significand >>= 1;
  753               exponent++;
  754           }
  755   
  756           // Calculate intVal and scale
  757           intVal = BigInteger.valueOf(sign*significand);
  758           if (exponent < 0) {
  759               intVal = intVal.multiply(BigInteger.valueOf(5).pow(-exponent));
  760               scale = -exponent;
  761           } else if (exponent > 0) {
  762               intVal = intVal.multiply(BigInteger.valueOf(2).pow(exponent));
  763           }
  764           if (intVal.bitLength() <= MAX_BIGINT_BITS) {
  765               intCompact = intVal.longValue();
  766           }
  767       }
  768   
  769       /**
  770        * Translates a {@code double} into a {@code BigDecimal}, with
  771        * rounding according to the context settings.  The scale of the
  772        * {@code BigDecimal} is the smallest value such that
  773        * <tt>(10<sup>scale</sup> &times; val)</tt> is an integer.
  774        *
  775        * <p>The results of this constructor can be somewhat unpredictable
  776        * and its use is generally not recommended; see the notes under
  777        * the {@link #BigDecimal(double)} constructor.
  778        *
  779        * @param  val {@code double} value to be converted to
  780        *         {@code BigDecimal}.
  781        * @param  mc the context to use.
  782        * @throws ArithmeticException if the result is inexact but the
  783        *         RoundingMode is UNNECESSARY.
  784        * @throws NumberFormatException if {@code val} is infinite or NaN.
  785        * @since  1.5
  786        */
  787       public BigDecimal(double val, MathContext mc) {
  788           this(val);
  789           if (mc.precision > 0)
  790               roundThis(mc);
  791       }
  792   
  793       /**
  794        * Translates a {@code BigInteger} into a {@code BigDecimal}.
  795        * The scale of the {@code BigDecimal} is zero.
  796        *
  797        * @param val {@code BigInteger} value to be converted to
  798        *            {@code BigDecimal}.
  799        */
  800       public BigDecimal(BigInteger val) {
  801           intVal = val;
  802           if (val.bitLength() <= MAX_BIGINT_BITS) {
  803               intCompact = val.longValue();
  804           }
  805       }
  806   
  807       /**
  808        * Translates a {@code BigInteger} into a {@code BigDecimal}
  809        * rounding according to the context settings.  The scale of the
  810        * {@code BigDecimal} is zero.
  811        *
  812        * @param val {@code BigInteger} value to be converted to
  813        *            {@code BigDecimal}.
  814        * @param  mc the context to use.
  815        * @throws ArithmeticException if the result is inexact but the
  816        *         rounding mode is {@code UNNECESSARY}.
  817        * @since  1.5
  818        */
  819       public BigDecimal(BigInteger val, MathContext mc) {
  820           intVal = val;
  821           if (mc.precision > 0)
  822               roundThis(mc);
  823       }
  824   
  825       /**
  826        * Translates a {@code BigInteger} unscaled value and an
  827        * {@code int} scale into a {@code BigDecimal}.  The value of
  828        * the {@code BigDecimal} is
  829        * <tt>(unscaledVal &times; 10<sup>-scale</sup>)</tt>.
  830        *
  831        * @param unscaledVal unscaled value of the {@code BigDecimal}.
  832        * @param scale scale of the {@code BigDecimal}.
  833        */
  834       public BigDecimal(BigInteger unscaledVal, int scale) {
  835           // Negative scales are now allowed
  836           intVal = unscaledVal;
  837           this.scale = scale;
  838           if (unscaledVal.bitLength() <= MAX_BIGINT_BITS) {
  839               intCompact = unscaledVal.longValue();
  840           }
  841       }
  842   
  843       /**
  844        * Translates a {@code BigInteger} unscaled value and an
  845        * {@code int} scale into a {@code BigDecimal}, with rounding
  846        * according to the context settings.  The value of the
  847        * {@code BigDecimal} is <tt>(unscaledVal &times;
  848        * 10<sup>-scale</sup>)</tt>, rounded according to the
  849        * {@code precision} and rounding mode settings.
  850        *
  851        * @param  unscaledVal unscaled value of the {@code BigDecimal}.
  852        * @param  scale scale of the {@code BigDecimal}.
  853        * @param  mc the context to use.
  854        * @throws ArithmeticException if the result is inexact but the
  855        *         rounding mode is {@code UNNECESSARY}.
  856        * @since  1.5
  857        */
  858       public BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) {
  859           intVal = unscaledVal;
  860           this.scale = scale;
  861           if (mc.precision > 0)
  862               roundThis(mc);
  863       }
  864   
  865       /**
  866        * Translates an {@code int} into a {@code BigDecimal}.  The
  867        * scale of the {@code BigDecimal} is zero.
  868        *
  869        * @param val {@code int} value to be converted to
  870        *            {@code BigDecimal}.
  871        * @since  1.5
  872        */
  873       public BigDecimal(int val) {
  874           intCompact = val;
  875       }
  876   
  877       /**
  878        * Translates an {@code int} into a {@code BigDecimal}, with
  879        * rounding according to the context settings.  The scale of the
  880        * {@code BigDecimal}, before any rounding, is zero.
  881        *
  882        * @param  val {@code int} value to be converted to {@code BigDecimal}.
  883        * @param  mc the context to use.
  884        * @throws ArithmeticException if the result is inexact but the
  885        *         rounding mode is {@code UNNECESSARY}.
  886        * @since  1.5
  887        */
  888       public BigDecimal(int val, MathContext mc) {
  889           intCompact = val;
  890           if (mc.precision > 0)
  891               roundThis(mc);
  892       }
  893   
  894       /**
  895        * Translates a {@code long} into a {@code BigDecimal}.  The
  896        * scale of the {@code BigDecimal} is zero.
  897        *
  898        * @param val {@code long} value to be converted to {@code BigDecimal}.
  899        * @since  1.5
  900        */
  901       public BigDecimal(long val) {
  902           if (compactLong(val))
  903               intCompact = val;
  904           else
  905               intVal = BigInteger.valueOf(val);
  906       }
  907   
  908       /**
  909        * Translates a {@code long} into a {@code BigDecimal}, with
  910        * rounding according to the context settings.  The scale of the
  911        * {@code BigDecimal}, before any rounding, is zero.
  912        *
  913        * @param  val {@code long} value to be converted to {@code BigDecimal}.
  914        * @param  mc the context to use.
  915        * @throws ArithmeticException if the result is inexact but the
  916        *         rounding mode is {@code UNNECESSARY}.
  917        * @since  1.5
  918        */
  919       public BigDecimal(long val, MathContext mc) {
  920           if (compactLong(val))
  921               intCompact = val;
  922           else
  923               intVal = BigInteger.valueOf(val);
  924           if (mc.precision > 0)
  925               roundThis(mc);
  926       }
  927   
  928       /**
  929        * Trusted internal constructor
  930        */
  931       private BigDecimal(long val, int scale) {
  932           this.intCompact = val;
  933           this.scale = scale;
  934       }
  935   
  936       /**
  937        * Trusted internal constructor
  938        */
  939       private BigDecimal(BigInteger intVal, long val, int scale) {
  940           this.intVal = intVal;
  941           this.intCompact = val;
  942           this.scale = scale;
  943       }
  944   
  945       // Static Factory Methods
  946   
  947       /**
  948        * Translates a {@code long} unscaled value and an
  949        * {@code int} scale into a {@code BigDecimal}.  This
  950        * {@literal "static factory method"} is provided in preference to
  951        * a ({@code long}, {@code int}) constructor because it
  952        * allows for reuse of frequently used {@code BigDecimal} values..
  953        *
  954        * @param unscaledVal unscaled value of the {@code BigDecimal}.
  955        * @param scale scale of the {@code BigDecimal}.
  956        * @return a {@code BigDecimal} whose value is
  957        *         <tt>(unscaledVal &times; 10<sup>-scale</sup>)</tt>.
  958        */
  959       public static BigDecimal valueOf(long unscaledVal, int scale) {
  960           if (scale == 0 && unscaledVal >= 0 && unscaledVal <= 10) {
  961               return zeroThroughTen[(int)unscaledVal];
  962           }
  963           if (compactLong(unscaledVal))
  964               return new BigDecimal(unscaledVal, scale);
  965           return new BigDecimal(BigInteger.valueOf(unscaledVal), scale);
  966       }
  967   
  968       /**
  969        * Translates a {@code long} value into a {@code BigDecimal}
  970        * with a scale of zero.  This {@literal "static factory method"}
  971        * is provided in preference to a ({@code long}) constructor
  972        * because it allows for reuse of frequently used
  973        * {@code BigDecimal} values.
  974        *
  975        * @param val value of the {@code BigDecimal}.
  976        * @return a {@code BigDecimal} whose value is {@code val}.
  977        */
  978       public static BigDecimal valueOf(long val) {
  979           return valueOf(val, 0);
  980       }
  981   
  982       /**
  983        * Translates a {@code double} into a {@code BigDecimal}, using
  984        * the {@code double}'s canonical string representation provided
  985        * by the {@link Double#toString(double)} method.
  986        *
  987        * <p><b>Note:</b> This is generally the preferred way to convert
  988        * a {@code double} (or {@code float}) into a
  989        * {@code BigDecimal}, as the value returned is equal to that
  990        * resulting from constructing a {@code BigDecimal} from the
  991        * result of using {@link Double#toString(double)}.
  992        *
  993        * @param  val {@code double} to convert to a {@code BigDecimal}.
  994        * @return a {@code BigDecimal} whose value is equal to or approximately
  995        *         equal to the value of {@code val}.
  996        * @throws NumberFormatException if {@code val} is infinite or NaN.
  997        * @since  1.5
  998        */
  999       public static BigDecimal valueOf(double val) {
 1000           // Reminder: a zero double returns '0.0', so we cannot fastpath
 1001           // to use the constant ZERO.  This might be important enough to
 1002           // justify a factory approach, a cache, or a few private
 1003           // constants, later.
 1004           return new BigDecimal(Double.toString(val));
 1005       }
 1006   
 1007       // Arithmetic Operations
 1008       /**
 1009        * Returns a {@code BigDecimal} whose value is {@code (this +
 1010        * augend)}, and whose scale is {@code max(this.scale(),
 1011        * augend.scale())}.
 1012        *
 1013        * @param  augend value to be added to this {@code BigDecimal}.
 1014        * @return {@code this + augend}
 1015        */
 1016       public BigDecimal add(BigDecimal augend) {
 1017           BigDecimal arg[] = {this, augend};
 1018           matchScale(arg);
 1019   
 1020           long x = arg[0].intCompact;
 1021           long y = arg[1].intCompact;
 1022   
 1023           // Might be able to do a more clever check incorporating the
 1024           // inflated check into the overflow computation.
 1025           if (x != INFLATED && y != INFLATED) {
 1026               long sum = x + y;
 1027               /*
 1028                * If the sum is not an overflowed value, continue to use
 1029                * the compact representation.  if either of x or y is
 1030                * INFLATED, the sum should also be regarded as an
 1031                * overflow.  See "Hacker's Delight" section 2-12 for
 1032                * explanation of the overflow test.
 1033                */
 1034               if ( (((sum ^ x) & (sum ^ y)) >> 63) == 0L )        // not overflowed
 1035                   return BigDecimal.valueOf(sum, arg[0].scale);
 1036           }
 1037           return new BigDecimal(arg[0].inflate().intVal.add(arg[1].inflate().intVal), arg[0].scale);
 1038       }
 1039   
 1040       /**
 1041        * Returns a {@code BigDecimal} whose value is {@code (this + augend)},
 1042        * with rounding according to the context settings.
 1043        *
 1044        * If either number is zero and the precision setting is nonzero then
 1045        * the other number, rounded if necessary, is used as the result.
 1046        *
 1047        * @param  augend value to be added to this {@code BigDecimal}.
 1048        * @param  mc the context to use.
 1049        * @return {@code this + augend}, rounded as necessary.
 1050        * @throws ArithmeticException if the result is inexact but the
 1051        *         rounding mode is {@code UNNECESSARY}.
 1052        * @since  1.5
 1053        */
 1054       public BigDecimal add(BigDecimal augend, MathContext mc) {
 1055           if (mc.precision == 0)
 1056               return add(augend);
 1057           BigDecimal lhs = this;
 1058   
 1059           // Could optimize if values are compact
 1060           this.inflate();
 1061           augend.inflate();
 1062   
 1063           // If either number is zero then the other number, rounded and
 1064           // scaled if necessary, is used as the result.
 1065           {
 1066               boolean lhsIsZero = lhs.signum() == 0;
 1067               boolean augendIsZero = augend.signum() == 0;
 1068   
 1069               if (lhsIsZero || augendIsZero) {
 1070                   int preferredScale = Math.max(lhs.scale(), augend.scale());
 1071                   BigDecimal result;
 1072   
 1073                   // Could use a factory for zero instead of a new object
 1074                   if (lhsIsZero && augendIsZero)
 1075                       return new BigDecimal(BigInteger.ZERO, 0, preferredScale);
 1076   
 1077   
 1078                   result = lhsIsZero ? augend.doRound(mc) : lhs.doRound(mc);
 1079   
 1080                   if (result.scale() == preferredScale)
 1081                       return result;
 1082                   else if (result.scale() > preferredScale)
 1083                       return new BigDecimal(result.intVal, result.intCompact, result.scale).
 1084                           stripZerosToMatchScale(preferredScale);
 1085                   else { // result.scale < preferredScale
 1086                       int precisionDiff = mc.precision - result.precision();
 1087                       int scaleDiff     = preferredScale - result.scale();
 1088   
 1089                       if (precisionDiff >= scaleDiff)
 1090                           return result.setScale(preferredScale); // can achieve target scale
 1091                       else
 1092                           return result.setScale(result.scale() + precisionDiff);
 1093                   }
 1094               }
 1095           }
 1096   
 1097           long padding = (long)lhs.scale - augend.scale;
 1098           if (padding != 0) {        // scales differ; alignment needed
 1099               BigDecimal arg[] = preAlign(lhs, augend, padding, mc);
 1100               matchScale(arg);
 1101               lhs    = arg[0];
 1102               augend = arg[1];
 1103           }
 1104   
 1105           return new BigDecimal(lhs.inflate().intVal.add(augend.inflate().intVal),
 1106                                 lhs.scale).doRound(mc);
 1107       }
 1108   
 1109       /**
 1110        * Returns an array of length two, the sum of whose entries is
 1111        * equal to the rounded sum of the {@code BigDecimal} arguments.
 1112        *
 1113        * <p>If the digit positions of the arguments have a sufficient
 1114        * gap between them, the value smaller in magnitude can be
 1115        * condensed into a {@literal "sticky bit"} and the end result will
 1116        * round the same way <em>if</em> the precision of the final
 1117        * result does not include the high order digit of the small
 1118        * magnitude operand.
 1119        *
 1120        * <p>Note that while strictly speaking this is an optimization,
 1121        * it makes a much wider range of additions practical.
 1122        *
 1123        * <p>This corresponds to a pre-shift operation in a fixed
 1124        * precision floating-point adder; this method is complicated by
 1125        * variable precision of the result as determined by the
 1126        * MathContext.  A more nuanced operation could implement a
 1127        * {@literal "right shift"} on the smaller magnitude operand so
 1128        * that the number of digits of the smaller operand could be
 1129        * reduced even though the significands partially overlapped.
 1130        */
 1131       private BigDecimal[] preAlign(BigDecimal lhs, BigDecimal augend,
 1132                                     long padding, MathContext mc) {
 1133           assert padding != 0;
 1134           BigDecimal big;
 1135           BigDecimal small;
 1136   
 1137           if (padding < 0) {     // lhs is big;   augend is small
 1138               big   = lhs;
 1139               small = augend;
 1140           } else {               // lhs is small; augend is big
 1141               big   = augend;
 1142               small = lhs;
 1143           }
 1144   
 1145           /*
 1146            * This is the estimated scale of an ulp of the result; it
 1147            * assumes that the result doesn't have a carry-out on a true
 1148            * add (e.g. 999 + 1 => 1000) or any subtractive cancellation
 1149            * on borrowing (e.g. 100 - 1.2 => 98.8)
 1150            */
 1151           long estResultUlpScale = (long)big.scale - big.precision() + mc.precision;
 1152   
 1153           /*
 1154            * The low-order digit position of big is big.scale().  This
 1155            * is true regardless of whether big has a positive or
 1156            * negative scale.  The high-order digit position of small is
 1157            * small.scale - (small.precision() - 1).  To do the full
 1158            * condensation, the digit positions of big and small must be
 1159            * disjoint *and* the digit positions of small should not be
 1160            * directly visible in the result.
 1161            */
 1162           long smallHighDigitPos = (long)small.scale - small.precision() + 1;
 1163           if (smallHighDigitPos > big.scale + 2 &&         // big and small disjoint
 1164               smallHighDigitPos > estResultUlpScale + 2) { // small digits not visible
 1165               small = BigDecimal.valueOf(small.signum(),
 1166                                          this.checkScale(Math.max(big.scale, estResultUlpScale) + 3));
 1167           }
 1168   
 1169           // Since addition is symmetric, preserving input order in
 1170           // returned operands doesn't matter
 1171           BigDecimal[] result = {big, small};
 1172           return result;
 1173       }
 1174   
 1175       /**
 1176        * Returns a {@code BigDecimal} whose value is {@code (this -
 1177        * subtrahend)}, and whose scale is {@code max(this.scale(),
 1178        * subtrahend.scale())}.
 1179        *
 1180        * @param  subtrahend value to be subtracted from this {@code BigDecimal}.
 1181        * @return {@code this - subtrahend}
 1182        */
 1183       public BigDecimal subtract(BigDecimal subtrahend) {
 1184           BigDecimal arg[] = {this, subtrahend};
 1185           matchScale(arg);
 1186   
 1187           long x = arg[0].intCompact;
 1188           long y = arg[1].intCompact;
 1189   
 1190           // Might be able to do a more clever check incorporating the
 1191           // inflated check into the overflow computation.
 1192           if (x != INFLATED && y != INFLATED) {
 1193               long difference = x - y;
 1194               /*
 1195                * If the difference is not an overflowed value, continue
 1196                * to use the compact representation.  if either of x or y
 1197                * is INFLATED, the difference should also be regarded as
 1198                * an overflow.  See "Hacker's Delight" section 2-12 for
 1199                * explanation of the overflow test.
 1200                */
 1201               if ( ((x ^ y) & (difference ^ x) ) >> 63 == 0L )    // not overflowed
 1202                   return BigDecimal.valueOf(difference, arg[0].scale);
 1203           }
 1204           return new BigDecimal(arg[0].inflate().intVal.subtract(arg[1].inflate().intVal),
 1205                                 arg[0].scale);
 1206       }
 1207   
 1208       /**
 1209        * Returns a {@code BigDecimal} whose value is {@code (this - subtrahend)},
 1210        * with rounding according to the context settings.
 1211        *
 1212        * If {@code subtrahend} is zero then this, rounded if necessary, is used as the
 1213        * result.  If this is zero then the result is {@code subtrahend.negate(mc)}.
 1214        *
 1215        * @param  subtrahend value to be subtracted from this {@code BigDecimal}.
 1216        * @param  mc the context to use.
 1217        * @return {@code this - subtrahend}, rounded as necessary.
 1218        * @throws ArithmeticException if the result is inexact but the
 1219        *         rounding mode is {@code UNNECESSARY}.
 1220        * @since  1.5
 1221        */
 1222       public BigDecimal subtract(BigDecimal subtrahend, MathContext mc) {
 1223           if (mc.precision == 0)
 1224               return subtract(subtrahend);
 1225           // share the special rounding code in add()
 1226           this.inflate();
 1227           subtrahend.inflate();
 1228           BigDecimal rhs = new BigDecimal(subtrahend.intVal.negate(), subtrahend.scale);
 1229           rhs.precision = subtrahend.precision;
 1230           return add(rhs, mc);
 1231       }
 1232   
 1233       /**
 1234        * Returns a {@code BigDecimal} whose value is <tt>(this &times;
 1235        * multiplicand)</tt>, and whose scale is {@code (this.scale() +
 1236        * multiplicand.scale())}.
 1237        *
 1238        * @param  multiplicand value to be multiplied by this {@code BigDecimal}.
 1239        * @return {@code this * multiplicand}
 1240        */
 1241       public BigDecimal multiply(BigDecimal multiplicand) {
 1242           long x = this.intCompact;
 1243           long y = multiplicand.intCompact;
 1244           int productScale = checkScale((long)scale+multiplicand.scale);
 1245   
 1246           // Might be able to do a more clever check incorporating the
 1247           // inflated check into the overflow computation.
 1248           if (x != INFLATED && y != INFLATED) {
 1249               /*
 1250                * If the product is not an overflowed value, continue
 1251                * to use the compact representation.  if either of x or y
 1252                * is INFLATED, the product should also be regarded as
 1253                * an overflow.  See "Hacker's Delight" section 2-12 for
 1254                * explanation of the overflow test.
 1255                */
 1256               long product = x * y;
 1257               if ( !(y != 0L && product/y != x)  )        // not overflowed
 1258                   return BigDecimal.valueOf(product, productScale);
 1259           }
 1260   
 1261           BigDecimal result = new BigDecimal(this.inflate().intVal.multiply(multiplicand.inflate().intVal), productScale);
 1262           return result;
 1263       }
 1264   
 1265       /**
 1266        * Returns a {@code BigDecimal} whose value is <tt>(this &times;
 1267        * multiplicand)</tt>, with rounding according to the context settings.
 1268        *
 1269        * @param  multiplicand value to be multiplied by this {@code BigDecimal}.
 1270        * @param  mc the context to use.
 1271        * @return {@code this * multiplicand}, rounded as necessary.
 1272        * @throws ArithmeticException if the result is inexact but the
 1273        *         rounding mode is {@code UNNECESSARY}.
 1274        * @since  1.5
 1275        */
 1276       public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) {
 1277           if (mc.precision == 0)
 1278               return multiply(multiplicand);
 1279           BigDecimal lhs = this;
 1280           return lhs.inflate().multiply(multiplicand.inflate()).doRound(mc);
 1281       }
 1282   
 1283       /**
 1284        * Returns a {@code BigDecimal} whose value is {@code (this /
 1285        * divisor)}, and whose scale is as specified.  If rounding must
 1286        * be performed to generate a result with the specified scale, the
 1287        * specified rounding mode is applied.
 1288        *
 1289        * <p>The new {@link #divide(BigDecimal, int, RoundingMode)} method
 1290        * should be used in preference to this legacy method.
 1291        *
 1292        * @param  divisor value by which this {@code BigDecimal} is to be divided.
 1293        * @param  scale scale of the {@code BigDecimal} quotient to be returned.
 1294        * @param  roundingMode rounding mode to apply.
 1295        * @return {@code this / divisor}
 1296        * @throws ArithmeticException if {@code divisor} is zero,
 1297        *         {@code roundingMode==ROUND_UNNECESSARY} and
 1298        *         the specified scale is insufficient to represent the result
 1299        *         of the division exactly.
 1300        * @throws IllegalArgumentException if {@code roundingMode} does not
 1301        *         represent a valid rounding mode.
 1302        * @see    #ROUND_UP
 1303        * @see    #ROUND_DOWN
 1304        * @see    #ROUND_CEILING
 1305        * @see    #ROUND_FLOOR
 1306        * @see    #ROUND_HALF_UP
 1307        * @see    #ROUND_HALF_DOWN
 1308        * @see    #ROUND_HALF_EVEN
 1309        * @see    #ROUND_UNNECESSARY
 1310        */
 1311       public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) {
 1312           /*
 1313            * IMPLEMENTATION NOTE: This method *must* return a new object
 1314            * since dropDigits uses divide to generate a value whose
 1315            * scale is then modified.
 1316            */
 1317           if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
 1318               throw new IllegalArgumentException("Invalid rounding mode");
 1319           /*
 1320            * Rescale dividend or divisor (whichever can be "upscaled" to
 1321            * produce correctly scaled quotient).
 1322            * Take care to detect out-of-range scales
 1323            */
 1324           BigDecimal dividend;
 1325           if (checkScale((long)scale + divisor.scale) >= this.scale) {
 1326               dividend = this.setScale(scale + divisor.scale);
 1327           } else {
 1328               dividend = this;
 1329               divisor = divisor.setScale(checkScale((long)this.scale - scale));
 1330           }
 1331   
 1332           boolean compact = dividend.intCompact != INFLATED && divisor.intCompact != INFLATED;
 1333           long div = INFLATED;
 1334           long rem = INFLATED;;
 1335           BigInteger q=null, r=null;
 1336   
 1337           if (compact) {
 1338               div = dividend.intCompact / divisor.intCompact;
 1339               rem = dividend.intCompact % divisor.intCompact;
 1340           } else {
 1341               // Do the division and return result if it's exact.
 1342               BigInteger i[] = dividend.inflate().intVal.divideAndRemainder(divisor.inflate().intVal);
 1343               q = i[0];
 1344               r = i[1];
 1345           }
 1346   
 1347           // Check for exact result
 1348           if (compact) {
 1349               if (rem == 0)
 1350                   return new BigDecimal(div, scale);
 1351           } else {
 1352               if (r.signum() == 0)
 1353                   return new BigDecimal(q, scale);
 1354           }
 1355   
 1356           if (roundingMode == ROUND_UNNECESSARY)      // Rounding prohibited
 1357               throw new ArithmeticException("Rounding necessary");
 1358   
 1359           /* Round as appropriate */
 1360           int signum = dividend.signum() * divisor.signum(); // Sign of result
 1361           boolean increment;
 1362           if (roundingMode == ROUND_UP) {             // Away from zero
 1363               increment = true;
 1364           } else if (roundingMode == ROUND_DOWN) {    // Towards zero
 1365               increment = false;
 1366           } else if (roundingMode == ROUND_CEILING) { // Towards +infinity
 1367               increment = (signum > 0);
 1368           } else if (roundingMode == ROUND_FLOOR) {   // Towards -infinity
 1369               increment = (signum < 0);
 1370           } else { // Remaining modes based on nearest-neighbor determination
 1371               int cmpFracHalf;
 1372               if (compact) {
 1373                    cmpFracHalf = longCompareTo(Math.abs(2*rem), Math.abs(divisor.intCompact));
 1374               } else {
 1375                   // add(r) here is faster than multiply(2) or shiftLeft(1)
 1376                   cmpFracHalf= r.add(r).abs().compareTo(divisor.intVal.abs());
 1377               }
 1378               if (cmpFracHalf < 0) {         // We're closer to higher digit
 1379                   increment = false;
 1380               } else if (cmpFracHalf > 0) {  // We're closer to lower digit
 1381                   increment = true;
 1382               } else {                       // We're dead-center
 1383                   if (roundingMode == ROUND_HALF_UP)
 1384                       increment = true;
 1385                   else if (roundingMode == ROUND_HALF_DOWN)
 1386                       increment = false;
 1387                   else { // roundingMode == ROUND_HALF_EVEN
 1388                       if (compact)
 1389                           increment = (div & 1L) != 0L;
 1390                       else
 1391                           increment = q.testBit(0);   // true iff q is odd
 1392                   }
 1393               }
 1394           }
 1395   
 1396           if (compact) {
 1397               if (increment)
 1398                   div += signum; // guaranteed not to overflow
 1399               return new BigDecimal(div, scale);
 1400           } else {
 1401               return (increment
 1402                       ? new BigDecimal(q.add(BigInteger.valueOf(signum)), scale)
 1403                       : new BigDecimal(q, scale));
 1404           }
 1405       }
 1406   
 1407       /**
 1408        * Returns a {@code BigDecimal} whose value is {@code (this /
 1409        * divisor)}, and whose scale is as specified.  If rounding must
 1410        * be performed to generate a result with the specified scale, the
 1411        * specified rounding mode is applied.
 1412        *
 1413        * @param  divisor value by which this {@code BigDecimal} is to be divided.
 1414        * @param  scale scale of the {@code BigDecimal} quotient to be returned.
 1415        * @param  roundingMode rounding mode to apply.
 1416        * @return {@code this / divisor}
 1417        * @throws ArithmeticException if {@code divisor} is zero,
 1418        *         {@code roundingMode==RoundingMode.UNNECESSARY} and
 1419        *         the specified scale is insufficient to represent the result
 1420        *         of the division exactly.
 1421        * @since 1.5
 1422        */
 1423       public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) {
 1424           return divide(divisor, scale, roundingMode.oldMode);
 1425       }
 1426   
 1427       /**
 1428        * Returns a {@code BigDecimal} whose value is {@code (this /
 1429        * divisor)}, and whose scale is {@code this.scale()}.  If
 1430        * rounding must be performed to generate a result with the given
 1431        * scale, the specified rounding mode is applied.
 1432        *
 1433        * <p>The new {@link #divide(BigDecimal, RoundingMode)} method
 1434        * should be used in preference to this legacy method.
 1435        *
 1436        * @param  divisor value by which this {@code BigDecimal} is to be divided.
 1437        * @param  roundingMode rounding mode to apply.
 1438        * @return {@code this / divisor}
 1439        * @throws ArithmeticException if {@code divisor==0}, or
 1440        *         {@code roundingMode==ROUND_UNNECESSARY} and
 1441        *         {@code this.scale()} is insufficient to represent the result
 1442        *         of the division exactly.
 1443        * @throws IllegalArgumentException if {@code roundingMode} does not
 1444        *         represent a valid rounding mode.
 1445        * @see    #ROUND_UP
 1446        * @see    #ROUND_DOWN
 1447        * @see    #ROUND_CEILING
 1448        * @see    #ROUND_FLOOR
 1449        * @see    #ROUND_HALF_UP
 1450        * @see    #ROUND_HALF_DOWN
 1451        * @see    #ROUND_HALF_EVEN
 1452        * @see    #ROUND_UNNECESSARY
 1453        */
 1454       public BigDecimal divide(BigDecimal divisor, int roundingMode) {
 1455               return this.divide(divisor, scale, roundingMode);
 1456       }
 1457   
 1458       /**
 1459        * Returns a {@code BigDecimal} whose value is {@code (this /
 1460        * divisor)}, and whose scale is {@code this.scale()}.  If
 1461        * rounding must be performed to generate a result with the given
 1462        * scale, the specified rounding mode is applied.
 1463        *
 1464        * @param  divisor value by which this {@code BigDecimal} is to be divided.
 1465        * @param  roundingMode rounding mode to apply.
 1466        * @return {@code this / divisor}
 1467        * @throws ArithmeticException if {@code divisor==0}, or
 1468        *         {@code roundingMode==RoundingMode.UNNECESSARY} and
 1469        *         {@code this.scale()} is insufficient to represent the result
 1470        *         of the division exactly.
 1471        * @since 1.5
 1472        */
 1473       public BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode) {
 1474           return this.divide(divisor, scale, roundingMode.oldMode);
 1475       }
 1476   
 1477       /**
 1478        * Returns a {@code BigDecimal} whose value is {@code (this /
 1479        * divisor)}, and whose preferred scale is {@code (this.scale() -
 1480        * divisor.scale())}; if the exact quotient cannot be
 1481        * represented (because it has a non-terminating decimal
 1482        * expansion) an {@code ArithmeticException} is thrown.
 1483        *
 1484        * @param  divisor value by which this {@code BigDecimal} is to be divided.
 1485        * @throws ArithmeticException if the exact quotient does not have a
 1486        *         terminating decimal expansion
 1487        * @return {@code this / divisor}
 1488        * @since 1.5
 1489        * @author Joseph D. Darcy
 1490        */
 1491       public BigDecimal divide(BigDecimal divisor) {
 1492           /*
 1493            * Handle zero cases first.
 1494            */
 1495           if (divisor.signum() == 0) {   // x/0
 1496               if (this.signum() == 0)    // 0/0
 1497                   throw new ArithmeticException("Division undefined");  // NaN
 1498               throw new ArithmeticException("Division by zero");
 1499           }
 1500   
 1501           // Calculate preferred scale
 1502           int preferredScale = (int)Math.max(Math.min((long)this.scale() - divisor.scale(),
 1503                                                       Integer.MAX_VALUE), Integer.MIN_VALUE);
 1504           if (this.signum() == 0)        // 0/y
 1505               return new BigDecimal(0, preferredScale);
 1506           else {
 1507               this.inflate();
 1508               divisor.inflate();
 1509               /*
 1510                * If the quotient this/divisor has a terminating decimal
 1511                * expansion, the expansion can have no more than
 1512                * (a.precision() + ceil(10*b.precision)/3) digits.
 1513                * Therefore, create a MathContext object with this
 1514                * precision and do a divide with the UNNECESSARY rounding
 1515                * mode.
 1516                */
 1517               MathContext mc = new MathContext( (int)Math.min(this.precision() +
 1518                                                               (long)Math.ceil(10.0*divisor.precision()/3.0),
 1519                                                               Integer.MAX_VALUE),
 1520                                                 RoundingMode.UNNECESSARY);
 1521               BigDecimal quotient;
 1522               try {
 1523                   quotient = this.divide(divisor, mc);
 1524               } catch (ArithmeticException e) {
 1525                   throw new ArithmeticException("Non-terminating decimal expansion; " +
 1526                                                 "no exact representable decimal result.");
 1527               }
 1528   
 1529               int quotientScale = quotient.scale();
 1530   
 1531               // divide(BigDecimal, mc) tries to adjust the quotient to
 1532               // the desired one by removing trailing zeros; since the
 1533               // exact divide method does not have an explicit digit
 1534               // limit, we can add zeros too.
 1535   
 1536               if (preferredScale > quotientScale)
 1537                   return quotient.setScale(preferredScale);
 1538   
 1539               return quotient;
 1540           }
 1541       }
 1542   
 1543       /**
 1544        * Returns a {@code BigDecimal} whose value is {@code (this /
 1545        * divisor)}, with rounding according to the context settings.
 1546        *
 1547        * @param  divisor value by which this {@code BigDecimal} is to be divided.
 1548        * @param  mc the context to use.
 1549        * @return {@code this / divisor}, rounded as necessary.
 1550        * @throws ArithmeticException if the result is inexact but the
 1551        *         rounding mode is {@code UNNECESSARY} or
 1552        *         {@code mc.precision == 0} and the quotient has a
 1553        *         non-terminating decimal expansion.
 1554        * @since  1.5
 1555        */
 1556       public BigDecimal divide(BigDecimal divisor, MathContext mc) {
 1557           if (mc.precision == 0)
 1558               return divide(divisor);
 1559           BigDecimal lhs = this.inflate();     // left-hand-side
 1560           BigDecimal rhs = divisor.inflate();  // right-hand-side
 1561           BigDecimal result;                   // work
 1562   
 1563           long preferredScale = (long)lhs.scale() - rhs.scale();
 1564   
 1565           // Now calculate the answer.  We use the existing
 1566           // divide-and-round method, but as this rounds to scale we have
 1567           // to normalize the values here to achieve the desired result.
 1568           // For x/y we first handle y=0 and x=0, and then normalize x and
 1569           // y to give x' and y' with the following constraints:
 1570           //   (a) 0.1 <= x' < 1
 1571           //   (b)  x' <= y' < 10*x'
 1572           // Dividing x'/y' with the required scale set to mc.precision then
 1573           // will give a result in the range 0.1 to 1 rounded to exactly
 1574           // the right number of digits (except in the case of a result of
 1575           // 1.000... which can arise when x=y, or when rounding overflows
 1576           // The 1.000... case will reduce properly to 1.
 1577           if (rhs.signum() == 0) {      // x/0
 1578               if (lhs.signum() == 0)    // 0/0
 1579                   throw new ArithmeticException("Division undefined");  // NaN
 1580               throw new ArithmeticException("Division by zero");
 1581           }
 1582           if (lhs.signum() == 0)        // 0/y
 1583               return new BigDecimal(BigInteger.ZERO,
 1584                                     (int)Math.max(Math.min(preferredScale,
 1585                                                            Integer.MAX_VALUE),
 1586                                                   Integer.MIN_VALUE));
 1587   
 1588           BigDecimal xprime = new BigDecimal(lhs.intVal.abs(), lhs.precision());
 1589           BigDecimal yprime = new BigDecimal(rhs.intVal.abs(), rhs.precision());
 1590           // xprime and yprime are now both in range 0.1 through 0.999...
 1591           if (mc.roundingMode == RoundingMode.CEILING ||
 1592               mc.roundingMode == RoundingMode.FLOOR) {
 1593               // The floor (round toward negative infinity) and ceil
 1594               // (round toward positive infinity) rounding modes are not
 1595               // invariant under a sign flip.  If xprime/yprime has a
 1596               // different sign than lhs/rhs, the rounding mode must be
 1597               // changed.
 1598               if ((xprime.signum() != lhs.signum()) ^
 1599                   (yprime.signum() != rhs.signum())) {
 1600                   mc = new MathContext(mc.precision,
 1601                                        (mc.roundingMode==RoundingMode.CEILING)?
 1602                                        RoundingMode.FLOOR:RoundingMode.CEILING);
 1603               }
 1604           }
 1605   
 1606           if (xprime.compareTo(yprime) > 0)    // satisfy constraint (b)
 1607             yprime.scale -= 1;                 // [that is, yprime *= 10]
 1608           result = xprime.divide(yprime, mc.precision, mc.roundingMode.oldMode);
 1609           // correct the scale of the result...
 1610           result.scale = checkScale((long)yprime.scale - xprime.scale
 1611               - (rhs.scale - lhs.scale) + mc.precision);
 1612           // apply the sign
 1613           if (lhs.signum() != rhs.signum())
 1614               result = result.negate();
 1615           // doRound, here, only affects 1000000000 case.
 1616           result = result.doRound(mc);
 1617   
 1618           if (result.multiply(divisor).compareTo(this) == 0) {
 1619               // Apply preferred scale rules for exact quotients
 1620               return result.stripZerosToMatchScale(preferredScale);
 1621           }
 1622           else {
 1623               return result;
 1624           }
 1625       }
 1626   
 1627       /**
 1628        * Returns a {@code BigDecimal} whose value is the integer part
 1629        * of the quotient {@code (this / divisor)} rounded down.  The
 1630        * preferred scale of the result is {@code (this.scale() -
 1631        * divisor.scale())}.
 1632        *
 1633        * @param  divisor value by which this {@code BigDecimal} is to be divided.
 1634        * @return The integer part of {@code this / divisor}.
 1635        * @throws ArithmeticException if {@code divisor==0}
 1636        * @since  1.5
 1637        */
 1638       public BigDecimal divideToIntegralValue(BigDecimal divisor) {
 1639           // Calculate preferred scale
 1640           int preferredScale = (int)Math.max(Math.min((long)this.scale() - divisor.scale(),
 1641                                                       Integer.MAX_VALUE), Integer.MIN_VALUE);
 1642           this.inflate();
 1643           divisor.inflate();
 1644           if (this.abs().compareTo(divisor.abs()) < 0) {
 1645               // much faster when this << divisor
 1646               return BigDecimal.valueOf(0, preferredScale);
 1647           }
 1648   
 1649           if(this.signum() == 0 && divisor.signum() != 0)
 1650               return this.setScale(preferredScale);
 1651   
 1652           // Perform a divide with enough digits to round to a correct
 1653           // integer value; then remove any fractional digits
 1654   
 1655           int maxDigits = (int)Math.min(this.precision() +
 1656                                         (long)Math.ceil(10.0*divisor.precision()/3.0) +
 1657                                         Math.abs((long)this.scale() - divisor.scale()) + 2,
 1658                                         Integer.MAX_VALUE);
 1659   
 1660           BigDecimal quotient = this.divide(divisor, new MathContext(maxDigits,
 1661                                                                      RoundingMode.DOWN));
 1662           if (quotient.scale > 0) {
 1663               quotient = quotient.setScale(0, RoundingMode.DOWN).
 1664                   stripZerosToMatchScale(preferredScale);
 1665           }
 1666   
 1667           if (quotient.scale < preferredScale) {
 1668               // pad with zeros if necessary
 1669               quotient = quotient.setScale(preferredScale);
 1670           }
 1671   
 1672           return quotient;
 1673       }
 1674   
 1675       /**
 1676        * Returns a {@code BigDecimal} whose value is the integer part
 1677        * of {@code (this / divisor)}.  Since the integer part of the
 1678        * exact quotient does not depend on the rounding mode, the
 1679        * rounding mode does not affect the values returned by this
 1680        * method.  The preferred scale of the result is
 1681        * {@code (this.scale() - divisor.scale())}.  An
 1682        * {@code ArithmeticException} is thrown if the integer part of
 1683        * the exact quotient needs more than {@code mc.precision}
 1684        * digits.
 1685        *
 1686        * @param  divisor value by which this {@code BigDecimal} is to be divided.
 1687        * @param  mc the context to use.
 1688        * @return The integer part of {@code this / divisor}.
 1689        * @throws ArithmeticException if {@code divisor==0}
 1690        * @throws ArithmeticException if {@code mc.precision} {@literal >} 0 and the result
 1691        *         requires a precision of more than {@code mc.precision} digits.
 1692        * @since  1.5
 1693        * @author Joseph D. Darcy
 1694        */
 1695       public BigDecimal divideToIntegralValue(BigDecimal divisor, MathContext mc) {
 1696           if (mc.precision == 0 ||                        // exact result
 1697               (this.abs().compareTo(divisor.abs()) < 0) ) // zero result
 1698               return divideToIntegralValue(divisor);
 1699   
 1700           // Calculate preferred scale
 1701           int preferredScale = (int)Math.max(Math.min((long)this.scale() - divisor.scale(),
 1702                                                       Integer.MAX_VALUE), Integer.MIN_VALUE);
 1703   
 1704           /*
 1705            * Perform a normal divide to mc.precision digits.  If the
 1706            * remainder has absolute value less than the divisor, the
 1707            * integer portion of the quotient fits into mc.precision
 1708            * digits.  Next, remove any fractional digits from the
 1709            * quotient and adjust the scale to the preferred value.
 1710            */
 1711           BigDecimal result = this.divide(divisor, new MathContext(mc.precision,
 1712                                                                    RoundingMode.DOWN));
 1713           int resultScale = result.scale();
 1714   
 1715           if (result.scale() < 0) {
 1716               /*
 1717                * Result is an integer. See if quotient represents the
 1718                * full integer portion of the exact quotient; if it does,
 1719                * the computed remainder will be less than the divisor.
 1720                */
 1721               BigDecimal product = result.multiply(divisor);
 1722               // If the quotient is the full integer value,
 1723               // |dividend-product| < |divisor|.
 1724               if (this.subtract(product).abs().compareTo(divisor.abs()) >= 0) {
 1725                   throw new ArithmeticException("Division impossible");
 1726               }
 1727           } else if (result.scale() > 0) {
 1728               /*
 1729                * Integer portion of quotient will fit into precision
 1730                * digits; recompute quotient to scale 0 to avoid double
 1731                * rounding and then try to adjust, if necessary.
 1732                */
 1733               result = result.setScale(0, RoundingMode.DOWN);
 1734           }
 1735           // else result.scale() == 0;
 1736   
 1737           int precisionDiff;
 1738           if ((preferredScale > result.scale()) &&
 1739               (precisionDiff = mc.precision - result.precision()) > 0  ) {
 1740               return result.setScale(result.scale() +
 1741                                      Math.min(precisionDiff, preferredScale - result.scale) );
 1742           } else
 1743               return result.stripZerosToMatchScale(preferredScale);
 1744       }
 1745   
 1746       /**
 1747        * Returns a {@code BigDecimal} whose value is {@code (this % divisor)}.
 1748        *
 1749        * <p>The remainder is given by
 1750        * {@code this.subtract(this.divideToIntegralValue(divisor).multiply(divisor))}.
 1751        * Note that this is not the modulo operation (the result can be
 1752        * negative).
 1753        *
 1754        * @param  divisor value by which this {@code BigDecimal} is to be divided.
 1755        * @return {@code this % divisor}.
 1756        * @throws ArithmeticException if {@code divisor==0}
 1757        * @since  1.5
 1758        */
 1759       public BigDecimal remainder(BigDecimal divisor) {
 1760           BigDecimal divrem[] = this.divideAndRemainder(divisor);
 1761           return divrem[1];
 1762       }
 1763   
 1764   
 1765       /**
 1766        * Returns a {@code BigDecimal} whose value is {@code (this %
 1767        * divisor)}, with rounding according to the context settings.
 1768        * The {@code MathContext} settings affect the implicit divide
 1769        * used to compute the remainder.  The remainder computation
 1770        * itself is by definition exact.  Therefore, the remainder may
 1771        * contain more than {@code mc.getPrecision()} digits.
 1772        *
 1773        * <p>The remainder is given by
 1774        * {@code this.subtract(this.divideToIntegralValue(divisor,
 1775        * mc).multiply(divisor))}.  Note that this is not the modulo
 1776        * operation (the result can be negative).
 1777        *
 1778        * @param  divisor value by which this {@code BigDecimal} is to be divided.
 1779        * @param  mc the context to use.
 1780        * @return {@code this % divisor}, rounded as necessary.
 1781        * @throws ArithmeticException if {@code divisor==0}
 1782        * @throws ArithmeticException if the result is inexact but the
 1783        *         rounding mode is {@code UNNECESSARY}, or {@code mc.precision}
 1784        *         {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would
 1785        *         require a precision of more than {@code mc.precision} digits.
 1786        * @see    #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
 1787        * @since  1.5
 1788        */
 1789       public BigDecimal remainder(BigDecimal divisor, MathContext mc) {
 1790           BigDecimal divrem[] = this.divideAndRemainder(divisor, mc);
 1791           return divrem[1];
 1792       }
 1793   
 1794       /**
 1795        * Returns a two-element {@code BigDecimal} array containing the
 1796        * result of {@code divideToIntegralValue} followed by the result of
 1797        * {@code remainder} on the two operands.
 1798        *
 1799        * <p>Note that if both the integer quotient and remainder are
 1800        * needed, this method is faster than using the
 1801        * {@code divideToIntegralValue} and {@code remainder} methods
 1802        * separately because the division need only be carried out once.
 1803        *
 1804        * @param  divisor value by which this {@code BigDecimal} is to be divided,
 1805        *         and the remainder computed.
 1806        * @return a two element {@code BigDecimal} array: the quotient
 1807        *         (the result of {@code divideToIntegralValue}) is the initial element
 1808        *         and the remainder is the final element.
 1809        * @throws ArithmeticException if {@code divisor==0}
 1810        * @see    #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
 1811        * @see    #remainder(java.math.BigDecimal, java.math.MathContext)
 1812        * @since  1.5
 1813        */
 1814       public BigDecimal[] divideAndRemainder(BigDecimal divisor) {
 1815           // we use the identity  x = i * y + r to determine r
 1816           BigDecimal[] result = new BigDecimal[2];
 1817   
 1818           result[0] = this.divideToIntegralValue(divisor);
 1819           result[1] = this.subtract(result[0].multiply(divisor));
 1820           return result;
 1821       }
 1822   
 1823       /**
 1824        * Returns a two-element {@code BigDecimal} array containing the
 1825        * result of {@code divideToIntegralValue} followed by the result of
 1826        * {@code remainder} on the two operands calculated with rounding
 1827        * according to the context settings.
 1828        *
 1829        * <p>Note that if both the integer quotient and remainder are
 1830        * needed, this method is faster than using the
 1831        * {@code divideToIntegralValue} and {@code remainder} methods
 1832        * separately because the division need only be carried out once.
 1833        *
 1834        * @param  divisor value by which this {@code BigDecimal} is to be divided,
 1835        *         and the remainder computed.
 1836        * @param  mc the context to use.
 1837        * @return a two element {@code BigDecimal} array: the quotient
 1838        *         (the result of {@code divideToIntegralValue}) is the
 1839        *         initial element and the remainder is the final element.
 1840        * @throws ArithmeticException if {@code divisor==0}
 1841        * @throws ArithmeticException if the result is inexact but the
 1842        *         rounding mode is {@code UNNECESSARY}, or {@code mc.precision}
 1843        *         {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would
 1844        *         require a precision of more than {@code mc.precision} digits.
 1845        * @see    #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
 1846        * @see    #remainder(java.math.BigDecimal, java.math.MathContext)
 1847        * @since  1.5
 1848        */
 1849       public BigDecimal[] divideAndRemainder(BigDecimal divisor, MathContext mc) {
 1850           if (mc.precision == 0)
 1851               return divideAndRemainder(divisor);
 1852   
 1853           BigDecimal[] result = new BigDecimal[2];
 1854           BigDecimal lhs = this;
 1855   
 1856           result[0] = lhs.divideToIntegralValue(divisor, mc);
 1857           result[1] = lhs.subtract(result[0].multiply(divisor));
 1858           return result;
 1859       }
 1860   
 1861       /**
 1862        * Returns a {@code BigDecimal} whose value is
 1863        * <tt>(this<sup>n</sup>)</tt>, The power is computed exactly, to
 1864        * unlimited precision.
 1865        *
 1866        * <p>The parameter {@code n} must be in the range 0 through
 1867        * 999999999, inclusive.  {@code ZERO.pow(0)} returns {@link
 1868        * #ONE}.
 1869        *
 1870        * Note that future releases may expand the allowable exponent
 1871        * range of this method.
 1872        *
 1873        * @param  n power to raise this {@code BigDecimal} to.
 1874        * @return <tt>this<sup>n</sup></tt>
 1875        * @throws ArithmeticException if {@code n} is out of range.
 1876        * @since  1.5
 1877        */
 1878       public BigDecimal pow(int n) {
 1879           if (n < 0 || n > 999999999)
 1880               throw new ArithmeticException("Invalid operation");
 1881           // No need to calculate pow(n) if result will over/underflow.
 1882           // Don't attempt to support "supernormal" numbers.
 1883           int newScale = checkScale((long)scale * n);
 1884           this.inflate();
 1885           return new BigDecimal(intVal.pow(n), newScale);
 1886       }
 1887   
 1888   
 1889       /**
 1890        * Returns a {@code BigDecimal} whose value is
 1891        * <tt>(this<sup>n</sup>)</tt>.  The current implementation uses
 1892        * the core algorithm defined in ANSI standard X3.274-1996 with
 1893        * rounding according to the context settings.  In general, the
 1894        * returned numerical value is within two ulps of the exact
 1895        * numerical value for the chosen precision.  Note that future
 1896        * releases may use a different algorithm with a decreased
 1897        * allowable error bound and increased allowable exponent range.
 1898        *
 1899        * <p>The X3.274-1996 algorithm is:
 1900        *
 1901        * <ul>
 1902        * <li> An {@code ArithmeticException} exception is thrown if
 1903        *  <ul>
 1904        *    <li>{@code abs(n) > 999999999}
 1905        *    <li>{@code mc.precision == 0} and {@code n < 0}
 1906        *    <li>{@code mc.precision > 0} and {@code n} has more than
 1907        *    {@code mc.precision} decimal digits
 1908        *  </ul>
 1909        *
 1910        * <li> if {@code n} is zero, {@link #ONE} is returned even if
 1911        * {@code this} is zero, otherwise
 1912        * <ul>
 1913        *   <li> if {@code n} is positive, the result is calculated via
 1914        *   the repeated squaring technique into a single accumulator.
 1915        *   The individual multiplications with the accumulator use the
 1916        *   same math context settings as in {@code mc} except for a
 1917        *   precision increased to {@code mc.precision + elength + 1}
 1918        *   where {@code elength} is the number of decimal digits in
 1919        *   {@code n}.
 1920        *
 1921        *   <li> if {@code n} is negative, the result is calculated as if
 1922        *   {@code n} were positive; this value is then divided into one
 1923        *   using the working precision specified above.
 1924        *
 1925        *   <li> The final value from either the positive or negative case
 1926        *   is then rounded to the destination precision.
 1927        *   </ul>
 1928        * </ul>
 1929        *
 1930        * @param  n power to raise this {@code BigDecimal} to.
 1931        * @param  mc the context to use.
 1932        * @return <tt>this<sup>n</sup></tt> using the ANSI standard X3.274-1996
 1933        *         algorithm
 1934        * @throws ArithmeticException if the result is inexact but the
 1935        *         rounding mode is {@code UNNECESSARY}, or {@code n} is out
 1936        *         of range.
 1937        * @since  1.5
 1938        */
 1939       public BigDecimal pow(int n, MathContext mc) {
 1940           if (mc.precision == 0)
 1941               return pow(n);
 1942           if (n < -999999999 || n > 999999999)
 1943               throw new ArithmeticException("Invalid operation");
 1944           if (n == 0)
 1945               return ONE;                      // x**0 == 1 in X3.274
 1946           this.inflate();
 1947           BigDecimal lhs = this;
 1948           MathContext workmc = mc;           // working settings
 1949           int mag = Math.abs(n);               // magnitude of n
 1950           if (mc.precision > 0) {
 1951   
 1952               int elength = intLength(mag);    // length of n in digits
 1953               if (elength > mc.precision)        // X3.274 rule
 1954                   throw new ArithmeticException("Invalid operation");
 1955               workmc = new MathContext(mc.precision + elength + 1,
 1956                                         mc.roundingMode);
 1957           }
 1958           // ready to carry out power calculation...
 1959           BigDecimal acc = ONE;           // accumulator
 1960           boolean seenbit = false;        // set once we've seen a 1-bit
 1961           for (int i=1;;i++) {            // for each bit [top bit ignored]
 1962               mag += mag;                 // shift left 1 bit
 1963               if (mag < 0) {              // top bit is set
 1964                   seenbit = true;         // OK, we're off
 1965                   acc = acc.multiply(lhs, workmc); // acc=acc*x
 1966               }
 1967               if (i == 31)
 1968                   break;                  // that was the last bit
 1969               if (seenbit)
 1970                   acc=acc.multiply(acc, workmc);   // acc=acc*acc [square]
 1971                   // else (!seenbit) no point in squaring ONE
 1972           }
 1973           // if negative n, calculate the reciprocal using working precision
 1974           if (n<0)                          // [hence mc.precision>0]
 1975               acc=ONE.divide(acc, workmc);
 1976           // round to final precision and strip zeros
 1977           return acc.doRound(mc);
 1978       }
 1979   
 1980       /**
 1981        * Returns a {@code BigDecimal} whose value is the absolute value
 1982        * of this {@code BigDecimal}, and whose scale is
 1983        * {@code this.scale()}.
 1984        *
 1985        * @return {@code abs(this)}
 1986        */
 1987       public BigDecimal abs() {
 1988           return (signum() < 0 ? negate() : this);
 1989       }
 1990   
 1991       /**
 1992        * Returns a {@code BigDecimal} whose value is the absolute value
 1993        * of this {@code BigDecimal}, with rounding according to the
 1994        * context settings.
 1995        *
 1996        * @param mc the context to use.
 1997        * @return {@code abs(this)}, rounded as necessary.
 1998        * @throws ArithmeticException if the result is inexact but the
 1999        *         rounding mode is {@code UNNECESSARY}.
 2000        * @since 1.5
 2001        */
 2002       public BigDecimal abs(MathContext mc) {
 2003           return (signum() < 0 ? negate(mc) : plus(mc));
 2004       }
 2005   
 2006       /**
 2007        * Returns a {@code BigDecimal} whose value is {@code (-this)},
 2008        * and whose scale is {@code this.scale()}.
 2009        *
 2010        * @return {@code -this}.
 2011        */
 2012       public BigDecimal negate() {
 2013           BigDecimal result;
 2014           if (intCompact != INFLATED)
 2015               result = BigDecimal.valueOf(-intCompact, scale);
 2016           else {
 2017               result = new BigDecimal(intVal.negate(), scale);
 2018               result.precision = precision;
 2019           }
 2020           return result;
 2021       }
 2022   
 2023       /**
 2024        * Returns a {@code BigDecimal} whose value is {@code (-this)},
 2025        * with rounding according to the context settings.
 2026        *
 2027        * @param mc the context to use.
 2028        * @return {@code -this}, rounded as necessary.
 2029        * @throws ArithmeticException if the result is inexact but the
 2030        *         rounding mode is {@code UNNECESSARY}.
 2031        * @since  1.5
 2032        */
 2033       public BigDecimal negate(MathContext mc) {
 2034           return negate().plus(mc);
 2035       }
 2036   
 2037       /**
 2038        * Returns a {@code BigDecimal} whose value is {@code (+this)}, and whose
 2039        * scale is {@code this.scale()}.
 2040        *
 2041        * <p>This method, which simply returns this {@code BigDecimal}
 2042        * is included for symmetry with the unary minus method {@link
 2043        * #negate()}.
 2044        *
 2045        * @return {@code this}.
 2046        * @see #negate()
 2047        * @since  1.5
 2048        */
 2049       public BigDecimal plus() {
 2050           return this;
 2051       }
 2052   
 2053       /**
 2054        * Returns a {@code BigDecimal} whose value is {@code (+this)},
 2055        * with rounding according to the context settings.
 2056        *
 2057        * <p>The effect of this method is identical to that of the {@link
 2058        * #round(MathContext)} method.
 2059        *
 2060        * @param mc the context to use.
 2061        * @return {@code this}, rounded as necessary.  A zero result will
 2062        *         have a scale of 0.
 2063        * @throws ArithmeticException if the result is inexact but the
 2064        *         rounding mode is {@code UNNECESSARY}.
 2065        * @see    #round(MathContext)
 2066        * @since  1.5
 2067        */
 2068       public BigDecimal plus(MathContext mc) {
 2069           if (mc.precision == 0)                 // no rounding please
 2070               return this;
 2071           return this.doRound(mc);
 2072       }
 2073   
 2074       /**
 2075        * Returns the signum function of this {@code BigDecimal}.
 2076        *
 2077        * @return -1, 0, or 1 as the value of this {@code BigDecimal}
 2078        *         is negative, zero, or positive.
 2079        */
 2080       public int signum() {
 2081           return (intCompact != INFLATED)?
 2082               Long.signum(intCompact):
 2083               intVal.signum();
 2084       }
 2085   
 2086       /**
 2087        * Returns the <i>scale</i> of this {@code BigDecimal}.  If zero
 2088        * or positive, the scale is the number of digits to the right of
 2089        * the decimal point.  If negative, the unscaled value of the
 2090        * number is multiplied by ten to the power of the negation of the
 2091        * scale.  For example, a scale of {@code -3} means the unscaled
 2092        * value is multiplied by 1000.
 2093        *
 2094        * @return the scale of this {@code BigDecimal}.
 2095        */
 2096       public int scale() {
 2097           return scale;
 2098       }
 2099   
 2100       /**
 2101        * Returns the <i>precision</i> of this {@code BigDecimal}.  (The
 2102        * precision is the number of digits in the unscaled value.)
 2103        *
 2104        * <p>The precision of a zero value is 1.
 2105        *
 2106        * @return the precision of this {@code BigDecimal}.
 2107        * @since  1.5
 2108        */
 2109       public int precision() {
 2110           int result = precision;
 2111           if (result == 0) {
 2112               result = digitLength();
 2113               precision = result;
 2114           }
 2115           return result;
 2116       }
 2117   
 2118   
 2119       /**
 2120        * Returns a {@code BigInteger} whose value is the <i>unscaled
 2121        * value</i> of this {@code BigDecimal}.  (Computes <tt>(this *
 2122        * 10<sup>this.scale()</sup>)</tt>.)
 2123        *
 2124        * @return the unscaled value of this {@code BigDecimal}.
 2125        * @since  1.2
 2126        */
 2127       public BigInteger unscaledValue() {
 2128           return this.inflate().intVal;
 2129       }
 2130   
 2131       // Rounding Modes
 2132   
 2133       /**
 2134        * Rounding mode to round away from zero.  Always increments the
 2135        * digit prior to a nonzero discarded fraction.  Note that this rounding
 2136        * mode never decreases the magnitude of the calculated value.
 2137        */
 2138       public final static int ROUND_UP =           0;
 2139   
 2140       /**
 2141        * Rounding mode to round towards zero.  Never increments the digit
 2142        * prior to a discarded fraction (i.e., truncates).  Note that this
 2143        * rounding mode never increases the magnitude of the calculated value.
 2144        */
 2145       public final static int ROUND_DOWN =         1;
 2146   
 2147       /**
 2148        * Rounding mode to round towards positive infinity.  If the
 2149        * {@code BigDecimal} is positive, behaves as for
 2150        * {@code ROUND_UP}; if negative, behaves as for
 2151        * {@code ROUND_DOWN}.  Note that this rounding mode never
 2152        * decreases the calculated value.
 2153        */
 2154       public final static int ROUND_CEILING =      2;
 2155   
 2156       /**
 2157        * Rounding mode to round towards negative infinity.  If the
 2158        * {@code BigDecimal} is positive, behave as for
 2159        * {@code ROUND_DOWN}; if negative, behave as for
 2160        * {@code ROUND_UP}.  Note that this rounding mode never
 2161        * increases the calculated value.
 2162        */
 2163       public final static int ROUND_FLOOR =        3;
 2164   
 2165       /**
 2166        * Rounding mode to round towards {@literal "nearest neighbor"}
 2167        * unless both neighbors are equidistant, in which case round up.
 2168        * Behaves as for {@code ROUND_UP} if the discarded fraction is
 2169        * &ge; 0.5; otherwise, behaves as for {@code ROUND_DOWN}.  Note
 2170        * that this is the rounding mode that most of us were taught in
 2171        * grade school.
 2172        */
 2173       public final static int ROUND_HALF_UP =      4;
 2174   
 2175       /**
 2176        * Rounding mode to round towards {@literal "nearest neighbor"}
 2177        * unless both neighbors are equidistant, in which case round
 2178        * down.  Behaves as for {@code ROUND_UP} if the discarded
 2179        * fraction is {@literal >} 0.5; otherwise, behaves as for
 2180        * {@code ROUND_DOWN}.
 2181        */
 2182       public final static int ROUND_HALF_DOWN =    5;
 2183   
 2184       /**
 2185        * Rounding mode to round towards the {@literal "nearest neighbor"}
 2186        * unless both neighbors are equidistant, in which case, round
 2187        * towards the even neighbor.  Behaves as for
 2188        * {@code ROUND_HALF_UP} if the digit to the left of the
 2189        * discarded fraction is odd; behaves as for
 2190        * {@code ROUND_HALF_DOWN} if it's even.  Note that this is the
 2191        * rounding mode that minimizes cumulative error when applied
 2192        * repeatedly over a sequence of calculations.
 2193        */
 2194       public final static int ROUND_HALF_EVEN =    6;
 2195   
 2196       /**
 2197        * Rounding mode to assert that the requested operation has an exact
 2198        * result, hence no rounding is necessary.  If this rounding mode is
 2199        * specified on an operation that yields an inexact result, an
 2200        * {@code ArithmeticException} is thrown.
 2201        */
 2202       public final static int ROUND_UNNECESSARY =  7;
 2203   
 2204   
 2205       // Scaling/Rounding Operations
 2206   
 2207       /**
 2208        * Returns a {@code BigDecimal} rounded according to the
 2209        * {@code MathContext} settings.  If the precision setting is 0 then
 2210        * no rounding takes place.
 2211        *
 2212        * <p>The effect of this method is identical to that of the
 2213        * {@link #plus(MathContext)} method.
 2214        *
 2215        * @param mc the context to use.
 2216        * @return a {@code BigDecimal} rounded according to the
 2217        *         {@code MathContext} settings.
 2218        * @throws ArithmeticException if the rounding mode is
 2219        *         {@code UNNECESSARY} and the
 2220        *         {@code BigDecimal}  operation would require rounding.
 2221        * @see    #plus(MathContext)
 2222        * @since  1.5
 2223        */
 2224       public BigDecimal round(MathContext mc) {
 2225           return plus(mc);
 2226       }
 2227   
 2228       /**
 2229        * Returns a {@code BigDecimal} whose scale is the specified
 2230        * value, and whose unscaled value is determined by multiplying or
 2231        * dividing this {@code BigDecimal}'s unscaled value by the
 2232        * appropriate power of ten to maintain its overall value.  If the
 2233        * scale is reduced