Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/java.base/share/classes/java/math/BigDecimal.java
41152 views
1
/*
2
* Copyright (c) 1996, 2021, Oracle and/or its affiliates. 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. Oracle designates this
8
* particular file as subject to the "Classpath" exception as provided
9
* by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22
* or visit www.oracle.com if you need additional information or have any
23
* questions.
24
*/
25
26
/*
27
* Portions Copyright IBM Corporation, 2001. All Rights Reserved.
28
*/
29
30
package java.math;
31
32
import static java.math.BigInteger.LONG_MASK;
33
import java.io.IOException;
34
import java.util.Arrays;
35
import java.util.Objects;
36
37
/**
38
* Immutable, arbitrary-precision signed decimal numbers. A {@code
39
* BigDecimal} consists of an arbitrary precision integer
40
* <i>{@linkplain unscaledValue() unscaled value}</i> and a 32-bit
41
* integer <i>{@linkplain scale() scale}</i>. If zero or positive,
42
* the scale is the number of digits to the right of the decimal
43
* point. If negative, the unscaled value of the number is multiplied
44
* by ten to the power of the negation of the scale. The value of the
45
* number represented by the {@code BigDecimal} is therefore
46
* <code>(unscaledValue &times; 10<sup>-scale</sup>)</code>.
47
*
48
* <p>The {@code BigDecimal} class provides operations for
49
* arithmetic, scale manipulation, rounding, comparison, hashing, and
50
* format conversion. The {@link #toString} method provides a
51
* canonical representation of a {@code BigDecimal}.
52
*
53
* <p>The {@code BigDecimal} class gives its user complete control
54
* over rounding behavior. If no rounding mode is specified and the
55
* exact result cannot be represented, an {@code ArithmeticException}
56
* is thrown; otherwise, calculations can be carried out to a chosen
57
* precision and rounding mode by supplying an appropriate {@link
58
* MathContext} object to the operation. In either case, eight
59
* <em>rounding modes</em> are provided for the control of rounding.
60
* Using the integer fields in this class (such as {@link
61
* #ROUND_HALF_UP}) to represent rounding mode is deprecated; the
62
* enumeration values of the {@code RoundingMode} {@code enum}, (such
63
* as {@link RoundingMode#HALF_UP}) should be used instead.
64
*
65
* <p>When a {@code MathContext} object is supplied with a precision
66
* setting of 0 (for example, {@link MathContext#UNLIMITED}),
67
* arithmetic operations are exact, as are the arithmetic methods
68
* which take no {@code MathContext} object. As a corollary of
69
* computing the exact result, the rounding mode setting of a {@code
70
* MathContext} object with a precision setting of 0 is not used and
71
* thus irrelevant. In the case of divide, the exact quotient could
72
* have an infinitely long decimal expansion; for example, 1 divided
73
* by 3. If the quotient has a nonterminating decimal expansion and
74
* the operation is specified to return an exact result, an {@code
75
* ArithmeticException} is thrown. Otherwise, the exact result of the
76
* division is returned, as done for other operations.
77
*
78
* <p>When the precision setting is not 0, the rules of {@code
79
* BigDecimal} arithmetic are broadly compatible with selected modes
80
* of operation of the arithmetic defined in ANSI X3.274-1996 and ANSI
81
* X3.274-1996/AM 1-2000 (section 7.4). Unlike those standards,
82
* {@code BigDecimal} includes many rounding modes. Any conflicts
83
* between these ANSI standards and the {@code BigDecimal}
84
* specification are resolved in favor of {@code BigDecimal}.
85
*
86
* <p>Since the same numerical value can have different
87
* representations (with different scales), the rules of arithmetic
88
* and rounding must specify both the numerical result and the scale
89
* used in the result's representation.
90
*
91
* The different representations of the same numerical value are
92
* called members of the same <i>cohort</i>. The {@linkplain
93
* compareTo(BigDecimal) natural order} of {@code BigDecimal}
94
* considers members of the same cohort to be equal to each other. In
95
* contrast, the {@link equals equals} method requires both the
96
* numerical value and representation to be the same for equality to
97
* hold. The results of methods like {@link scale} and {@link
98
* unscaledValue} will differ for numerically equal values with
99
* different representations.
100
*
101
* <p>In general the rounding modes and precision setting determine
102
* how operations return results with a limited number of digits when
103
* the exact result has more digits (perhaps infinitely many in the
104
* case of division and square root) than the number of digits returned.
105
*
106
* First, the total number of digits to return is specified by the
107
* {@code MathContext}'s {@code precision} setting; this determines
108
* the result's <i>precision</i>. The digit count starts from the
109
* leftmost nonzero digit of the exact result. The rounding mode
110
* determines how any discarded trailing digits affect the returned
111
* result.
112
*
113
* <p>For all arithmetic operators, the operation is carried out as
114
* though an exact intermediate result were first calculated and then
115
* rounded to the number of digits specified by the precision setting
116
* (if necessary), using the selected rounding mode. If the exact
117
* result is not returned, some digit positions of the exact result
118
* are discarded. When rounding increases the magnitude of the
119
* returned result, it is possible for a new digit position to be
120
* created by a carry propagating to a leading {@literal "9"} digit.
121
* For example, rounding the value 999.9 to three digits rounding up
122
* would be numerically equal to one thousand, represented as
123
* 100&times;10<sup>1</sup>. In such cases, the new {@literal "1"} is
124
* the leading digit position of the returned result.
125
*
126
* <p>For methods and constructors with a {@code MathContext}
127
* parameter, if the result is inexact but the rounding mode is {@link
128
* RoundingMode#UNNECESSARY UNNECESSARY}, an {@code
129
* ArithmeticException} will be thrown.
130
*
131
* <p>Besides a logical exact result, each arithmetic operation has a
132
* preferred scale for representing a result. The preferred
133
* scale for each operation is listed in the table below.
134
*
135
* <table class="striped" style="text-align:left">
136
* <caption>Preferred Scales for Results of Arithmetic Operations
137
* </caption>
138
* <thead>
139
* <tr><th scope="col">Operation</th><th scope="col">Preferred Scale of Result</th></tr>
140
* </thead>
141
* <tbody>
142
* <tr><th scope="row">Add</th><td>max(addend.scale(), augend.scale())</td>
143
* <tr><th scope="row">Subtract</th><td>max(minuend.scale(), subtrahend.scale())</td>
144
* <tr><th scope="row">Multiply</th><td>multiplier.scale() + multiplicand.scale()</td>
145
* <tr><th scope="row">Divide</th><td>dividend.scale() - divisor.scale()</td>
146
* <tr><th scope="row">Square root</th><td>radicand.scale()/2</td>
147
* </tbody>
148
* </table>
149
*
150
* These scales are the ones used by the methods which return exact
151
* arithmetic results; except that an exact divide may have to use a
152
* larger scale since the exact result may have more digits. For
153
* example, {@code 1/32} is {@code 0.03125}.
154
*
155
* <p>Before rounding, the scale of the logical exact intermediate
156
* result is the preferred scale for that operation. If the exact
157
* numerical result cannot be represented in {@code precision}
158
* digits, rounding selects the set of digits to return and the scale
159
* of the result is reduced from the scale of the intermediate result
160
* to the least scale which can represent the {@code precision}
161
* digits actually returned. If the exact result can be represented
162
* with at most {@code precision} digits, the representation
163
* of the result with the scale closest to the preferred scale is
164
* returned. In particular, an exactly representable quotient may be
165
* represented in fewer than {@code precision} digits by removing
166
* trailing zeros and decreasing the scale. For example, rounding to
167
* three digits using the {@linkplain RoundingMode#FLOOR floor}
168
* rounding mode, <br>
169
*
170
* {@code 19/100 = 0.19 // integer=19, scale=2} <br>
171
*
172
* but<br>
173
*
174
* {@code 21/110 = 0.190 // integer=190, scale=3} <br>
175
*
176
* <p>Note that for add, subtract, and multiply, the reduction in
177
* scale will equal the number of digit positions of the exact result
178
* which are discarded. If the rounding causes a carry propagation to
179
* create a new high-order digit position, an additional digit of the
180
* result is discarded than when no new digit position is created.
181
*
182
* <p>Other methods may have slightly different rounding semantics.
183
* For example, the result of the {@code pow} method using the
184
* {@linkplain #pow(int, MathContext) specified algorithm} can
185
* occasionally differ from the rounded mathematical result by more
186
* than one unit in the last place, one <i>{@linkplain #ulp() ulp}</i>.
187
*
188
* <p>Two types of operations are provided for manipulating the scale
189
* of a {@code BigDecimal}: scaling/rounding operations and decimal
190
* point motion operations. Scaling/rounding operations ({@link
191
* #setScale setScale} and {@link #round round}) return a
192
* {@code BigDecimal} whose value is approximately (or exactly) equal
193
* to that of the operand, but whose scale or precision is the
194
* specified value; that is, they increase or decrease the precision
195
* of the stored number with minimal effect on its value. Decimal
196
* point motion operations ({@link #movePointLeft movePointLeft} and
197
* {@link #movePointRight movePointRight}) return a
198
* {@code BigDecimal} created from the operand by moving the decimal
199
* point a specified distance in the specified direction.
200
*
201
* <p>As a 32-bit integer, the set of values for the scale is large,
202
* but bounded. If the scale of a result would exceed the range of a
203
* 32-bit integer, either by overflow or underflow, the operation may
204
* throw an {@code ArithmeticException}.
205
*
206
* <p>For the sake of brevity and clarity, pseudo-code is used
207
* throughout the descriptions of {@code BigDecimal} methods. The
208
* pseudo-code expression {@code (i + j)} is shorthand for "a
209
* {@code BigDecimal} whose value is that of the {@code BigDecimal}
210
* {@code i} added to that of the {@code BigDecimal}
211
* {@code j}." The pseudo-code expression {@code (i == j)} is
212
* shorthand for "{@code true} if and only if the
213
* {@code BigDecimal} {@code i} represents the same value as the
214
* {@code BigDecimal} {@code j}." Other pseudo-code expressions
215
* are interpreted similarly. Square brackets are used to represent
216
* the particular {@code BigInteger} and scale pair defining a
217
* {@code BigDecimal} value; for example [19, 2] is the
218
* {@code BigDecimal} numerically equal to 0.19 having a scale of 2.
219
*
220
* <p>All methods and constructors for this class throw
221
* {@code NullPointerException} when passed a {@code null} object
222
* reference for any input parameter.
223
*
224
* @apiNote Care should be exercised if {@code BigDecimal} objects are
225
* used as keys in a {@link java.util.SortedMap SortedMap} or elements
226
* in a {@link java.util.SortedSet SortedSet} since {@code
227
* BigDecimal}'s <i>{@linkplain compareTo(BigDecimal) natural
228
* ordering}</i> is <em>inconsistent with equals</em>. See {@link
229
* Comparable}, {@link java.util.SortedMap} or {@link
230
* java.util.SortedSet} for more information.
231
*
232
* <h2>Relation to IEEE 754 Decimal Arithmetic</h2>
233
*
234
* Starting with its 2008 revision, the <cite>IEEE 754 Standard for
235
* Floating-point Arithmetic</cite> has covered decimal formats and
236
* operations. While there are broad similarities in the decimal
237
* arithmetic defined by IEEE 754 and by this class, there are notable
238
* differences as well. The fundamental similarity shared by {@code
239
* BigDecimal} and IEEE 754 decimal arithmetic is the conceptual
240
* operation of computing the mathematical infinitely precise real
241
* number value of an operation and then mapping that real number to a
242
* representable decimal floating-point value under a <em>rounding
243
* policy</em>. The rounding policy is called a {@linkplain
244
* RoundingMode rounding mode} for {@code BigDecimal} and called a
245
* rounding-direction attribute in IEEE 754-2019. When the exact value
246
* is not representable, the rounding policy determines which of the
247
* two representable decimal values bracketing the exact value is
248
* selected as the computed result. The notion of a <em>preferred
249
* scale/preferred exponent</em> is also shared by both systems.
250
*
251
* <p>For differences, IEEE 754 includes several kinds of values not
252
* modeled by {@code BigDecimal} including negative zero, signed
253
* infinities, and NaN (not-a-number). IEEE 754 defines formats, which
254
* are parameterized by base (binary or decimal), number of digits of
255
* precision, and exponent range. A format determines the set of
256
* representable values. Most operations accept as input one or more
257
* values of a given format and produce a result in the same format.
258
* A {@code BigDecimal}'s {@linkplain scale() scale} is equivalent to
259
* negating an IEEE 754 value's exponent. {@code BigDecimal} values do
260
* not have a format in the same sense; all values have the same
261
* possible range of scale/exponent and the {@linkplain
262
* unscaledValue() unscaled value} has arbitrary precision. Instead,
263
* for the {@code BigDecimal} operations taking a {@code MathContext}
264
* parameter, if the {@code MathContext} has a nonzero precision, the
265
* set of possible representable values for the result is determined
266
* by the precision of the {@code MathContext} argument. For example
267
* in {@code BigDecimal}, if a nonzero three-digit number and a
268
* nonzero four-digit number are multiplied together in the context of
269
* a {@code MathContext} object having a precision of three, the
270
* result will have three digits (assuming no overflow or underflow,
271
* etc.).
272
*
273
* <p>The rounding policies implemented by {@code BigDecimal}
274
* operations indicated by {@linkplain RoundingMode rounding modes}
275
* are a proper superset of the IEEE 754 rounding-direction
276
* attributes.
277
278
* <p>{@code BigDecimal} arithmetic will most resemble IEEE 754
279
* decimal arithmetic if a {@code MathContext} corresponding to an
280
* IEEE 754 decimal format, such as {@linkplain MathContext#DECIMAL64
281
* decimal64} or {@linkplain MathContext#DECIMAL128 decimal128} is
282
* used to round all starting values and intermediate operations. The
283
* numerical values computed can differ if the exponent range of the
284
* IEEE 754 format being approximated is exceeded since a {@code
285
* MathContext} does not constrain the scale of {@code BigDecimal}
286
* results. Operations that would generate a NaN or exact infinity,
287
* such as dividing by zero, throw an {@code ArithmeticException} in
288
* {@code BigDecimal} arithmetic.
289
*
290
* @see BigInteger
291
* @see MathContext
292
* @see RoundingMode
293
* @see java.util.SortedMap
294
* @see java.util.SortedSet
295
* @author Josh Bloch
296
* @author Mike Cowlishaw
297
* @author Joseph D. Darcy
298
* @author Sergey V. Kuksenko
299
* @since 1.1
300
*/
301
public class BigDecimal extends Number implements Comparable<BigDecimal> {
302
/**
303
* The unscaled value of this BigDecimal, as returned by {@link
304
* #unscaledValue}.
305
*
306
* @serial
307
* @see #unscaledValue
308
*/
309
private final BigInteger intVal;
310
311
/**
312
* The scale of this BigDecimal, as returned by {@link #scale}.
313
*
314
* @serial
315
* @see #scale
316
*/
317
private final int scale; // Note: this may have any value, so
318
// calculations must be done in longs
319
320
/**
321
* The number of decimal digits in this BigDecimal, or 0 if the
322
* number of digits are not known (lookaside information). If
323
* nonzero, the value is guaranteed correct. Use the precision()
324
* method to obtain and set the value if it might be 0. This
325
* field is mutable until set nonzero.
326
*
327
* @since 1.5
328
*/
329
private transient int precision;
330
331
/**
332
* Used to store the canonical string representation, if computed.
333
*/
334
private transient String stringCache;
335
336
/**
337
* Sentinel value for {@link #intCompact} indicating the
338
* significand information is only available from {@code intVal}.
339
*/
340
static final long INFLATED = Long.MIN_VALUE;
341
342
private static final BigInteger INFLATED_BIGINT = BigInteger.valueOf(INFLATED);
343
344
/**
345
* If the absolute value of the significand of this BigDecimal is
346
* less than or equal to {@code Long.MAX_VALUE}, the value can be
347
* compactly stored in this field and used in computations.
348
*/
349
private final transient long intCompact;
350
351
// All 18-digit base ten strings fit into a long; not all 19-digit
352
// strings will
353
private static final int MAX_COMPACT_DIGITS = 18;
354
355
/* Appease the serialization gods */
356
@java.io.Serial
357
private static final long serialVersionUID = 6108874887143696463L;
358
359
// Cache of common small BigDecimal values.
360
private static final BigDecimal ZERO_THROUGH_TEN[] = {
361
new BigDecimal(BigInteger.ZERO, 0, 0, 1),
362
new BigDecimal(BigInteger.ONE, 1, 0, 1),
363
new BigDecimal(BigInteger.TWO, 2, 0, 1),
364
new BigDecimal(BigInteger.valueOf(3), 3, 0, 1),
365
new BigDecimal(BigInteger.valueOf(4), 4, 0, 1),
366
new BigDecimal(BigInteger.valueOf(5), 5, 0, 1),
367
new BigDecimal(BigInteger.valueOf(6), 6, 0, 1),
368
new BigDecimal(BigInteger.valueOf(7), 7, 0, 1),
369
new BigDecimal(BigInteger.valueOf(8), 8, 0, 1),
370
new BigDecimal(BigInteger.valueOf(9), 9, 0, 1),
371
new BigDecimal(BigInteger.TEN, 10, 0, 2),
372
};
373
374
// Cache of zero scaled by 0 - 15
375
private static final BigDecimal[] ZERO_SCALED_BY = {
376
ZERO_THROUGH_TEN[0],
377
new BigDecimal(BigInteger.ZERO, 0, 1, 1),
378
new BigDecimal(BigInteger.ZERO, 0, 2, 1),
379
new BigDecimal(BigInteger.ZERO, 0, 3, 1),
380
new BigDecimal(BigInteger.ZERO, 0, 4, 1),
381
new BigDecimal(BigInteger.ZERO, 0, 5, 1),
382
new BigDecimal(BigInteger.ZERO, 0, 6, 1),
383
new BigDecimal(BigInteger.ZERO, 0, 7, 1),
384
new BigDecimal(BigInteger.ZERO, 0, 8, 1),
385
new BigDecimal(BigInteger.ZERO, 0, 9, 1),
386
new BigDecimal(BigInteger.ZERO, 0, 10, 1),
387
new BigDecimal(BigInteger.ZERO, 0, 11, 1),
388
new BigDecimal(BigInteger.ZERO, 0, 12, 1),
389
new BigDecimal(BigInteger.ZERO, 0, 13, 1),
390
new BigDecimal(BigInteger.ZERO, 0, 14, 1),
391
new BigDecimal(BigInteger.ZERO, 0, 15, 1),
392
};
393
394
// Half of Long.MIN_VALUE & Long.MAX_VALUE.
395
private static final long HALF_LONG_MAX_VALUE = Long.MAX_VALUE / 2;
396
private static final long HALF_LONG_MIN_VALUE = Long.MIN_VALUE / 2;
397
398
// Constants
399
/**
400
* The value 0, with a scale of 0.
401
*
402
* @since 1.5
403
*/
404
public static final BigDecimal ZERO =
405
ZERO_THROUGH_TEN[0];
406
407
/**
408
* The value 1, with a scale of 0.
409
*
410
* @since 1.5
411
*/
412
public static final BigDecimal ONE =
413
ZERO_THROUGH_TEN[1];
414
415
/**
416
* The value 10, with a scale of 0.
417
*
418
* @since 1.5
419
*/
420
public static final BigDecimal TEN =
421
ZERO_THROUGH_TEN[10];
422
423
/**
424
* The value 0.1, with a scale of 1.
425
*/
426
private static final BigDecimal ONE_TENTH = valueOf(1L, 1);
427
428
/**
429
* The value 0.5, with a scale of 1.
430
*/
431
private static final BigDecimal ONE_HALF = valueOf(5L, 1);
432
433
// Constructors
434
435
/**
436
* Trusted package private constructor.
437
* Trusted simply means if val is INFLATED, intVal could not be null and
438
* if intVal is null, val could not be INFLATED.
439
*/
440
BigDecimal(BigInteger intVal, long val, int scale, int prec) {
441
this.scale = scale;
442
this.precision = prec;
443
this.intCompact = val;
444
this.intVal = intVal;
445
}
446
447
/**
448
* Translates a character array representation of a
449
* {@code BigDecimal} into a {@code BigDecimal}, accepting the
450
* same sequence of characters as the {@link #BigDecimal(String)}
451
* constructor, while allowing a sub-array to be specified.
452
*
453
* @implNote If the sequence of characters is already available
454
* within a character array, using this constructor is faster than
455
* converting the {@code char} array to string and using the
456
* {@code BigDecimal(String)} constructor.
457
*
458
* @param in {@code char} array that is the source of characters.
459
* @param offset first character in the array to inspect.
460
* @param len number of characters to consider.
461
* @throws NumberFormatException if {@code in} is not a valid
462
* representation of a {@code BigDecimal} or the defined subarray
463
* is not wholly within {@code in}.
464
* @since 1.5
465
*/
466
public BigDecimal(char[] in, int offset, int len) {
467
this(in,offset,len,MathContext.UNLIMITED);
468
}
469
470
/**
471
* Translates a character array representation of a
472
* {@code BigDecimal} into a {@code BigDecimal}, accepting the
473
* same sequence of characters as the {@link #BigDecimal(String)}
474
* constructor, while allowing a sub-array to be specified and
475
* with rounding according to the context settings.
476
*
477
* @implNote If the sequence of characters is already available
478
* within a character array, using this constructor is faster than
479
* converting the {@code char} array to string and using the
480
* {@code BigDecimal(String)} constructor.
481
*
482
* @param in {@code char} array that is the source of characters.
483
* @param offset first character in the array to inspect.
484
* @param len number of characters to consider.
485
* @param mc the context to use.
486
* @throws NumberFormatException if {@code in} is not a valid
487
* representation of a {@code BigDecimal} or the defined subarray
488
* is not wholly within {@code in}.
489
* @since 1.5
490
*/
491
public BigDecimal(char[] in, int offset, int len, MathContext mc) {
492
// protect against huge length, negative values, and integer overflow
493
try {
494
Objects.checkFromIndexSize(offset, len, in.length);
495
} catch (IndexOutOfBoundsException e) {
496
throw new NumberFormatException
497
("Bad offset or len arguments for char[] input.");
498
}
499
500
// This is the primary string to BigDecimal constructor; all
501
// incoming strings end up here; it uses explicit (inline)
502
// parsing for speed and generates at most one intermediate
503
// (temporary) object (a char[] array) for non-compact case.
504
505
// Use locals for all fields values until completion
506
int prec = 0; // record precision value
507
int scl = 0; // record scale value
508
long rs = 0; // the compact value in long
509
BigInteger rb = null; // the inflated value in BigInteger
510
// use array bounds checking to handle too-long, len == 0,
511
// bad offset, etc.
512
try {
513
// handle the sign
514
boolean isneg = false; // assume positive
515
if (in[offset] == '-') {
516
isneg = true; // leading minus means negative
517
offset++;
518
len--;
519
} else if (in[offset] == '+') { // leading + allowed
520
offset++;
521
len--;
522
}
523
524
// should now be at numeric part of the significand
525
boolean dot = false; // true when there is a '.'
526
long exp = 0; // exponent
527
char c; // current character
528
boolean isCompact = (len <= MAX_COMPACT_DIGITS);
529
// integer significand array & idx is the index to it. The array
530
// is ONLY used when we can't use a compact representation.
531
int idx = 0;
532
if (isCompact) {
533
// First compact case, we need not to preserve the character
534
// and we can just compute the value in place.
535
for (; len > 0; offset++, len--) {
536
c = in[offset];
537
if ((c == '0')) { // have zero
538
if (prec == 0)
539
prec = 1;
540
else if (rs != 0) {
541
rs *= 10;
542
++prec;
543
} // else digit is a redundant leading zero
544
if (dot)
545
++scl;
546
} else if ((c >= '1' && c <= '9')) { // have digit
547
int digit = c - '0';
548
if (prec != 1 || rs != 0)
549
++prec; // prec unchanged if preceded by 0s
550
rs = rs * 10 + digit;
551
if (dot)
552
++scl;
553
} else if (c == '.') { // have dot
554
// have dot
555
if (dot) // two dots
556
throw new NumberFormatException("Character array"
557
+ " contains more than one decimal point.");
558
dot = true;
559
} else if (Character.isDigit(c)) { // slow path
560
int digit = Character.digit(c, 10);
561
if (digit == 0) {
562
if (prec == 0)
563
prec = 1;
564
else if (rs != 0) {
565
rs *= 10;
566
++prec;
567
} // else digit is a redundant leading zero
568
} else {
569
if (prec != 1 || rs != 0)
570
++prec; // prec unchanged if preceded by 0s
571
rs = rs * 10 + digit;
572
}
573
if (dot)
574
++scl;
575
} else if ((c == 'e') || (c == 'E')) {
576
exp = parseExp(in, offset, len);
577
// Next test is required for backwards compatibility
578
if ((int) exp != exp) // overflow
579
throw new NumberFormatException("Exponent overflow.");
580
break; // [saves a test]
581
} else {
582
throw new NumberFormatException("Character " + c
583
+ " is neither a decimal digit number, decimal point, nor"
584
+ " \"e\" notation exponential mark.");
585
}
586
}
587
if (prec == 0) // no digits found
588
throw new NumberFormatException("No digits found.");
589
// Adjust scale if exp is not zero.
590
if (exp != 0) { // had significant exponent
591
scl = adjustScale(scl, exp);
592
}
593
rs = isneg ? -rs : rs;
594
int mcp = mc.precision;
595
int drop = prec - mcp; // prec has range [1, MAX_INT], mcp has range [0, MAX_INT];
596
// therefore, this subtract cannot overflow
597
if (mcp > 0 && drop > 0) { // do rounding
598
while (drop > 0) {
599
scl = checkScaleNonZero((long) scl - drop);
600
rs = divideAndRound(rs, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
601
prec = longDigitLength(rs);
602
drop = prec - mcp;
603
}
604
}
605
} else {
606
char coeff[] = new char[len];
607
for (; len > 0; offset++, len--) {
608
c = in[offset];
609
// have digit
610
if ((c >= '0' && c <= '9') || Character.isDigit(c)) {
611
// First compact case, we need not to preserve the character
612
// and we can just compute the value in place.
613
if (c == '0' || Character.digit(c, 10) == 0) {
614
if (prec == 0) {
615
coeff[idx] = c;
616
prec = 1;
617
} else if (idx != 0) {
618
coeff[idx++] = c;
619
++prec;
620
} // else c must be a redundant leading zero
621
} else {
622
if (prec != 1 || idx != 0)
623
++prec; // prec unchanged if preceded by 0s
624
coeff[idx++] = c;
625
}
626
if (dot)
627
++scl;
628
continue;
629
}
630
// have dot
631
if (c == '.') {
632
// have dot
633
if (dot) // two dots
634
throw new NumberFormatException("Character array"
635
+ " contains more than one decimal point.");
636
dot = true;
637
continue;
638
}
639
// exponent expected
640
if ((c != 'e') && (c != 'E'))
641
throw new NumberFormatException("Character array"
642
+ " is missing \"e\" notation exponential mark.");
643
exp = parseExp(in, offset, len);
644
// Next test is required for backwards compatibility
645
if ((int) exp != exp) // overflow
646
throw new NumberFormatException("Exponent overflow.");
647
break; // [saves a test]
648
}
649
// here when no characters left
650
if (prec == 0) // no digits found
651
throw new NumberFormatException("No digits found.");
652
// Adjust scale if exp is not zero.
653
if (exp != 0) { // had significant exponent
654
scl = adjustScale(scl, exp);
655
}
656
// Remove leading zeros from precision (digits count)
657
rb = new BigInteger(coeff, isneg ? -1 : 1, prec);
658
rs = compactValFor(rb);
659
int mcp = mc.precision;
660
if (mcp > 0 && (prec > mcp)) {
661
if (rs == INFLATED) {
662
int drop = prec - mcp;
663
while (drop > 0) {
664
scl = checkScaleNonZero((long) scl - drop);
665
rb = divideAndRoundByTenPow(rb, drop, mc.roundingMode.oldMode);
666
rs = compactValFor(rb);
667
if (rs != INFLATED) {
668
prec = longDigitLength(rs);
669
break;
670
}
671
prec = bigDigitLength(rb);
672
drop = prec - mcp;
673
}
674
}
675
if (rs != INFLATED) {
676
int drop = prec - mcp;
677
while (drop > 0) {
678
scl = checkScaleNonZero((long) scl - drop);
679
rs = divideAndRound(rs, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
680
prec = longDigitLength(rs);
681
drop = prec - mcp;
682
}
683
rb = null;
684
}
685
}
686
}
687
} catch (ArrayIndexOutOfBoundsException | NegativeArraySizeException e) {
688
NumberFormatException nfe = new NumberFormatException();
689
nfe.initCause(e);
690
throw nfe;
691
}
692
this.scale = scl;
693
this.precision = prec;
694
this.intCompact = rs;
695
this.intVal = rb;
696
}
697
698
private int adjustScale(int scl, long exp) {
699
long adjustedScale = scl - exp;
700
if (adjustedScale > Integer.MAX_VALUE || adjustedScale < Integer.MIN_VALUE)
701
throw new NumberFormatException("Scale out of range.");
702
scl = (int) adjustedScale;
703
return scl;
704
}
705
706
/*
707
* parse exponent
708
*/
709
private static long parseExp(char[] in, int offset, int len){
710
long exp = 0;
711
offset++;
712
char c = in[offset];
713
len--;
714
boolean negexp = (c == '-');
715
// optional sign
716
if (negexp || c == '+') {
717
offset++;
718
c = in[offset];
719
len--;
720
}
721
if (len <= 0) // no exponent digits
722
throw new NumberFormatException("No exponent digits.");
723
// skip leading zeros in the exponent
724
while (len > 10 && (c=='0' || (Character.digit(c, 10) == 0))) {
725
offset++;
726
c = in[offset];
727
len--;
728
}
729
if (len > 10) // too many nonzero exponent digits
730
throw new NumberFormatException("Too many nonzero exponent digits.");
731
// c now holds first digit of exponent
732
for (;; len--) {
733
int v;
734
if (c >= '0' && c <= '9') {
735
v = c - '0';
736
} else {
737
v = Character.digit(c, 10);
738
if (v < 0) // not a digit
739
throw new NumberFormatException("Not a digit.");
740
}
741
exp = exp * 10 + v;
742
if (len == 1)
743
break; // that was final character
744
offset++;
745
c = in[offset];
746
}
747
if (negexp) // apply sign
748
exp = -exp;
749
return exp;
750
}
751
752
/**
753
* Translates a character array representation of a
754
* {@code BigDecimal} into a {@code BigDecimal}, accepting the
755
* same sequence of characters as the {@link #BigDecimal(String)}
756
* constructor.
757
*
758
* @implNote If the sequence of characters is already available
759
* as a character array, using this constructor is faster than
760
* converting the {@code char} array to string and using the
761
* {@code BigDecimal(String)} constructor.
762
*
763
* @param in {@code char} array that is the source of characters.
764
* @throws NumberFormatException if {@code in} is not a valid
765
* representation of a {@code BigDecimal}.
766
* @since 1.5
767
*/
768
public BigDecimal(char[] in) {
769
this(in, 0, in.length);
770
}
771
772
/**
773
* Translates a character array representation of a
774
* {@code BigDecimal} into a {@code BigDecimal}, accepting the
775
* same sequence of characters as the {@link #BigDecimal(String)}
776
* constructor and with rounding according to the context
777
* settings.
778
*
779
* @implNote If the sequence of characters is already available
780
* as a character array, using this constructor is faster than
781
* converting the {@code char} array to string and using the
782
* {@code BigDecimal(String)} constructor.
783
*
784
* @param in {@code char} array that is the source of characters.
785
* @param mc the context to use.
786
* @throws NumberFormatException if {@code in} is not a valid
787
* representation of a {@code BigDecimal}.
788
* @since 1.5
789
*/
790
public BigDecimal(char[] in, MathContext mc) {
791
this(in, 0, in.length, mc);
792
}
793
794
/**
795
* Translates the string representation of a {@code BigDecimal}
796
* into a {@code BigDecimal}. The string representation consists
797
* of an optional sign, {@code '+'} (<code> '&#92;u002B'</code>) or
798
* {@code '-'} (<code>'&#92;u002D'</code>), followed by a sequence of
799
* zero or more decimal digits ("the integer"), optionally
800
* followed by a fraction, optionally followed by an exponent.
801
*
802
* <p>The fraction consists of a decimal point followed by zero
803
* or more decimal digits. The string must contain at least one
804
* digit in either the integer or the fraction. The number formed
805
* by the sign, the integer and the fraction is referred to as the
806
* <i>significand</i>.
807
*
808
* <p>The exponent consists of the character {@code 'e'}
809
* (<code>'&#92;u0065'</code>) or {@code 'E'} (<code>'&#92;u0045'</code>)
810
* followed by one or more decimal digits. The value of the
811
* exponent must lie between -{@link Integer#MAX_VALUE} ({@link
812
* Integer#MIN_VALUE}+1) and {@link Integer#MAX_VALUE}, inclusive.
813
*
814
* <p>More formally, the strings this constructor accepts are
815
* described by the following grammar:
816
* <blockquote>
817
* <dl>
818
* <dt><i>BigDecimalString:</i>
819
* <dd><i>Sign<sub>opt</sub> Significand Exponent<sub>opt</sub></i>
820
* <dt><i>Sign:</i>
821
* <dd>{@code +}
822
* <dd>{@code -}
823
* <dt><i>Significand:</i>
824
* <dd><i>IntegerPart</i> {@code .} <i>FractionPart<sub>opt</sub></i>
825
* <dd>{@code .} <i>FractionPart</i>
826
* <dd><i>IntegerPart</i>
827
* <dt><i>IntegerPart:</i>
828
* <dd><i>Digits</i>
829
* <dt><i>FractionPart:</i>
830
* <dd><i>Digits</i>
831
* <dt><i>Exponent:</i>
832
* <dd><i>ExponentIndicator SignedInteger</i>
833
* <dt><i>ExponentIndicator:</i>
834
* <dd>{@code e}
835
* <dd>{@code E}
836
* <dt><i>SignedInteger:</i>
837
* <dd><i>Sign<sub>opt</sub> Digits</i>
838
* <dt><i>Digits:</i>
839
* <dd><i>Digit</i>
840
* <dd><i>Digits Digit</i>
841
* <dt><i>Digit:</i>
842
* <dd>any character for which {@link Character#isDigit}
843
* returns {@code true}, including 0, 1, 2 ...
844
* </dl>
845
* </blockquote>
846
*
847
* <p>The scale of the returned {@code BigDecimal} will be the
848
* number of digits in the fraction, or zero if the string
849
* contains no decimal point, subject to adjustment for any
850
* exponent; if the string contains an exponent, the exponent is
851
* subtracted from the scale. The value of the resulting scale
852
* must lie between {@code Integer.MIN_VALUE} and
853
* {@code Integer.MAX_VALUE}, inclusive.
854
*
855
* <p>The character-to-digit mapping is provided by {@link
856
* java.lang.Character#digit} set to convert to radix 10. The
857
* String may not contain any extraneous characters (whitespace,
858
* for example).
859
*
860
* <p><b>Examples:</b><br>
861
* The value of the returned {@code BigDecimal} is equal to
862
* <i>significand</i> &times; 10<sup>&nbsp;<i>exponent</i></sup>.
863
* For each string on the left, the resulting representation
864
* [{@code BigInteger}, {@code scale}] is shown on the right.
865
* <pre>
866
* "0" [0,0]
867
* "0.00" [0,2]
868
* "123" [123,0]
869
* "-123" [-123,0]
870
* "1.23E3" [123,-1]
871
* "1.23E+3" [123,-1]
872
* "12.3E+7" [123,-6]
873
* "12.0" [120,1]
874
* "12.3" [123,1]
875
* "0.00123" [123,5]
876
* "-1.23E-12" [-123,14]
877
* "1234.5E-4" [12345,5]
878
* "0E+7" [0,-7]
879
* "-0" [0,0]
880
* </pre>
881
*
882
* @apiNote For values other than {@code float} and
883
* {@code double} NaN and &plusmn;Infinity, this constructor is
884
* compatible with the values returned by {@link Float#toString}
885
* and {@link Double#toString}. This is generally the preferred
886
* way to convert a {@code float} or {@code double} into a
887
* BigDecimal, as it doesn't suffer from the unpredictability of
888
* the {@link #BigDecimal(double)} constructor.
889
*
890
* @param val String representation of {@code BigDecimal}.
891
*
892
* @throws NumberFormatException if {@code val} is not a valid
893
* representation of a {@code BigDecimal}.
894
*/
895
public BigDecimal(String val) {
896
this(val.toCharArray(), 0, val.length());
897
}
898
899
/**
900
* Translates the string representation of a {@code BigDecimal}
901
* into a {@code BigDecimal}, accepting the same strings as the
902
* {@link #BigDecimal(String)} constructor, with rounding
903
* according to the context settings.
904
*
905
* @param val string representation of a {@code BigDecimal}.
906
* @param mc the context to use.
907
* @throws NumberFormatException if {@code val} is not a valid
908
* representation of a BigDecimal.
909
* @since 1.5
910
*/
911
public BigDecimal(String val, MathContext mc) {
912
this(val.toCharArray(), 0, val.length(), mc);
913
}
914
915
/**
916
* Translates a {@code double} into a {@code BigDecimal} which
917
* is the exact decimal representation of the {@code double}'s
918
* binary floating-point value. The scale of the returned
919
* {@code BigDecimal} is the smallest value such that
920
* <code>(10<sup>scale</sup> &times; val)</code> is an integer.
921
* <p>
922
* <b>Notes:</b>
923
* <ol>
924
* <li>
925
* The results of this constructor can be somewhat unpredictable.
926
* One might assume that writing {@code new BigDecimal(0.1)} in
927
* Java creates a {@code BigDecimal} which is exactly equal to
928
* 0.1 (an unscaled value of 1, with a scale of 1), but it is
929
* actually equal to
930
* 0.1000000000000000055511151231257827021181583404541015625.
931
* This is because 0.1 cannot be represented exactly as a
932
* {@code double} (or, for that matter, as a binary fraction of
933
* any finite length). Thus, the value that is being passed
934
* <em>in</em> to the constructor is not exactly equal to 0.1,
935
* appearances notwithstanding.
936
*
937
* <li>
938
* The {@code String} constructor, on the other hand, is
939
* perfectly predictable: writing {@code new BigDecimal("0.1")}
940
* creates a {@code BigDecimal} which is <em>exactly</em> equal to
941
* 0.1, as one would expect. Therefore, it is generally
942
* recommended that the {@linkplain #BigDecimal(String)
943
* String constructor} be used in preference to this one.
944
*
945
* <li>
946
* When a {@code double} must be used as a source for a
947
* {@code BigDecimal}, note that this constructor provides an
948
* exact conversion; it does not give the same result as
949
* converting the {@code double} to a {@code String} using the
950
* {@link Double#toString(double)} method and then using the
951
* {@link #BigDecimal(String)} constructor. To get that result,
952
* use the {@code static} {@link #valueOf(double)} method.
953
* </ol>
954
*
955
* @param val {@code double} value to be converted to
956
* {@code BigDecimal}.
957
* @throws NumberFormatException if {@code val} is infinite or NaN.
958
*/
959
public BigDecimal(double val) {
960
this(val,MathContext.UNLIMITED);
961
}
962
963
/**
964
* Translates a {@code double} into a {@code BigDecimal}, with
965
* rounding according to the context settings. The scale of the
966
* {@code BigDecimal} is the smallest value such that
967
* <code>(10<sup>scale</sup> &times; val)</code> is an integer.
968
*
969
* <p>The results of this constructor can be somewhat unpredictable
970
* and its use is generally not recommended; see the notes under
971
* the {@link #BigDecimal(double)} constructor.
972
*
973
* @param val {@code double} value to be converted to
974
* {@code BigDecimal}.
975
* @param mc the context to use.
976
* @throws NumberFormatException if {@code val} is infinite or NaN.
977
* @since 1.5
978
*/
979
public BigDecimal(double val, MathContext mc) {
980
if (Double.isInfinite(val) || Double.isNaN(val))
981
throw new NumberFormatException("Infinite or NaN");
982
// Translate the double into sign, exponent and significand, according
983
// to the formulae in JLS, Section 20.10.22.
984
long valBits = Double.doubleToLongBits(val);
985
int sign = ((valBits >> 63) == 0 ? 1 : -1);
986
int exponent = (int) ((valBits >> 52) & 0x7ffL);
987
long significand = (exponent == 0
988
? (valBits & ((1L << 52) - 1)) << 1
989
: (valBits & ((1L << 52) - 1)) | (1L << 52));
990
exponent -= 1075;
991
// At this point, val == sign * significand * 2**exponent.
992
993
/*
994
* Special case zero to suppress nonterminating normalization and bogus
995
* scale calculation.
996
*/
997
if (significand == 0) {
998
this.intVal = BigInteger.ZERO;
999
this.scale = 0;
1000
this.intCompact = 0;
1001
this.precision = 1;
1002
return;
1003
}
1004
// Normalize
1005
while ((significand & 1) == 0) { // i.e., significand is even
1006
significand >>= 1;
1007
exponent++;
1008
}
1009
int scl = 0;
1010
// Calculate intVal and scale
1011
BigInteger rb;
1012
long compactVal = sign * significand;
1013
if (exponent == 0) {
1014
rb = (compactVal == INFLATED) ? INFLATED_BIGINT : null;
1015
} else {
1016
if (exponent < 0) {
1017
rb = BigInteger.valueOf(5).pow(-exponent).multiply(compactVal);
1018
scl = -exponent;
1019
} else { // (exponent > 0)
1020
rb = BigInteger.TWO.pow(exponent).multiply(compactVal);
1021
}
1022
compactVal = compactValFor(rb);
1023
}
1024
int prec = 0;
1025
int mcp = mc.precision;
1026
if (mcp > 0) { // do rounding
1027
int mode = mc.roundingMode.oldMode;
1028
int drop;
1029
if (compactVal == INFLATED) {
1030
prec = bigDigitLength(rb);
1031
drop = prec - mcp;
1032
while (drop > 0) {
1033
scl = checkScaleNonZero((long) scl - drop);
1034
rb = divideAndRoundByTenPow(rb, drop, mode);
1035
compactVal = compactValFor(rb);
1036
if (compactVal != INFLATED) {
1037
break;
1038
}
1039
prec = bigDigitLength(rb);
1040
drop = prec - mcp;
1041
}
1042
}
1043
if (compactVal != INFLATED) {
1044
prec = longDigitLength(compactVal);
1045
drop = prec - mcp;
1046
while (drop > 0) {
1047
scl = checkScaleNonZero((long) scl - drop);
1048
compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
1049
prec = longDigitLength(compactVal);
1050
drop = prec - mcp;
1051
}
1052
rb = null;
1053
}
1054
}
1055
this.intVal = rb;
1056
this.intCompact = compactVal;
1057
this.scale = scl;
1058
this.precision = prec;
1059
}
1060
1061
/**
1062
* Translates a {@code BigInteger} into a {@code BigDecimal}.
1063
* The scale of the {@code BigDecimal} is zero.
1064
*
1065
* @param val {@code BigInteger} value to be converted to
1066
* {@code BigDecimal}.
1067
*/
1068
public BigDecimal(BigInteger val) {
1069
scale = 0;
1070
intVal = val;
1071
intCompact = compactValFor(val);
1072
}
1073
1074
/**
1075
* Translates a {@code BigInteger} into a {@code BigDecimal}
1076
* rounding according to the context settings. The scale of the
1077
* {@code BigDecimal} is zero.
1078
*
1079
* @param val {@code BigInteger} value to be converted to
1080
* {@code BigDecimal}.
1081
* @param mc the context to use.
1082
* @since 1.5
1083
*/
1084
public BigDecimal(BigInteger val, MathContext mc) {
1085
this(val,0,mc);
1086
}
1087
1088
/**
1089
* Translates a {@code BigInteger} unscaled value and an
1090
* {@code int} scale into a {@code BigDecimal}. The value of
1091
* the {@code BigDecimal} is
1092
* <code>(unscaledVal &times; 10<sup>-scale</sup>)</code>.
1093
*
1094
* @param unscaledVal unscaled value of the {@code BigDecimal}.
1095
* @param scale scale of the {@code BigDecimal}.
1096
*/
1097
public BigDecimal(BigInteger unscaledVal, int scale) {
1098
// Negative scales are now allowed
1099
this.intVal = unscaledVal;
1100
this.intCompact = compactValFor(unscaledVal);
1101
this.scale = scale;
1102
}
1103
1104
/**
1105
* Translates a {@code BigInteger} unscaled value and an
1106
* {@code int} scale into a {@code BigDecimal}, with rounding
1107
* according to the context settings. The value of the
1108
* {@code BigDecimal} is <code>(unscaledVal &times;
1109
* 10<sup>-scale</sup>)</code>, rounded according to the
1110
* {@code precision} and rounding mode settings.
1111
*
1112
* @param unscaledVal unscaled value of the {@code BigDecimal}.
1113
* @param scale scale of the {@code BigDecimal}.
1114
* @param mc the context to use.
1115
* @since 1.5
1116
*/
1117
public BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) {
1118
long compactVal = compactValFor(unscaledVal);
1119
int mcp = mc.precision;
1120
int prec = 0;
1121
if (mcp > 0) { // do rounding
1122
int mode = mc.roundingMode.oldMode;
1123
if (compactVal == INFLATED) {
1124
prec = bigDigitLength(unscaledVal);
1125
int drop = prec - mcp;
1126
while (drop > 0) {
1127
scale = checkScaleNonZero((long) scale - drop);
1128
unscaledVal = divideAndRoundByTenPow(unscaledVal, drop, mode);
1129
compactVal = compactValFor(unscaledVal);
1130
if (compactVal != INFLATED) {
1131
break;
1132
}
1133
prec = bigDigitLength(unscaledVal);
1134
drop = prec - mcp;
1135
}
1136
}
1137
if (compactVal != INFLATED) {
1138
prec = longDigitLength(compactVal);
1139
int drop = prec - mcp; // drop can't be more than 18
1140
while (drop > 0) {
1141
scale = checkScaleNonZero((long) scale - drop);
1142
compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mode);
1143
prec = longDigitLength(compactVal);
1144
drop = prec - mcp;
1145
}
1146
unscaledVal = null;
1147
}
1148
}
1149
this.intVal = unscaledVal;
1150
this.intCompact = compactVal;
1151
this.scale = scale;
1152
this.precision = prec;
1153
}
1154
1155
/**
1156
* Translates an {@code int} into a {@code BigDecimal}. The
1157
* scale of the {@code BigDecimal} is zero.
1158
*
1159
* @param val {@code int} value to be converted to
1160
* {@code BigDecimal}.
1161
* @since 1.5
1162
*/
1163
public BigDecimal(int val) {
1164
this.intCompact = val;
1165
this.scale = 0;
1166
this.intVal = null;
1167
}
1168
1169
/**
1170
* Translates an {@code int} into a {@code BigDecimal}, with
1171
* rounding according to the context settings. The scale of the
1172
* {@code BigDecimal}, before any rounding, is zero.
1173
*
1174
* @param val {@code int} value to be converted to {@code BigDecimal}.
1175
* @param mc the context to use.
1176
* @since 1.5
1177
*/
1178
public BigDecimal(int val, MathContext mc) {
1179
int mcp = mc.precision;
1180
long compactVal = val;
1181
int scl = 0;
1182
int prec = 0;
1183
if (mcp > 0) { // do rounding
1184
prec = longDigitLength(compactVal);
1185
int drop = prec - mcp; // drop can't be more than 18
1186
while (drop > 0) {
1187
scl = checkScaleNonZero((long) scl - drop);
1188
compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
1189
prec = longDigitLength(compactVal);
1190
drop = prec - mcp;
1191
}
1192
}
1193
this.intVal = null;
1194
this.intCompact = compactVal;
1195
this.scale = scl;
1196
this.precision = prec;
1197
}
1198
1199
/**
1200
* Translates a {@code long} into a {@code BigDecimal}. The
1201
* scale of the {@code BigDecimal} is zero.
1202
*
1203
* @param val {@code long} value to be converted to {@code BigDecimal}.
1204
* @since 1.5
1205
*/
1206
public BigDecimal(long val) {
1207
this.intCompact = val;
1208
this.intVal = (val == INFLATED) ? INFLATED_BIGINT : null;
1209
this.scale = 0;
1210
}
1211
1212
/**
1213
* Translates a {@code long} into a {@code BigDecimal}, with
1214
* rounding according to the context settings. The scale of the
1215
* {@code BigDecimal}, before any rounding, is zero.
1216
*
1217
* @param val {@code long} value to be converted to {@code BigDecimal}.
1218
* @param mc the context to use.
1219
* @since 1.5
1220
*/
1221
public BigDecimal(long val, MathContext mc) {
1222
int mcp = mc.precision;
1223
int mode = mc.roundingMode.oldMode;
1224
int prec = 0;
1225
int scl = 0;
1226
BigInteger rb = (val == INFLATED) ? INFLATED_BIGINT : null;
1227
if (mcp > 0) { // do rounding
1228
if (val == INFLATED) {
1229
prec = 19;
1230
int drop = prec - mcp;
1231
while (drop > 0) {
1232
scl = checkScaleNonZero((long) scl - drop);
1233
rb = divideAndRoundByTenPow(rb, drop, mode);
1234
val = compactValFor(rb);
1235
if (val != INFLATED) {
1236
break;
1237
}
1238
prec = bigDigitLength(rb);
1239
drop = prec - mcp;
1240
}
1241
}
1242
if (val != INFLATED) {
1243
prec = longDigitLength(val);
1244
int drop = prec - mcp;
1245
while (drop > 0) {
1246
scl = checkScaleNonZero((long) scl - drop);
1247
val = divideAndRound(val, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
1248
prec = longDigitLength(val);
1249
drop = prec - mcp;
1250
}
1251
rb = null;
1252
}
1253
}
1254
this.intVal = rb;
1255
this.intCompact = val;
1256
this.scale = scl;
1257
this.precision = prec;
1258
}
1259
1260
// Static Factory Methods
1261
1262
/**
1263
* Translates a {@code long} unscaled value and an
1264
* {@code int} scale into a {@code BigDecimal}.
1265
*
1266
* @apiNote This static factory method is provided in preference
1267
* to a ({@code long}, {@code int}) constructor because it allows
1268
* for reuse of frequently used {@code BigDecimal} values.
1269
*
1270
* @param unscaledVal unscaled value of the {@code BigDecimal}.
1271
* @param scale scale of the {@code BigDecimal}.
1272
* @return a {@code BigDecimal} whose value is
1273
* <code>(unscaledVal &times; 10<sup>-scale</sup>)</code>.
1274
*/
1275
public static BigDecimal valueOf(long unscaledVal, int scale) {
1276
if (scale == 0)
1277
return valueOf(unscaledVal);
1278
else if (unscaledVal == 0) {
1279
return zeroValueOf(scale);
1280
}
1281
return new BigDecimal(unscaledVal == INFLATED ?
1282
INFLATED_BIGINT : null,
1283
unscaledVal, scale, 0);
1284
}
1285
1286
/**
1287
* Translates a {@code long} value into a {@code BigDecimal}
1288
* with a scale of zero.
1289
*
1290
* @apiNote This static factory method is provided in preference
1291
* to a ({@code long}) constructor because it allows for reuse of
1292
* frequently used {@code BigDecimal} values.
1293
*
1294
* @param val value of the {@code BigDecimal}.
1295
* @return a {@code BigDecimal} whose value is {@code val}.
1296
*/
1297
public static BigDecimal valueOf(long val) {
1298
if (val >= 0 && val < ZERO_THROUGH_TEN.length)
1299
return ZERO_THROUGH_TEN[(int)val];
1300
else if (val != INFLATED)
1301
return new BigDecimal(null, val, 0, 0);
1302
return new BigDecimal(INFLATED_BIGINT, val, 0, 0);
1303
}
1304
1305
static BigDecimal valueOf(long unscaledVal, int scale, int prec) {
1306
if (scale == 0 && unscaledVal >= 0 && unscaledVal < ZERO_THROUGH_TEN.length) {
1307
return ZERO_THROUGH_TEN[(int) unscaledVal];
1308
} else if (unscaledVal == 0) {
1309
return zeroValueOf(scale);
1310
}
1311
return new BigDecimal(unscaledVal == INFLATED ? INFLATED_BIGINT : null,
1312
unscaledVal, scale, prec);
1313
}
1314
1315
static BigDecimal valueOf(BigInteger intVal, int scale, int prec) {
1316
long val = compactValFor(intVal);
1317
if (val == 0) {
1318
return zeroValueOf(scale);
1319
} else if (scale == 0 && val >= 0 && val < ZERO_THROUGH_TEN.length) {
1320
return ZERO_THROUGH_TEN[(int) val];
1321
}
1322
return new BigDecimal(intVal, val, scale, prec);
1323
}
1324
1325
static BigDecimal zeroValueOf(int scale) {
1326
if (scale >= 0 && scale < ZERO_SCALED_BY.length)
1327
return ZERO_SCALED_BY[scale];
1328
else
1329
return new BigDecimal(BigInteger.ZERO, 0, scale, 1);
1330
}
1331
1332
/**
1333
* Translates a {@code double} into a {@code BigDecimal}, using
1334
* the {@code double}'s canonical string representation provided
1335
* by the {@link Double#toString(double)} method.
1336
*
1337
* @apiNote This is generally the preferred way to convert a
1338
* {@code double} (or {@code float}) into a {@code BigDecimal}, as
1339
* the value returned is equal to that resulting from constructing
1340
* a {@code BigDecimal} from the result of using {@link
1341
* Double#toString(double)}.
1342
*
1343
* @param val {@code double} to convert to a {@code BigDecimal}.
1344
* @return a {@code BigDecimal} whose value is equal to or approximately
1345
* equal to the value of {@code val}.
1346
* @throws NumberFormatException if {@code val} is infinite or NaN.
1347
* @since 1.5
1348
*/
1349
public static BigDecimal valueOf(double val) {
1350
// Reminder: a zero double returns '0.0', so we cannot fastpath
1351
// to use the constant ZERO. This might be important enough to
1352
// justify a factory approach, a cache, or a few private
1353
// constants, later.
1354
return new BigDecimal(Double.toString(val));
1355
}
1356
1357
// Arithmetic Operations
1358
/**
1359
* Returns a {@code BigDecimal} whose value is {@code (this +
1360
* augend)}, and whose scale is {@code max(this.scale(),
1361
* augend.scale())}.
1362
*
1363
* @param augend value to be added to this {@code BigDecimal}.
1364
* @return {@code this + augend}
1365
*/
1366
public BigDecimal add(BigDecimal augend) {
1367
if (this.intCompact != INFLATED) {
1368
if ((augend.intCompact != INFLATED)) {
1369
return add(this.intCompact, this.scale, augend.intCompact, augend.scale);
1370
} else {
1371
return add(this.intCompact, this.scale, augend.intVal, augend.scale);
1372
}
1373
} else {
1374
if ((augend.intCompact != INFLATED)) {
1375
return add(augend.intCompact, augend.scale, this.intVal, this.scale);
1376
} else {
1377
return add(this.intVal, this.scale, augend.intVal, augend.scale);
1378
}
1379
}
1380
}
1381
1382
/**
1383
* Returns a {@code BigDecimal} whose value is {@code (this + augend)},
1384
* with rounding according to the context settings.
1385
*
1386
* If either number is zero and the precision setting is nonzero then
1387
* the other number, rounded if necessary, is used as the result.
1388
*
1389
* @param augend value to be added to this {@code BigDecimal}.
1390
* @param mc the context to use.
1391
* @return {@code this + augend}, rounded as necessary.
1392
* @since 1.5
1393
*/
1394
public BigDecimal add(BigDecimal augend, MathContext mc) {
1395
if (mc.precision == 0)
1396
return add(augend);
1397
BigDecimal lhs = this;
1398
1399
// If either number is zero then the other number, rounded and
1400
// scaled if necessary, is used as the result.
1401
{
1402
boolean lhsIsZero = lhs.signum() == 0;
1403
boolean augendIsZero = augend.signum() == 0;
1404
1405
if (lhsIsZero || augendIsZero) {
1406
int preferredScale = Math.max(lhs.scale(), augend.scale());
1407
BigDecimal result;
1408
1409
if (lhsIsZero && augendIsZero)
1410
return zeroValueOf(preferredScale);
1411
result = lhsIsZero ? doRound(augend, mc) : doRound(lhs, mc);
1412
1413
if (result.scale() == preferredScale)
1414
return result;
1415
else if (result.scale() > preferredScale) {
1416
return stripZerosToMatchScale(result.intVal, result.intCompact, result.scale, preferredScale);
1417
} else { // result.scale < preferredScale
1418
int precisionDiff = mc.precision - result.precision();
1419
int scaleDiff = preferredScale - result.scale();
1420
1421
if (precisionDiff >= scaleDiff)
1422
return result.setScale(preferredScale); // can achieve target scale
1423
else
1424
return result.setScale(result.scale() + precisionDiff);
1425
}
1426
}
1427
}
1428
1429
long padding = (long) lhs.scale - augend.scale;
1430
if (padding != 0) { // scales differ; alignment needed
1431
BigDecimal arg[] = preAlign(lhs, augend, padding, mc);
1432
matchScale(arg);
1433
lhs = arg[0];
1434
augend = arg[1];
1435
}
1436
return doRound(lhs.inflated().add(augend.inflated()), lhs.scale, mc);
1437
}
1438
1439
/**
1440
* Returns an array of length two, the sum of whose entries is
1441
* equal to the rounded sum of the {@code BigDecimal} arguments.
1442
*
1443
* <p>If the digit positions of the arguments have a sufficient
1444
* gap between them, the value smaller in magnitude can be
1445
* condensed into a {@literal "sticky bit"} and the end result will
1446
* round the same way <em>if</em> the precision of the final
1447
* result does not include the high order digit of the small
1448
* magnitude operand.
1449
*
1450
* <p>Note that while strictly speaking this is an optimization,
1451
* it makes a much wider range of additions practical.
1452
*
1453
* <p>This corresponds to a pre-shift operation in a fixed
1454
* precision floating-point adder; this method is complicated by
1455
* variable precision of the result as determined by the
1456
* MathContext. A more nuanced operation could implement a
1457
* {@literal "right shift"} on the smaller magnitude operand so
1458
* that the number of digits of the smaller operand could be
1459
* reduced even though the significands partially overlapped.
1460
*/
1461
private BigDecimal[] preAlign(BigDecimal lhs, BigDecimal augend, long padding, MathContext mc) {
1462
assert padding != 0;
1463
BigDecimal big;
1464
BigDecimal small;
1465
1466
if (padding < 0) { // lhs is big; augend is small
1467
big = lhs;
1468
small = augend;
1469
} else { // lhs is small; augend is big
1470
big = augend;
1471
small = lhs;
1472
}
1473
1474
/*
1475
* This is the estimated scale of an ulp of the result; it assumes that
1476
* the result doesn't have a carry-out on a true add (e.g. 999 + 1 =>
1477
* 1000) or any subtractive cancellation on borrowing (e.g. 100 - 1.2 =>
1478
* 98.8)
1479
*/
1480
long estResultUlpScale = (long) big.scale - big.precision() + mc.precision;
1481
1482
/*
1483
* The low-order digit position of big is big.scale(). This
1484
* is true regardless of whether big has a positive or
1485
* negative scale. The high-order digit position of small is
1486
* small.scale - (small.precision() - 1). To do the full
1487
* condensation, the digit positions of big and small must be
1488
* disjoint *and* the digit positions of small should not be
1489
* directly visible in the result.
1490
*/
1491
long smallHighDigitPos = (long) small.scale - small.precision() + 1;
1492
if (smallHighDigitPos > big.scale + 2 && // big and small disjoint
1493
smallHighDigitPos > estResultUlpScale + 2) { // small digits not visible
1494
small = BigDecimal.valueOf(small.signum(), this.checkScale(Math.max(big.scale, estResultUlpScale) + 3));
1495
}
1496
1497
// Since addition is symmetric, preserving input order in
1498
// returned operands doesn't matter
1499
BigDecimal[] result = {big, small};
1500
return result;
1501
}
1502
1503
/**
1504
* Returns a {@code BigDecimal} whose value is {@code (this -
1505
* subtrahend)}, and whose scale is {@code max(this.scale(),
1506
* subtrahend.scale())}.
1507
*
1508
* @param subtrahend value to be subtracted from this {@code BigDecimal}.
1509
* @return {@code this - subtrahend}
1510
*/
1511
public BigDecimal subtract(BigDecimal subtrahend) {
1512
if (this.intCompact != INFLATED) {
1513
if ((subtrahend.intCompact != INFLATED)) {
1514
return add(this.intCompact, this.scale, -subtrahend.intCompact, subtrahend.scale);
1515
} else {
1516
return add(this.intCompact, this.scale, subtrahend.intVal.negate(), subtrahend.scale);
1517
}
1518
} else {
1519
if ((subtrahend.intCompact != INFLATED)) {
1520
// Pair of subtrahend values given before pair of
1521
// values from this BigDecimal to avoid need for
1522
// method overloading on the specialized add method
1523
return add(-subtrahend.intCompact, subtrahend.scale, this.intVal, this.scale);
1524
} else {
1525
return add(this.intVal, this.scale, subtrahend.intVal.negate(), subtrahend.scale);
1526
}
1527
}
1528
}
1529
1530
/**
1531
* Returns a {@code BigDecimal} whose value is {@code (this - subtrahend)},
1532
* with rounding according to the context settings.
1533
*
1534
* If {@code subtrahend} is zero then this, rounded if necessary, is used as the
1535
* result. If this is zero then the result is {@code subtrahend.negate(mc)}.
1536
*
1537
* @param subtrahend value to be subtracted from this {@code BigDecimal}.
1538
* @param mc the context to use.
1539
* @return {@code this - subtrahend}, rounded as necessary.
1540
* @since 1.5
1541
*/
1542
public BigDecimal subtract(BigDecimal subtrahend, MathContext mc) {
1543
if (mc.precision == 0)
1544
return subtract(subtrahend);
1545
// share the special rounding code in add()
1546
return add(subtrahend.negate(), mc);
1547
}
1548
1549
/**
1550
* Returns a {@code BigDecimal} whose value is <code>(this &times;
1551
* multiplicand)</code>, and whose scale is {@code (this.scale() +
1552
* multiplicand.scale())}.
1553
*
1554
* @param multiplicand value to be multiplied by this {@code BigDecimal}.
1555
* @return {@code this * multiplicand}
1556
*/
1557
public BigDecimal multiply(BigDecimal multiplicand) {
1558
int productScale = checkScale((long) scale + multiplicand.scale);
1559
if (this.intCompact != INFLATED) {
1560
if ((multiplicand.intCompact != INFLATED)) {
1561
return multiply(this.intCompact, multiplicand.intCompact, productScale);
1562
} else {
1563
return multiply(this.intCompact, multiplicand.intVal, productScale);
1564
}
1565
} else {
1566
if ((multiplicand.intCompact != INFLATED)) {
1567
return multiply(multiplicand.intCompact, this.intVal, productScale);
1568
} else {
1569
return multiply(this.intVal, multiplicand.intVal, productScale);
1570
}
1571
}
1572
}
1573
1574
/**
1575
* Returns a {@code BigDecimal} whose value is <code>(this &times;
1576
* multiplicand)</code>, with rounding according to the context settings.
1577
*
1578
* @param multiplicand value to be multiplied by this {@code BigDecimal}.
1579
* @param mc the context to use.
1580
* @return {@code this * multiplicand}, rounded as necessary.
1581
* @since 1.5
1582
*/
1583
public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) {
1584
if (mc.precision == 0)
1585
return multiply(multiplicand);
1586
int productScale = checkScale((long) scale + multiplicand.scale);
1587
if (this.intCompact != INFLATED) {
1588
if ((multiplicand.intCompact != INFLATED)) {
1589
return multiplyAndRound(this.intCompact, multiplicand.intCompact, productScale, mc);
1590
} else {
1591
return multiplyAndRound(this.intCompact, multiplicand.intVal, productScale, mc);
1592
}
1593
} else {
1594
if ((multiplicand.intCompact != INFLATED)) {
1595
return multiplyAndRound(multiplicand.intCompact, this.intVal, productScale, mc);
1596
} else {
1597
return multiplyAndRound(this.intVal, multiplicand.intVal, productScale, mc);
1598
}
1599
}
1600
}
1601
1602
/**
1603
* Returns a {@code BigDecimal} whose value is {@code (this /
1604
* divisor)}, and whose scale is as specified. If rounding must
1605
* be performed to generate a result with the specified scale, the
1606
* specified rounding mode is applied.
1607
*
1608
* @deprecated The method {@link #divide(BigDecimal, int, RoundingMode)}
1609
* should be used in preference to this legacy method.
1610
*
1611
* @param divisor value by which this {@code BigDecimal} is to be divided.
1612
* @param scale scale of the {@code BigDecimal} quotient to be returned.
1613
* @param roundingMode rounding mode to apply.
1614
* @return {@code this / divisor}
1615
* @throws ArithmeticException if {@code divisor} is zero,
1616
* {@code roundingMode==ROUND_UNNECESSARY} and
1617
* the specified scale is insufficient to represent the result
1618
* of the division exactly.
1619
* @throws IllegalArgumentException if {@code roundingMode} does not
1620
* represent a valid rounding mode.
1621
* @see #ROUND_UP
1622
* @see #ROUND_DOWN
1623
* @see #ROUND_CEILING
1624
* @see #ROUND_FLOOR
1625
* @see #ROUND_HALF_UP
1626
* @see #ROUND_HALF_DOWN
1627
* @see #ROUND_HALF_EVEN
1628
* @see #ROUND_UNNECESSARY
1629
*/
1630
@Deprecated(since="9")
1631
public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) {
1632
if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
1633
throw new IllegalArgumentException("Invalid rounding mode");
1634
if (this.intCompact != INFLATED) {
1635
if ((divisor.intCompact != INFLATED)) {
1636
return divide(this.intCompact, this.scale, divisor.intCompact, divisor.scale, scale, roundingMode);
1637
} else {
1638
return divide(this.intCompact, this.scale, divisor.intVal, divisor.scale, scale, roundingMode);
1639
}
1640
} else {
1641
if ((divisor.intCompact != INFLATED)) {
1642
return divide(this.intVal, this.scale, divisor.intCompact, divisor.scale, scale, roundingMode);
1643
} else {
1644
return divide(this.intVal, this.scale, divisor.intVal, divisor.scale, scale, roundingMode);
1645
}
1646
}
1647
}
1648
1649
/**
1650
* Returns a {@code BigDecimal} whose value is {@code (this /
1651
* divisor)}, and whose scale is as specified. If rounding must
1652
* be performed to generate a result with the specified scale, the
1653
* specified rounding mode is applied.
1654
*
1655
* @param divisor value by which this {@code BigDecimal} is to be divided.
1656
* @param scale scale of the {@code BigDecimal} quotient to be returned.
1657
* @param roundingMode rounding mode to apply.
1658
* @return {@code this / divisor}
1659
* @throws ArithmeticException if {@code divisor} is zero,
1660
* {@code roundingMode==RoundingMode.UNNECESSARY} and
1661
* the specified scale is insufficient to represent the result
1662
* of the division exactly.
1663
* @since 1.5
1664
*/
1665
public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) {
1666
return divide(divisor, scale, roundingMode.oldMode);
1667
}
1668
1669
/**
1670
* Returns a {@code BigDecimal} whose value is {@code (this /
1671
* divisor)}, and whose scale is {@code this.scale()}. If
1672
* rounding must be performed to generate a result with the given
1673
* scale, the specified rounding mode is applied.
1674
*
1675
* @deprecated The method {@link #divide(BigDecimal, RoundingMode)}
1676
* should be used in preference to this legacy method.
1677
*
1678
* @param divisor value by which this {@code BigDecimal} is to be divided.
1679
* @param roundingMode rounding mode to apply.
1680
* @return {@code this / divisor}
1681
* @throws ArithmeticException if {@code divisor==0}, or
1682
* {@code roundingMode==ROUND_UNNECESSARY} and
1683
* {@code this.scale()} is insufficient to represent the result
1684
* of the division exactly.
1685
* @throws IllegalArgumentException if {@code roundingMode} does not
1686
* represent a valid rounding mode.
1687
* @see #ROUND_UP
1688
* @see #ROUND_DOWN
1689
* @see #ROUND_CEILING
1690
* @see #ROUND_FLOOR
1691
* @see #ROUND_HALF_UP
1692
* @see #ROUND_HALF_DOWN
1693
* @see #ROUND_HALF_EVEN
1694
* @see #ROUND_UNNECESSARY
1695
*/
1696
@Deprecated(since="9")
1697
public BigDecimal divide(BigDecimal divisor, int roundingMode) {
1698
return this.divide(divisor, scale, roundingMode);
1699
}
1700
1701
/**
1702
* Returns a {@code BigDecimal} whose value is {@code (this /
1703
* divisor)}, and whose scale is {@code this.scale()}. If
1704
* rounding must be performed to generate a result with the given
1705
* scale, the specified rounding mode is applied.
1706
*
1707
* @param divisor value by which this {@code BigDecimal} is to be divided.
1708
* @param roundingMode rounding mode to apply.
1709
* @return {@code this / divisor}
1710
* @throws ArithmeticException if {@code divisor==0}, or
1711
* {@code roundingMode==RoundingMode.UNNECESSARY} and
1712
* {@code this.scale()} is insufficient to represent the result
1713
* of the division exactly.
1714
* @since 1.5
1715
*/
1716
public BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode) {
1717
return this.divide(divisor, scale, roundingMode.oldMode);
1718
}
1719
1720
/**
1721
* Returns a {@code BigDecimal} whose value is {@code (this /
1722
* divisor)}, and whose preferred scale is {@code (this.scale() -
1723
* divisor.scale())}; if the exact quotient cannot be
1724
* represented (because it has a non-terminating decimal
1725
* expansion) an {@code ArithmeticException} is thrown.
1726
*
1727
* @param divisor value by which this {@code BigDecimal} is to be divided.
1728
* @throws ArithmeticException if the exact quotient does not have a
1729
* terminating decimal expansion, including dividing by zero
1730
* @return {@code this / divisor}
1731
* @since 1.5
1732
* @author Joseph D. Darcy
1733
*/
1734
public BigDecimal divide(BigDecimal divisor) {
1735
/*
1736
* Handle zero cases first.
1737
*/
1738
if (divisor.signum() == 0) { // x/0
1739
if (this.signum() == 0) // 0/0
1740
throw new ArithmeticException("Division undefined"); // NaN
1741
throw new ArithmeticException("Division by zero");
1742
}
1743
1744
// Calculate preferred scale
1745
int preferredScale = saturateLong((long) this.scale - divisor.scale);
1746
1747
if (this.signum() == 0) // 0/y
1748
return zeroValueOf(preferredScale);
1749
else {
1750
/*
1751
* If the quotient this/divisor has a terminating decimal
1752
* expansion, the expansion can have no more than
1753
* (a.precision() + ceil(10*b.precision)/3) digits.
1754
* Therefore, create a MathContext object with this
1755
* precision and do a divide with the UNNECESSARY rounding
1756
* mode.
1757
*/
1758
MathContext mc = new MathContext( (int)Math.min(this.precision() +
1759
(long)Math.ceil(10.0*divisor.precision()/3.0),
1760
Integer.MAX_VALUE),
1761
RoundingMode.UNNECESSARY);
1762
BigDecimal quotient;
1763
try {
1764
quotient = this.divide(divisor, mc);
1765
} catch (ArithmeticException e) {
1766
throw new ArithmeticException("Non-terminating decimal expansion; " +
1767
"no exact representable decimal result.");
1768
}
1769
1770
int quotientScale = quotient.scale();
1771
1772
// divide(BigDecimal, mc) tries to adjust the quotient to
1773
// the desired one by removing trailing zeros; since the
1774
// exact divide method does not have an explicit digit
1775
// limit, we can add zeros too.
1776
if (preferredScale > quotientScale)
1777
return quotient.setScale(preferredScale, ROUND_UNNECESSARY);
1778
1779
return quotient;
1780
}
1781
}
1782
1783
/**
1784
* Returns a {@code BigDecimal} whose value is {@code (this /
1785
* divisor)}, with rounding according to the context settings.
1786
*
1787
* @param divisor value by which this {@code BigDecimal} is to be divided.
1788
* @param mc the context to use.
1789
* @return {@code this / divisor}, rounded as necessary.
1790
* @throws ArithmeticException if the result is inexact but the
1791
* rounding mode is {@code UNNECESSARY} or
1792
* {@code mc.precision == 0} and the quotient has a
1793
* non-terminating decimal expansion,including dividing by zero
1794
* @since 1.5
1795
*/
1796
public BigDecimal divide(BigDecimal divisor, MathContext mc) {
1797
int mcp = mc.precision;
1798
if (mcp == 0)
1799
return divide(divisor);
1800
1801
BigDecimal dividend = this;
1802
long preferredScale = (long)dividend.scale - divisor.scale;
1803
// Now calculate the answer. We use the existing
1804
// divide-and-round method, but as this rounds to scale we have
1805
// to normalize the values here to achieve the desired result.
1806
// For x/y we first handle y=0 and x=0, and then normalize x and
1807
// y to give x' and y' with the following constraints:
1808
// (a) 0.1 <= x' < 1
1809
// (b) x' <= y' < 10*x'
1810
// Dividing x'/y' with the required scale set to mc.precision then
1811
// will give a result in the range 0.1 to 1 rounded to exactly
1812
// the right number of digits (except in the case of a result of
1813
// 1.000... which can arise when x=y, or when rounding overflows
1814
// The 1.000... case will reduce properly to 1.
1815
if (divisor.signum() == 0) { // x/0
1816
if (dividend.signum() == 0) // 0/0
1817
throw new ArithmeticException("Division undefined"); // NaN
1818
throw new ArithmeticException("Division by zero");
1819
}
1820
if (dividend.signum() == 0) // 0/y
1821
return zeroValueOf(saturateLong(preferredScale));
1822
int xscale = dividend.precision();
1823
int yscale = divisor.precision();
1824
if(dividend.intCompact!=INFLATED) {
1825
if(divisor.intCompact!=INFLATED) {
1826
return divide(dividend.intCompact, xscale, divisor.intCompact, yscale, preferredScale, mc);
1827
} else {
1828
return divide(dividend.intCompact, xscale, divisor.intVal, yscale, preferredScale, mc);
1829
}
1830
} else {
1831
if(divisor.intCompact!=INFLATED) {
1832
return divide(dividend.intVal, xscale, divisor.intCompact, yscale, preferredScale, mc);
1833
} else {
1834
return divide(dividend.intVal, xscale, divisor.intVal, yscale, preferredScale, mc);
1835
}
1836
}
1837
}
1838
1839
/**
1840
* Returns a {@code BigDecimal} whose value is the integer part
1841
* of the quotient {@code (this / divisor)} rounded down. The
1842
* preferred scale of the result is {@code (this.scale() -
1843
* divisor.scale())}.
1844
*
1845
* @param divisor value by which this {@code BigDecimal} is to be divided.
1846
* @return The integer part of {@code this / divisor}.
1847
* @throws ArithmeticException if {@code divisor==0}
1848
* @since 1.5
1849
*/
1850
public BigDecimal divideToIntegralValue(BigDecimal divisor) {
1851
// Calculate preferred scale
1852
int preferredScale = saturateLong((long) this.scale - divisor.scale);
1853
if (this.compareMagnitude(divisor) < 0) {
1854
// much faster when this << divisor
1855
return zeroValueOf(preferredScale);
1856
}
1857
1858
if (this.signum() == 0 && divisor.signum() != 0)
1859
return this.setScale(preferredScale, ROUND_UNNECESSARY);
1860
1861
// Perform a divide with enough digits to round to a correct
1862
// integer value; then remove any fractional digits
1863
1864
int maxDigits = (int)Math.min(this.precision() +
1865
(long)Math.ceil(10.0*divisor.precision()/3.0) +
1866
Math.abs((long)this.scale() - divisor.scale()) + 2,
1867
Integer.MAX_VALUE);
1868
BigDecimal quotient = this.divide(divisor, new MathContext(maxDigits,
1869
RoundingMode.DOWN));
1870
if (quotient.scale > 0) {
1871
quotient = quotient.setScale(0, RoundingMode.DOWN);
1872
quotient = stripZerosToMatchScale(quotient.intVal, quotient.intCompact, quotient.scale, preferredScale);
1873
}
1874
1875
if (quotient.scale < preferredScale) {
1876
// pad with zeros if necessary
1877
quotient = quotient.setScale(preferredScale, ROUND_UNNECESSARY);
1878
}
1879
1880
return quotient;
1881
}
1882
1883
/**
1884
* Returns a {@code BigDecimal} whose value is the integer part
1885
* of {@code (this / divisor)}. Since the integer part of the
1886
* exact quotient does not depend on the rounding mode, the
1887
* rounding mode does not affect the values returned by this
1888
* method. The preferred scale of the result is
1889
* {@code (this.scale() - divisor.scale())}. An
1890
* {@code ArithmeticException} is thrown if the integer part of
1891
* the exact quotient needs more than {@code mc.precision}
1892
* digits.
1893
*
1894
* @param divisor value by which this {@code BigDecimal} is to be divided.
1895
* @param mc the context to use.
1896
* @return The integer part of {@code this / divisor}.
1897
* @throws ArithmeticException if {@code divisor==0}
1898
* @throws ArithmeticException if {@code mc.precision} {@literal >} 0 and the result
1899
* requires a precision of more than {@code mc.precision} digits.
1900
* @since 1.5
1901
* @author Joseph D. Darcy
1902
*/
1903
public BigDecimal divideToIntegralValue(BigDecimal divisor, MathContext mc) {
1904
if (mc.precision == 0 || // exact result
1905
(this.compareMagnitude(divisor) < 0)) // zero result
1906
return divideToIntegralValue(divisor);
1907
1908
// Calculate preferred scale
1909
int preferredScale = saturateLong((long)this.scale - divisor.scale);
1910
1911
/*
1912
* Perform a normal divide to mc.precision digits. If the
1913
* remainder has absolute value less than the divisor, the
1914
* integer portion of the quotient fits into mc.precision
1915
* digits. Next, remove any fractional digits from the
1916
* quotient and adjust the scale to the preferred value.
1917
*/
1918
BigDecimal result = this.divide(divisor, new MathContext(mc.precision, RoundingMode.DOWN));
1919
1920
if (result.scale() < 0) {
1921
/*
1922
* Result is an integer. See if quotient represents the
1923
* full integer portion of the exact quotient; if it does,
1924
* the computed remainder will be less than the divisor.
1925
*/
1926
BigDecimal product = result.multiply(divisor);
1927
// If the quotient is the full integer value,
1928
// |dividend-product| < |divisor|.
1929
if (this.subtract(product).compareMagnitude(divisor) >= 0) {
1930
throw new ArithmeticException("Division impossible");
1931
}
1932
} else if (result.scale() > 0) {
1933
/*
1934
* Integer portion of quotient will fit into precision
1935
* digits; recompute quotient to scale 0 to avoid double
1936
* rounding and then try to adjust, if necessary.
1937
*/
1938
result = result.setScale(0, RoundingMode.DOWN);
1939
}
1940
// else result.scale() == 0;
1941
1942
int precisionDiff;
1943
if ((preferredScale > result.scale()) &&
1944
(precisionDiff = mc.precision - result.precision()) > 0) {
1945
return result.setScale(result.scale() +
1946
Math.min(precisionDiff, preferredScale - result.scale) );
1947
} else {
1948
return stripZerosToMatchScale(result.intVal,result.intCompact,result.scale,preferredScale);
1949
}
1950
}
1951
1952
/**
1953
* Returns a {@code BigDecimal} whose value is {@code (this % divisor)}.
1954
*
1955
* <p>The remainder is given by
1956
* {@code this.subtract(this.divideToIntegralValue(divisor).multiply(divisor))}.
1957
* Note that this is <em>not</em> the modulo operation (the result can be
1958
* negative).
1959
*
1960
* @param divisor value by which this {@code BigDecimal} is to be divided.
1961
* @return {@code this % divisor}.
1962
* @throws ArithmeticException if {@code divisor==0}
1963
* @since 1.5
1964
*/
1965
public BigDecimal remainder(BigDecimal divisor) {
1966
BigDecimal divrem[] = this.divideAndRemainder(divisor);
1967
return divrem[1];
1968
}
1969
1970
1971
/**
1972
* Returns a {@code BigDecimal} whose value is {@code (this %
1973
* divisor)}, with rounding according to the context settings.
1974
* The {@code MathContext} settings affect the implicit divide
1975
* used to compute the remainder. The remainder computation
1976
* itself is by definition exact. Therefore, the remainder may
1977
* contain more than {@code mc.getPrecision()} digits.
1978
*
1979
* <p>The remainder is given by
1980
* {@code this.subtract(this.divideToIntegralValue(divisor,
1981
* mc).multiply(divisor))}. Note that this is not the modulo
1982
* operation (the result can be negative).
1983
*
1984
* @param divisor value by which this {@code BigDecimal} is to be divided.
1985
* @param mc the context to use.
1986
* @return {@code this % divisor}, rounded as necessary.
1987
* @throws ArithmeticException if {@code divisor==0}
1988
* @throws ArithmeticException if the result is inexact but the
1989
* rounding mode is {@code UNNECESSARY}, or {@code mc.precision}
1990
* {@literal >} 0 and the result of {@code this.divideToIntegralValue(divisor)} would
1991
* require a precision of more than {@code mc.precision} digits.
1992
* @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
1993
* @since 1.5
1994
*/
1995
public BigDecimal remainder(BigDecimal divisor, MathContext mc) {
1996
BigDecimal divrem[] = this.divideAndRemainder(divisor, mc);
1997
return divrem[1];
1998
}
1999
2000
/**
2001
* Returns a two-element {@code BigDecimal} array containing the
2002
* result of {@code divideToIntegralValue} followed by the result of
2003
* {@code remainder} on the two operands.
2004
*
2005
* <p>Note that if both the integer quotient and remainder are
2006
* needed, this method is faster than using the
2007
* {@code divideToIntegralValue} and {@code remainder} methods
2008
* separately because the division need only be carried out once.
2009
*
2010
* @param divisor value by which this {@code BigDecimal} is to be divided,
2011
* and the remainder computed.
2012
* @return a two element {@code BigDecimal} array: the quotient
2013
* (the result of {@code divideToIntegralValue}) is the initial element
2014
* and the remainder is the final element.
2015
* @throws ArithmeticException if {@code divisor==0}
2016
* @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
2017
* @see #remainder(java.math.BigDecimal, java.math.MathContext)
2018
* @since 1.5
2019
*/
2020
public BigDecimal[] divideAndRemainder(BigDecimal divisor) {
2021
// we use the identity x = i * y + r to determine r
2022
BigDecimal[] result = new BigDecimal[2];
2023
2024
result[0] = this.divideToIntegralValue(divisor);
2025
result[1] = this.subtract(result[0].multiply(divisor));
2026
return result;
2027
}
2028
2029
/**
2030
* Returns a two-element {@code BigDecimal} array containing the
2031
* result of {@code divideToIntegralValue} followed by the result of
2032
* {@code remainder} on the two operands calculated with rounding
2033
* according to the context settings.
2034
*
2035
* <p>Note that if both the integer quotient and remainder are
2036
* needed, this method is faster than using the
2037
* {@code divideToIntegralValue} and {@code remainder} methods
2038
* separately because the division need only be carried out once.
2039
*
2040
* @param divisor value by which this {@code BigDecimal} is to be divided,
2041
* and the remainder computed.
2042
* @param mc the context to use.
2043
* @return a two element {@code BigDecimal} array: the quotient
2044
* (the result of {@code divideToIntegralValue}) is the
2045
* initial element and the remainder is the final element.
2046
* @throws ArithmeticException if {@code divisor==0}
2047
* @throws ArithmeticException if the result is inexact but the
2048
* rounding mode is {@code UNNECESSARY}, or {@code mc.precision}
2049
* {@literal >} 0 and the result of {@code this.divideToIntegralValue(divisor)} would
2050
* require a precision of more than {@code mc.precision} digits.
2051
* @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
2052
* @see #remainder(java.math.BigDecimal, java.math.MathContext)
2053
* @since 1.5
2054
*/
2055
public BigDecimal[] divideAndRemainder(BigDecimal divisor, MathContext mc) {
2056
if (mc.precision == 0)
2057
return divideAndRemainder(divisor);
2058
2059
BigDecimal[] result = new BigDecimal[2];
2060
BigDecimal lhs = this;
2061
2062
result[0] = lhs.divideToIntegralValue(divisor, mc);
2063
result[1] = lhs.subtract(result[0].multiply(divisor));
2064
return result;
2065
}
2066
2067
/**
2068
* Returns an approximation to the square root of {@code this}
2069
* with rounding according to the context settings.
2070
*
2071
* <p>The preferred scale of the returned result is equal to
2072
* {@code this.scale()/2}. The value of the returned result is
2073
* always within one ulp of the exact decimal value for the
2074
* precision in question. If the rounding mode is {@link
2075
* RoundingMode#HALF_UP HALF_UP}, {@link RoundingMode#HALF_DOWN
2076
* HALF_DOWN}, or {@link RoundingMode#HALF_EVEN HALF_EVEN}, the
2077
* result is within one half an ulp of the exact decimal value.
2078
*
2079
* <p>Special case:
2080
* <ul>
2081
* <li> The square root of a number numerically equal to {@code
2082
* ZERO} is numerically equal to {@code ZERO} with a preferred
2083
* scale according to the general rule above. In particular, for
2084
* {@code ZERO}, {@code ZERO.sqrt(mc).equals(ZERO)} is true with
2085
* any {@code MathContext} as an argument.
2086
* </ul>
2087
*
2088
* @param mc the context to use.
2089
* @return the square root of {@code this}.
2090
* @throws ArithmeticException if {@code this} is less than zero.
2091
* @throws ArithmeticException if an exact result is requested
2092
* ({@code mc.getPrecision()==0}) and there is no finite decimal
2093
* expansion of the exact result
2094
* @throws ArithmeticException if
2095
* {@code (mc.getRoundingMode()==RoundingMode.UNNECESSARY}) and
2096
* the exact result cannot fit in {@code mc.getPrecision()}
2097
* digits.
2098
* @see BigInteger#sqrt()
2099
* @since 9
2100
*/
2101
public BigDecimal sqrt(MathContext mc) {
2102
int signum = signum();
2103
if (signum == 1) {
2104
/*
2105
* The following code draws on the algorithm presented in
2106
* "Properly Rounded Variable Precision Square Root," Hull and
2107
* Abrham, ACM Transactions on Mathematical Software, Vol 11,
2108
* No. 3, September 1985, Pages 229-237.
2109
*
2110
* The BigDecimal computational model differs from the one
2111
* presented in the paper in several ways: first BigDecimal
2112
* numbers aren't necessarily normalized, second many more
2113
* rounding modes are supported, including UNNECESSARY, and
2114
* exact results can be requested.
2115
*
2116
* The main steps of the algorithm below are as follows,
2117
* first argument reduce the value to the numerical range
2118
* [1, 10) using the following relations:
2119
*
2120
* x = y * 10 ^ exp
2121
* sqrt(x) = sqrt(y) * 10^(exp / 2) if exp is even
2122
* sqrt(x) = sqrt(y/10) * 10 ^((exp+1)/2) is exp is odd
2123
*
2124
* Then use Newton's iteration on the reduced value to compute
2125
* the numerical digits of the desired result.
2126
*
2127
* Finally, scale back to the desired exponent range and
2128
* perform any adjustment to get the preferred scale in the
2129
* representation.
2130
*/
2131
2132
// The code below favors relative simplicity over checking
2133
// for special cases that could run faster.
2134
2135
int preferredScale = this.scale()/2;
2136
BigDecimal zeroWithFinalPreferredScale = valueOf(0L, preferredScale);
2137
2138
// First phase of numerical normalization, strip trailing
2139
// zeros and check for even powers of 10.
2140
BigDecimal stripped = this.stripTrailingZeros();
2141
int strippedScale = stripped.scale();
2142
2143
// Numerically sqrt(10^2N) = 10^N
2144
if (stripped.isPowerOfTen() &&
2145
strippedScale % 2 == 0) {
2146
BigDecimal result = valueOf(1L, strippedScale/2);
2147
if (result.scale() != preferredScale) {
2148
// Adjust to requested precision and preferred
2149
// scale as appropriate.
2150
result = result.add(zeroWithFinalPreferredScale, mc);
2151
}
2152
return result;
2153
}
2154
2155
// After stripTrailingZeros, the representation is normalized as
2156
//
2157
// unscaledValue * 10^(-scale)
2158
//
2159
// where unscaledValue is an integer with the mimimum
2160
// precision for the cohort of the numerical value. To
2161
// allow binary floating-point hardware to be used to get
2162
// approximately a 15 digit approximation to the square
2163
// root, it is helpful to instead normalize this so that
2164
// the significand portion is to right of the decimal
2165
// point by roughly (scale() - precision() + 1).
2166
2167
// Now the precision / scale adjustment
2168
int scaleAdjust = 0;
2169
int scale = stripped.scale() - stripped.precision() + 1;
2170
if (scale % 2 == 0) {
2171
scaleAdjust = scale;
2172
} else {
2173
scaleAdjust = scale - 1;
2174
}
2175
2176
BigDecimal working = stripped.scaleByPowerOfTen(scaleAdjust);
2177
2178
assert // Verify 0.1 <= working < 10
2179
ONE_TENTH.compareTo(working) <= 0 && working.compareTo(TEN) < 0;
2180
2181
// Use good ole' Math.sqrt to get the initial guess for
2182
// the Newton iteration, good to at least 15 decimal
2183
// digits. This approach does incur the cost of a
2184
//
2185
// BigDecimal -> double -> BigDecimal
2186
//
2187
// conversion cycle, but it avoids the need for several
2188
// Newton iterations in BigDecimal arithmetic to get the
2189
// working answer to 15 digits of precision. If many fewer
2190
// than 15 digits were needed, it might be faster to do
2191
// the loop entirely in BigDecimal arithmetic.
2192
//
2193
// (A double value might have as many as 17 decimal
2194
// digits of precision; it depends on the relative density
2195
// of binary and decimal numbers at different regions of
2196
// the number line.)
2197
//
2198
// (It would be possible to check for certain special
2199
// cases to avoid doing any Newton iterations. For
2200
// example, if the BigDecimal -> double conversion was
2201
// known to be exact and the rounding mode had a
2202
// low-enough precision, the post-Newton rounding logic
2203
// could be applied directly.)
2204
2205
BigDecimal guess = new BigDecimal(Math.sqrt(working.doubleValue()));
2206
int guessPrecision = 15;
2207
int originalPrecision = mc.getPrecision();
2208
int targetPrecision;
2209
2210
// If an exact value is requested, it must only need about
2211
// half of the input digits to represent since multiplying
2212
// an N digit number by itself yield a 2N-1 digit or 2N
2213
// digit result.
2214
if (originalPrecision == 0) {
2215
targetPrecision = stripped.precision()/2 + 1;
2216
} else {
2217
/*
2218
* To avoid the need for post-Newton fix-up logic, in
2219
* the case of half-way rounding modes, double the
2220
* target precision so that the "2p + 2" property can
2221
* be relied on to accomplish the final rounding.
2222
*/
2223
switch (mc.getRoundingMode()) {
2224
case HALF_UP:
2225
case HALF_DOWN:
2226
case HALF_EVEN:
2227
targetPrecision = 2 * originalPrecision;
2228
if (targetPrecision < 0) // Overflow
2229
targetPrecision = Integer.MAX_VALUE - 2;
2230
break;
2231
2232
default:
2233
targetPrecision = originalPrecision;
2234
break;
2235
}
2236
}
2237
2238
// When setting the precision to use inside the Newton
2239
// iteration loop, take care to avoid the case where the
2240
// precision of the input exceeds the requested precision
2241
// and rounding the input value too soon.
2242
BigDecimal approx = guess;
2243
int workingPrecision = working.precision();
2244
do {
2245
int tmpPrecision = Math.max(Math.max(guessPrecision, targetPrecision + 2),
2246
workingPrecision);
2247
MathContext mcTmp = new MathContext(tmpPrecision, RoundingMode.HALF_EVEN);
2248
// approx = 0.5 * (approx + fraction / approx)
2249
approx = ONE_HALF.multiply(approx.add(working.divide(approx, mcTmp), mcTmp));
2250
guessPrecision *= 2;
2251
} while (guessPrecision < targetPrecision + 2);
2252
2253
BigDecimal result;
2254
RoundingMode targetRm = mc.getRoundingMode();
2255
if (targetRm == RoundingMode.UNNECESSARY || originalPrecision == 0) {
2256
RoundingMode tmpRm =
2257
(targetRm == RoundingMode.UNNECESSARY) ? RoundingMode.DOWN : targetRm;
2258
MathContext mcTmp = new MathContext(targetPrecision, tmpRm);
2259
result = approx.scaleByPowerOfTen(-scaleAdjust/2).round(mcTmp);
2260
2261
// If result*result != this numerically, the square
2262
// root isn't exact
2263
if (this.subtract(result.square()).compareTo(ZERO) != 0) {
2264
throw new ArithmeticException("Computed square root not exact.");
2265
}
2266
} else {
2267
result = approx.scaleByPowerOfTen(-scaleAdjust/2).round(mc);
2268
2269
switch (targetRm) {
2270
case DOWN:
2271
case FLOOR:
2272
// Check if too big
2273
if (result.square().compareTo(this) > 0) {
2274
BigDecimal ulp = result.ulp();
2275
// Adjust increment down in case of 1.0 = 10^0
2276
// since the next smaller number is only 1/10
2277
// as far way as the next larger at exponent
2278
// boundaries. Test approx and *not* result to
2279
// avoid having to detect an arbitrary power
2280
// of ten.
2281
if (approx.compareTo(ONE) == 0) {
2282
ulp = ulp.multiply(ONE_TENTH);
2283
}
2284
result = result.subtract(ulp);
2285
}
2286
break;
2287
2288
case UP:
2289
case CEILING:
2290
// Check if too small
2291
if (result.square().compareTo(this) < 0) {
2292
result = result.add(result.ulp());
2293
}
2294
break;
2295
2296
default:
2297
// No additional work, rely on "2p + 2" property
2298
// for correct rounding. Alternatively, could
2299
// instead run the Newton iteration to around p
2300
// digits and then do tests and fix-ups on the
2301
// rounded value. One possible set of tests and
2302
// fix-ups is given in the Hull and Abrham paper;
2303
// however, additional half-way cases can occur
2304
// for BigDecimal given the more varied
2305
// combinations of input and output precisions
2306
// supported.
2307
break;
2308
}
2309
2310
}
2311
2312
// Test numerical properties at full precision before any
2313
// scale adjustments.
2314
assert squareRootResultAssertions(result, mc);
2315
if (result.scale() != preferredScale) {
2316
// The preferred scale of an add is
2317
// max(addend.scale(), augend.scale()). Therefore, if
2318
// the scale of the result is first minimized using
2319
// stripTrailingZeros(), adding a zero of the
2320
// preferred scale rounding to the correct precision
2321
// will perform the proper scale vs precision
2322
// tradeoffs.
2323
result = result.stripTrailingZeros().
2324
add(zeroWithFinalPreferredScale,
2325
new MathContext(originalPrecision, RoundingMode.UNNECESSARY));
2326
}
2327
return result;
2328
} else {
2329
BigDecimal result = null;
2330
switch (signum) {
2331
case -1:
2332
throw new ArithmeticException("Attempted square root " +
2333
"of negative BigDecimal");
2334
case 0:
2335
result = valueOf(0L, scale()/2);
2336
assert squareRootResultAssertions(result, mc);
2337
return result;
2338
2339
default:
2340
throw new AssertionError("Bad value from signum");
2341
}
2342
}
2343
}
2344
2345
private BigDecimal square() {
2346
return this.multiply(this);
2347
}
2348
2349
private boolean isPowerOfTen() {
2350
return BigInteger.ONE.equals(this.unscaledValue());
2351
}
2352
2353
/**
2354
* For nonzero values, check numerical correctness properties of
2355
* the computed result for the chosen rounding mode.
2356
*
2357
* For the directed rounding modes:
2358
*
2359
* <ul>
2360
*
2361
* <li> For DOWN and FLOOR, result^2 must be {@code <=} the input
2362
* and (result+ulp)^2 must be {@code >} the input.
2363
*
2364
* <li>Conversely, for UP and CEIL, result^2 must be {@code >=}
2365
* the input and (result-ulp)^2 must be {@code <} the input.
2366
* </ul>
2367
*/
2368
private boolean squareRootResultAssertions(BigDecimal result, MathContext mc) {
2369
if (result.signum() == 0) {
2370
return squareRootZeroResultAssertions(result, mc);
2371
} else {
2372
RoundingMode rm = mc.getRoundingMode();
2373
BigDecimal ulp = result.ulp();
2374
BigDecimal neighborUp = result.add(ulp);
2375
// Make neighbor down accurate even for powers of ten
2376
if (result.isPowerOfTen()) {
2377
ulp = ulp.divide(TEN);
2378
}
2379
BigDecimal neighborDown = result.subtract(ulp);
2380
2381
// Both the starting value and result should be nonzero and positive.
2382
assert (result.signum() == 1 &&
2383
this.signum() == 1) :
2384
"Bad signum of this and/or its sqrt.";
2385
2386
switch (rm) {
2387
case DOWN:
2388
case FLOOR:
2389
assert
2390
result.square().compareTo(this) <= 0 &&
2391
neighborUp.square().compareTo(this) > 0:
2392
"Square of result out for bounds rounding " + rm;
2393
return true;
2394
2395
case UP:
2396
case CEILING:
2397
assert
2398
result.square().compareTo(this) >= 0 &&
2399
neighborDown.square().compareTo(this) < 0:
2400
"Square of result out for bounds rounding " + rm;
2401
return true;
2402
2403
2404
case HALF_DOWN:
2405
case HALF_EVEN:
2406
case HALF_UP:
2407
BigDecimal err = result.square().subtract(this).abs();
2408
BigDecimal errUp = neighborUp.square().subtract(this);
2409
BigDecimal errDown = this.subtract(neighborDown.square());
2410
// All error values should be positive so don't need to
2411
// compare absolute values.
2412
2413
int err_comp_errUp = err.compareTo(errUp);
2414
int err_comp_errDown = err.compareTo(errDown);
2415
2416
assert
2417
errUp.signum() == 1 &&
2418
errDown.signum() == 1 :
2419
"Errors of neighbors squared don't have correct signs";
2420
2421
// For breaking a half-way tie, the return value may
2422
// have a larger error than one of the neighbors. For
2423
// example, the square root of 2.25 to a precision of
2424
// 1 digit is either 1 or 2 depending on how the exact
2425
// value of 1.5 is rounded. If 2 is returned, it will
2426
// have a larger rounding error than its neighbor 1.
2427
assert
2428
err_comp_errUp <= 0 ||
2429
err_comp_errDown <= 0 :
2430
"Computed square root has larger error than neighbors for " + rm;
2431
2432
assert
2433
((err_comp_errUp == 0 ) ? err_comp_errDown < 0 : true) &&
2434
((err_comp_errDown == 0 ) ? err_comp_errUp < 0 : true) :
2435
"Incorrect error relationships";
2436
// && could check for digit conditions for ties too
2437
return true;
2438
2439
default: // Definition of UNNECESSARY already verified.
2440
return true;
2441
}
2442
}
2443
}
2444
2445
private boolean squareRootZeroResultAssertions(BigDecimal result, MathContext mc) {
2446
return this.compareTo(ZERO) == 0;
2447
}
2448
2449
/**
2450
* Returns a {@code BigDecimal} whose value is
2451
* <code>(this<sup>n</sup>)</code>, The power is computed exactly, to
2452
* unlimited precision.
2453
*
2454
* <p>The parameter {@code n} must be in the range 0 through
2455
* 999999999, inclusive. {@code ZERO.pow(0)} returns {@link
2456
* #ONE}.
2457
*
2458
* Note that future releases may expand the allowable exponent
2459
* range of this method.
2460
*
2461
* @param n power to raise this {@code BigDecimal} to.
2462
* @return <code>this<sup>n</sup></code>
2463
* @throws ArithmeticException if {@code n} is out of range.
2464
* @since 1.5
2465
*/
2466
public BigDecimal pow(int n) {
2467
if (n < 0 || n > 999999999)
2468
throw new ArithmeticException("Invalid operation");
2469
// No need to calculate pow(n) if result will over/underflow.
2470
// Don't attempt to support "supernormal" numbers.
2471
int newScale = checkScale((long)scale * n);
2472
return new BigDecimal(this.inflated().pow(n), newScale);
2473
}
2474
2475
2476
/**
2477
* Returns a {@code BigDecimal} whose value is
2478
* <code>(this<sup>n</sup>)</code>. The current implementation uses
2479
* the core algorithm defined in ANSI standard X3.274-1996 with
2480
* rounding according to the context settings. In general, the
2481
* returned numerical value is within two ulps of the exact
2482
* numerical value for the chosen precision. Note that future
2483
* releases may use a different algorithm with a decreased
2484
* allowable error bound and increased allowable exponent range.
2485
*
2486
* <p>The X3.274-1996 algorithm is:
2487
*
2488
* <ul>
2489
* <li> An {@code ArithmeticException} exception is thrown if
2490
* <ul>
2491
* <li>{@code abs(n) > 999999999}
2492
* <li>{@code mc.precision == 0} and {@code n < 0}
2493
* <li>{@code mc.precision > 0} and {@code n} has more than
2494
* {@code mc.precision} decimal digits
2495
* </ul>
2496
*
2497
* <li> if {@code n} is zero, {@link #ONE} is returned even if
2498
* {@code this} is zero, otherwise
2499
* <ul>
2500
* <li> if {@code n} is positive, the result is calculated via
2501
* the repeated squaring technique into a single accumulator.
2502
* The individual multiplications with the accumulator use the
2503
* same math context settings as in {@code mc} except for a
2504
* precision increased to {@code mc.precision + elength + 1}
2505
* where {@code elength} is the number of decimal digits in
2506
* {@code n}.
2507
*
2508
* <li> if {@code n} is negative, the result is calculated as if
2509
* {@code n} were positive; this value is then divided into one
2510
* using the working precision specified above.
2511
*
2512
* <li> The final value from either the positive or negative case
2513
* is then rounded to the destination precision.
2514
* </ul>
2515
* </ul>
2516
*
2517
* @param n power to raise this {@code BigDecimal} to.
2518
* @param mc the context to use.
2519
* @return <code>this<sup>n</sup></code> using the ANSI standard X3.274-1996
2520
* algorithm
2521
* @throws ArithmeticException if the result is inexact but the
2522
* rounding mode is {@code UNNECESSARY}, or {@code n} is out
2523
* of range.
2524
* @since 1.5
2525
*/
2526
public BigDecimal pow(int n, MathContext mc) {
2527
if (mc.precision == 0)
2528
return pow(n);
2529
if (n < -999999999 || n > 999999999)
2530
throw new ArithmeticException("Invalid operation");
2531
if (n == 0)
2532
return ONE; // x**0 == 1 in X3.274
2533
BigDecimal lhs = this;
2534
MathContext workmc = mc; // working settings
2535
int mag = Math.abs(n); // magnitude of n
2536
if (mc.precision > 0) {
2537
int elength = longDigitLength(mag); // length of n in digits
2538
if (elength > mc.precision) // X3.274 rule
2539
throw new ArithmeticException("Invalid operation");
2540
workmc = new MathContext(mc.precision + elength + 1,
2541
mc.roundingMode);
2542
}
2543
// ready to carry out power calculation...
2544
BigDecimal acc = ONE; // accumulator
2545
boolean seenbit = false; // set once we've seen a 1-bit
2546
for (int i=1;;i++) { // for each bit [top bit ignored]
2547
mag += mag; // shift left 1 bit
2548
if (mag < 0) { // top bit is set
2549
seenbit = true; // OK, we're off
2550
acc = acc.multiply(lhs, workmc); // acc=acc*x
2551
}
2552
if (i == 31)
2553
break; // that was the last bit
2554
if (seenbit)
2555
acc=acc.multiply(acc, workmc); // acc=acc*acc [square]
2556
// else (!seenbit) no point in squaring ONE
2557
}
2558
// if negative n, calculate the reciprocal using working precision
2559
if (n < 0) // [hence mc.precision>0]
2560
acc=ONE.divide(acc, workmc);
2561
// round to final precision and strip zeros
2562
return doRound(acc, mc);
2563
}
2564
2565
/**
2566
* Returns a {@code BigDecimal} whose value is the absolute value
2567
* of this {@code BigDecimal}, and whose scale is
2568
* {@code this.scale()}.
2569
*
2570
* @return {@code abs(this)}
2571
*/
2572
public BigDecimal abs() {
2573
return (signum() < 0 ? negate() : this);
2574
}
2575
2576
/**
2577
* Returns a {@code BigDecimal} whose value is the absolute value
2578
* of this {@code BigDecimal}, with rounding according to the
2579
* context settings.
2580
*
2581
* @param mc the context to use.
2582
* @return {@code abs(this)}, rounded as necessary.
2583
* @since 1.5
2584
*/
2585
public BigDecimal abs(MathContext mc) {
2586
return (signum() < 0 ? negate(mc) : plus(mc));
2587
}
2588
2589
/**
2590
* Returns a {@code BigDecimal} whose value is {@code (-this)},
2591
* and whose scale is {@code this.scale()}.
2592
*
2593
* @return {@code -this}.
2594
*/
2595
public BigDecimal negate() {
2596
if (intCompact == INFLATED) {
2597
return new BigDecimal(intVal.negate(), INFLATED, scale, precision);
2598
} else {
2599
return valueOf(-intCompact, scale, precision);
2600
}
2601
}
2602
2603
/**
2604
* Returns a {@code BigDecimal} whose value is {@code (-this)},
2605
* with rounding according to the context settings.
2606
*
2607
* @param mc the context to use.
2608
* @return {@code -this}, rounded as necessary.
2609
* @since 1.5
2610
*/
2611
public BigDecimal negate(MathContext mc) {
2612
return negate().plus(mc);
2613
}
2614
2615
/**
2616
* Returns a {@code BigDecimal} whose value is {@code (+this)}, and whose
2617
* scale is {@code this.scale()}.
2618
*
2619
* <p>This method, which simply returns this {@code BigDecimal}
2620
* is included for symmetry with the unary minus method {@link
2621
* #negate()}.
2622
*
2623
* @return {@code this}.
2624
* @see #negate()
2625
* @since 1.5
2626
*/
2627
public BigDecimal plus() {
2628
return this;
2629
}
2630
2631
/**
2632
* Returns a {@code BigDecimal} whose value is {@code (+this)},
2633
* with rounding according to the context settings.
2634
*
2635
* <p>The effect of this method is identical to that of the {@link
2636
* #round(MathContext)} method.
2637
*
2638
* @param mc the context to use.
2639
* @return {@code this}, rounded as necessary. A zero result will
2640
* have a scale of 0.
2641
* @see #round(MathContext)
2642
* @since 1.5
2643
*/
2644
public BigDecimal plus(MathContext mc) {
2645
if (mc.precision == 0) // no rounding please
2646
return this;
2647
return doRound(this, mc);
2648
}
2649
2650
/**
2651
* Returns the signum function of this {@code BigDecimal}.
2652
*
2653
* @return -1, 0, or 1 as the value of this {@code BigDecimal}
2654
* is negative, zero, or positive.
2655
*/
2656
public int signum() {
2657
return (intCompact != INFLATED)?
2658
Long.signum(intCompact):
2659
intVal.signum();
2660
}
2661
2662
/**
2663
* Returns the <i>scale</i> of this {@code BigDecimal}. If zero
2664
* or positive, the scale is the number of digits to the right of
2665
* the decimal point. If negative, the unscaled value of the
2666
* number is multiplied by ten to the power of the negation of the
2667
* scale. For example, a scale of {@code -3} means the unscaled
2668
* value is multiplied by 1000.
2669
*
2670
* @return the scale of this {@code BigDecimal}.
2671
*/
2672
public int scale() {
2673
return scale;
2674
}
2675
2676
/**
2677
* Returns the <i>precision</i> of this {@code BigDecimal}. (The
2678
* precision is the number of digits in the unscaled value.)
2679
*
2680
* <p>The precision of a zero value is 1.
2681
*
2682
* @return the precision of this {@code BigDecimal}.
2683
* @since 1.5
2684
*/
2685
public int precision() {
2686
int result = precision;
2687
if (result == 0) {
2688
long s = intCompact;
2689
if (s != INFLATED)
2690
result = longDigitLength(s);
2691
else
2692
result = bigDigitLength(intVal);
2693
precision = result;
2694
}
2695
return result;
2696
}
2697
2698
2699
/**
2700
* Returns a {@code BigInteger} whose value is the <i>unscaled
2701
* value</i> of this {@code BigDecimal}. (Computes <code>(this *
2702
* 10<sup>this.scale()</sup>)</code>.)
2703
*
2704
* @return the unscaled value of this {@code BigDecimal}.
2705
* @since 1.2
2706
*/
2707
public BigInteger unscaledValue() {
2708
return this.inflated();
2709
}
2710
2711
// Rounding Modes
2712
2713
/**
2714
* Rounding mode to round away from zero. Always increments the
2715
* digit prior to a nonzero discarded fraction. Note that this rounding
2716
* mode never decreases the magnitude of the calculated value.
2717
*
2718
* @deprecated Use {@link RoundingMode#UP} instead.
2719
*/
2720
@Deprecated(since="9")
2721
public static final int ROUND_UP = 0;
2722
2723
/**
2724
* Rounding mode to round towards zero. Never increments the digit
2725
* prior to a discarded fraction (i.e., truncates). Note that this
2726
* rounding mode never increases the magnitude of the calculated value.
2727
*
2728
* @deprecated Use {@link RoundingMode#DOWN} instead.
2729
*/
2730
@Deprecated(since="9")
2731
public static final int ROUND_DOWN = 1;
2732
2733
/**
2734
* Rounding mode to round towards positive infinity. If the
2735
* {@code BigDecimal} is positive, behaves as for
2736
* {@code ROUND_UP}; if negative, behaves as for
2737
* {@code ROUND_DOWN}. Note that this rounding mode never
2738
* decreases the calculated value.
2739
*
2740
* @deprecated Use {@link RoundingMode#CEILING} instead.
2741
*/
2742
@Deprecated(since="9")
2743
public static final int ROUND_CEILING = 2;
2744
2745
/**
2746
* Rounding mode to round towards negative infinity. If the
2747
* {@code BigDecimal} is positive, behave as for
2748
* {@code ROUND_DOWN}; if negative, behave as for
2749
* {@code ROUND_UP}. Note that this rounding mode never
2750
* increases the calculated value.
2751
*
2752
* @deprecated Use {@link RoundingMode#FLOOR} instead.
2753
*/
2754
@Deprecated(since="9")
2755
public static final int ROUND_FLOOR = 3;
2756
2757
/**
2758
* Rounding mode to round towards {@literal "nearest neighbor"}
2759
* unless both neighbors are equidistant, in which case round up.
2760
* Behaves as for {@code ROUND_UP} if the discarded fraction is
2761
* &ge; 0.5; otherwise, behaves as for {@code ROUND_DOWN}. Note
2762
* that this is the rounding mode that most of us were taught in
2763
* grade school.
2764
*
2765
* @deprecated Use {@link RoundingMode#HALF_UP} instead.
2766
*/
2767
@Deprecated(since="9")
2768
public static final int ROUND_HALF_UP = 4;
2769
2770
/**
2771
* Rounding mode to round towards {@literal "nearest neighbor"}
2772
* unless both neighbors are equidistant, in which case round
2773
* down. Behaves as for {@code ROUND_UP} if the discarded
2774
* fraction is {@literal >} 0.5; otherwise, behaves as for
2775
* {@code ROUND_DOWN}.
2776
*
2777
* @deprecated Use {@link RoundingMode#HALF_DOWN} instead.
2778
*/
2779
@Deprecated(since="9")
2780
public static final int ROUND_HALF_DOWN = 5;
2781
2782
/**
2783
* Rounding mode to round towards the {@literal "nearest neighbor"}
2784
* unless both neighbors are equidistant, in which case, round
2785
* towards the even neighbor. Behaves as for
2786
* {@code ROUND_HALF_UP} if the digit to the left of the
2787
* discarded fraction is odd; behaves as for
2788
* {@code ROUND_HALF_DOWN} if it's even. Note that this is the
2789
* rounding mode that minimizes cumulative error when applied
2790
* repeatedly over a sequence of calculations.
2791
*
2792
* @deprecated Use {@link RoundingMode#HALF_EVEN} instead.
2793
*/
2794
@Deprecated(since="9")
2795
public static final int ROUND_HALF_EVEN = 6;
2796
2797
/**
2798
* Rounding mode to assert that the requested operation has an exact
2799
* result, hence no rounding is necessary. If this rounding mode is
2800
* specified on an operation that yields an inexact result, an
2801
* {@code ArithmeticException} is thrown.
2802
*
2803
* @deprecated Use {@link RoundingMode#UNNECESSARY} instead.
2804
*/
2805
@Deprecated(since="9")
2806
public static final int ROUND_UNNECESSARY = 7;
2807
2808
2809
// Scaling/Rounding Operations
2810
2811
/**
2812
* Returns a {@code BigDecimal} rounded according to the
2813
* {@code MathContext} settings. If the precision setting is 0 then
2814
* no rounding takes place.
2815
*
2816
* <p>The effect of this method is identical to that of the
2817
* {@link #plus(MathContext)} method.
2818
*
2819
* @param mc the context to use.
2820
* @return a {@code BigDecimal} rounded according to the
2821
* {@code MathContext} settings.
2822
* @see #plus(MathContext)
2823
* @since 1.5
2824
*/
2825
public BigDecimal round(MathContext mc) {
2826
return plus(mc);
2827
}
2828
2829
/**
2830
* Returns a {@code BigDecimal} whose scale is the specified
2831
* value, and whose unscaled value is determined by multiplying or
2832
* dividing this {@code BigDecimal}'s unscaled value by the
2833
* appropriate power of ten to maintain its overall value. If the
2834
* scale is reduced by the operation, the unscaled value must be
2835
* divided (rather than multiplied), and the value may be changed;
2836
* in this case, the specified rounding mode is applied to the
2837
* division.
2838
*
2839
* @apiNote Since BigDecimal objects are immutable, calls of
2840
* this method do <em>not</em> result in the original object being
2841
* modified, contrary to the usual convention of having methods
2842
* named <code>set<i>X</i></code> mutate field <i>{@code X}</i>.
2843
* Instead, {@code setScale} returns an object with the proper
2844
* scale; the returned object may or may not be newly allocated.
2845
*
2846
* @param newScale scale of the {@code BigDecimal} value to be returned.
2847
* @param roundingMode The rounding mode to apply.
2848
* @return a {@code BigDecimal} whose scale is the specified value,
2849
* and whose unscaled value is determined by multiplying or
2850
* dividing this {@code BigDecimal}'s unscaled value by the
2851
* appropriate power of ten to maintain its overall value.
2852
* @throws ArithmeticException if {@code roundingMode==UNNECESSARY}
2853
* and the specified scaling operation would require
2854
* rounding.
2855
* @see RoundingMode
2856
* @since 1.5
2857
*/
2858
public BigDecimal setScale(int newScale, RoundingMode roundingMode) {
2859
return setScale(newScale, roundingMode.oldMode);
2860
}
2861
2862
/**
2863
* Returns a {@code BigDecimal} whose scale is the specified
2864
* value, and whose unscaled value is determined by multiplying or
2865
* dividing this {@code BigDecimal}'s unscaled value by the
2866
* appropriate power of ten to maintain its overall value. If the
2867
* scale is reduced by the operation, the unscaled value must be
2868
* divided (rather than multiplied), and the value may be changed;
2869
* in this case, the specified rounding mode is applied to the
2870
* division.
2871
*
2872
* @apiNote Since BigDecimal objects are immutable, calls of
2873
* this method do <em>not</em> result in the original object being
2874
* modified, contrary to the usual convention of having methods
2875
* named <code>set<i>X</i></code> mutate field <i>{@code X}</i>.
2876
* Instead, {@code setScale} returns an object with the proper
2877
* scale; the returned object may or may not be newly allocated.
2878
*
2879
* @deprecated The method {@link #setScale(int, RoundingMode)} should
2880
* be used in preference to this legacy method.
2881
*
2882
* @param newScale scale of the {@code BigDecimal} value to be returned.
2883
* @param roundingMode The rounding mode to apply.
2884
* @return a {@code BigDecimal} whose scale is the specified value,
2885
* and whose unscaled value is determined by multiplying or
2886
* dividing this {@code BigDecimal}'s unscaled value by the
2887
* appropriate power of ten to maintain its overall value.
2888
* @throws ArithmeticException if {@code roundingMode==ROUND_UNNECESSARY}
2889
* and the specified scaling operation would require
2890
* rounding.
2891
* @throws IllegalArgumentException if {@code roundingMode} does not
2892
* represent a valid rounding mode.
2893
* @see #ROUND_UP
2894
* @see #ROUND_DOWN
2895
* @see #ROUND_CEILING
2896
* @see #ROUND_FLOOR
2897
* @see #ROUND_HALF_UP
2898
* @see #ROUND_HALF_DOWN
2899
* @see #ROUND_HALF_EVEN
2900
* @see #ROUND_UNNECESSARY
2901
*/
2902
@Deprecated(since="9")
2903
public BigDecimal setScale(int newScale, int roundingMode) {
2904
if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
2905
throw new IllegalArgumentException("Invalid rounding mode");
2906
2907
int oldScale = this.scale;
2908
if (newScale == oldScale) // easy case
2909
return this;
2910
if (this.signum() == 0) // zero can have any scale
2911
return zeroValueOf(newScale);
2912
if(this.intCompact!=INFLATED) {
2913
long rs = this.intCompact;
2914
if (newScale > oldScale) {
2915
int raise = checkScale((long) newScale - oldScale);
2916
if ((rs = longMultiplyPowerTen(rs, raise)) != INFLATED) {
2917
return valueOf(rs,newScale);
2918
}
2919
BigInteger rb = bigMultiplyPowerTen(raise);
2920
return new BigDecimal(rb, INFLATED, newScale, (precision > 0) ? precision + raise : 0);
2921
} else {
2922
// newScale < oldScale -- drop some digits
2923
// Can't predict the precision due to the effect of rounding.
2924
int drop = checkScale((long) oldScale - newScale);
2925
if (drop < LONG_TEN_POWERS_TABLE.length) {
2926
return divideAndRound(rs, LONG_TEN_POWERS_TABLE[drop], newScale, roundingMode, newScale);
2927
} else {
2928
return divideAndRound(this.inflated(), bigTenToThe(drop), newScale, roundingMode, newScale);
2929
}
2930
}
2931
} else {
2932
if (newScale > oldScale) {
2933
int raise = checkScale((long) newScale - oldScale);
2934
BigInteger rb = bigMultiplyPowerTen(this.intVal,raise);
2935
return new BigDecimal(rb, INFLATED, newScale, (precision > 0) ? precision + raise : 0);
2936
} else {
2937
// newScale < oldScale -- drop some digits
2938
// Can't predict the precision due to the effect of rounding.
2939
int drop = checkScale((long) oldScale - newScale);
2940
if (drop < LONG_TEN_POWERS_TABLE.length)
2941
return divideAndRound(this.intVal, LONG_TEN_POWERS_TABLE[drop], newScale, roundingMode,
2942
newScale);
2943
else
2944
return divideAndRound(this.intVal, bigTenToThe(drop), newScale, roundingMode, newScale);
2945
}
2946
}
2947
}
2948
2949
/**
2950
* Returns a {@code BigDecimal} whose scale is the specified
2951
* value, and whose value is numerically equal to this
2952
* {@code BigDecimal}'s. Throws an {@code ArithmeticException}
2953
* if this is not possible.
2954
*
2955
* <p>This call is typically used to increase the scale, in which
2956
* case it is guaranteed that there exists a {@code BigDecimal}
2957
* of the specified scale and the correct value. The call can
2958
* also be used to reduce the scale if the caller knows that the
2959
* {@code BigDecimal} has sufficiently many zeros at the end of
2960
* its fractional part (i.e., factors of ten in its integer value)
2961
* to allow for the rescaling without changing its value.
2962
*
2963
* <p>This method returns the same result as the two-argument
2964
* versions of {@code setScale}, but saves the caller the trouble
2965
* of specifying a rounding mode in cases where it is irrelevant.
2966
*
2967
* @apiNote Since {@code BigDecimal} objects are immutable,
2968
* calls of this method do <em>not</em> result in the original
2969
* object being modified, contrary to the usual convention of
2970
* having methods named <code>set<i>X</i></code> mutate field
2971
* <i>{@code X}</i>. Instead, {@code setScale} returns an
2972
* object with the proper scale; the returned object may or may
2973
* not be newly allocated.
2974
*
2975
* @param newScale scale of the {@code BigDecimal} value to be returned.
2976
* @return a {@code BigDecimal} whose scale is the specified value, and
2977
* whose unscaled value is determined by multiplying or dividing
2978
* this {@code BigDecimal}'s unscaled value by the appropriate
2979
* power of ten to maintain its overall value.
2980
* @throws ArithmeticException if the specified scaling operation would
2981
* require rounding.
2982
* @see #setScale(int, int)
2983
* @see #setScale(int, RoundingMode)
2984
*/
2985
public BigDecimal setScale(int newScale) {
2986
return setScale(newScale, ROUND_UNNECESSARY);
2987
}
2988
2989
// Decimal Point Motion Operations
2990
2991
/**
2992
* Returns a {@code BigDecimal} which is equivalent to this one
2993
* with the decimal point moved {@code n} places to the left. If
2994
* {@code n} is non-negative, the call merely adds {@code n} to
2995
* the scale. If {@code n} is negative, the call is equivalent
2996
* to {@code movePointRight(-n)}. The {@code BigDecimal}
2997
* returned by this call has value <code>(this &times;
2998
* 10<sup>-n</sup>)</code> and scale {@code max(this.scale()+n,
2999
* 0)}.
3000
*
3001
* @param n number of places to move the decimal point to the left.
3002
* @return a {@code BigDecimal} which is equivalent to this one with the
3003
* decimal point moved {@code n} places to the left.
3004
* @throws ArithmeticException if scale overflows.
3005
*/
3006
public BigDecimal movePointLeft(int n) {
3007
if (n == 0) return this;
3008
3009
// Cannot use movePointRight(-n) in case of n==Integer.MIN_VALUE
3010
int newScale = checkScale((long)scale + n);
3011
BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0);
3012
return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num;
3013
}
3014
3015
/**
3016
* Returns a {@code BigDecimal} which is equivalent to this one
3017
* with the decimal point moved {@code n} places to the right.
3018
* If {@code n} is non-negative, the call merely subtracts
3019
* {@code n} from the scale. If {@code n} is negative, the call
3020
* is equivalent to {@code movePointLeft(-n)}. The
3021
* {@code BigDecimal} returned by this call has value <code>(this
3022
* &times; 10<sup>n</sup>)</code> and scale {@code max(this.scale()-n,
3023
* 0)}.
3024
*
3025
* @param n number of places to move the decimal point to the right.
3026
* @return a {@code BigDecimal} which is equivalent to this one
3027
* with the decimal point moved {@code n} places to the right.
3028
* @throws ArithmeticException if scale overflows.
3029
*/
3030
public BigDecimal movePointRight(int n) {
3031
if (n == 0) return this;
3032
3033
// Cannot use movePointLeft(-n) in case of n==Integer.MIN_VALUE
3034
int newScale = checkScale((long)scale - n);
3035
BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0);
3036
return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num;
3037
}
3038
3039
/**
3040
* Returns a BigDecimal whose numerical value is equal to
3041
* ({@code this} * 10<sup>n</sup>). The scale of
3042
* the result is {@code (this.scale() - n)}.
3043
*
3044
* @param n the exponent power of ten to scale by
3045
* @return a BigDecimal whose numerical value is equal to
3046
* ({@code this} * 10<sup>n</sup>)
3047
* @throws ArithmeticException if the scale would be
3048
* outside the range of a 32-bit integer.
3049
*
3050
* @since 1.5
3051
*/
3052
public BigDecimal scaleByPowerOfTen(int n) {
3053
return new BigDecimal(intVal, intCompact,
3054
checkScale((long)scale - n), precision);
3055
}
3056
3057
/**
3058
* Returns a {@code BigDecimal} which is numerically equal to
3059
* this one but with any trailing zeros removed from the
3060
* representation. For example, stripping the trailing zeros from
3061
* the {@code BigDecimal} value {@code 600.0}, which has
3062
* [{@code BigInteger}, {@code scale}] components equal to
3063
* [6000, 1], yields {@code 6E2} with [{@code BigInteger},
3064
* {@code scale}] components equal to [6, -2]. If
3065
* this BigDecimal is numerically equal to zero, then
3066
* {@code BigDecimal.ZERO} is returned.
3067
*
3068
* @return a numerically equal {@code BigDecimal} with any
3069
* trailing zeros removed.
3070
* @throws ArithmeticException if scale overflows.
3071
* @since 1.5
3072
*/
3073
public BigDecimal stripTrailingZeros() {
3074
if (intCompact == 0 || (intVal != null && intVal.signum() == 0)) {
3075
return BigDecimal.ZERO;
3076
} else if (intCompact != INFLATED) {
3077
return createAndStripZerosToMatchScale(intCompact, scale, Long.MIN_VALUE);
3078
} else {
3079
return createAndStripZerosToMatchScale(intVal, scale, Long.MIN_VALUE);
3080
}
3081
}
3082
3083
// Comparison Operations
3084
3085
/**
3086
* Compares this {@code BigDecimal} numerically with the specified
3087
* {@code BigDecimal}. Two {@code BigDecimal} objects that are
3088
* equal in value but have a different scale (like 2.0 and 2.00)
3089
* are considered equal by this method. Such values are in the
3090
* same <i>cohort</i>.
3091
*
3092
* This method is provided in preference to individual methods for
3093
* each of the six boolean comparison operators ({@literal <}, ==,
3094
* {@literal >}, {@literal >=}, !=, {@literal <=}). The suggested
3095
* idiom for performing these comparisons is: {@code
3096
* (x.compareTo(y)} &lt;<i>op</i>&gt; {@code 0)}, where
3097
* &lt;<i>op</i>&gt; is one of the six comparison operators.
3098
3099
* @apiNote
3100
* Note: this class has a natural ordering that is inconsistent with equals.
3101
*
3102
* @param val {@code BigDecimal} to which this {@code BigDecimal} is
3103
* to be compared.
3104
* @return -1, 0, or 1 as this {@code BigDecimal} is numerically
3105
* less than, equal to, or greater than {@code val}.
3106
*/
3107
@Override
3108
public int compareTo(BigDecimal val) {
3109
// Quick path for equal scale and non-inflated case.
3110
if (scale == val.scale) {
3111
long xs = intCompact;
3112
long ys = val.intCompact;
3113
if (xs != INFLATED && ys != INFLATED)
3114
return xs != ys ? ((xs > ys) ? 1 : -1) : 0;
3115
}
3116
int xsign = this.signum();
3117
int ysign = val.signum();
3118
if (xsign != ysign)
3119
return (xsign > ysign) ? 1 : -1;
3120
if (xsign == 0)
3121
return 0;
3122
int cmp = compareMagnitude(val);
3123
return (xsign > 0) ? cmp : -cmp;
3124
}
3125
3126
/**
3127
* Version of compareTo that ignores sign.
3128
*/
3129
private int compareMagnitude(BigDecimal val) {
3130
// Match scales, avoid unnecessary inflation
3131
long ys = val.intCompact;
3132
long xs = this.intCompact;
3133
if (xs == 0)
3134
return (ys == 0) ? 0 : -1;
3135
if (ys == 0)
3136
return 1;
3137
3138
long sdiff = (long)this.scale - val.scale;
3139
if (sdiff != 0) {
3140
// Avoid matching scales if the (adjusted) exponents differ
3141
long xae = (long)this.precision() - this.scale; // [-1]
3142
long yae = (long)val.precision() - val.scale; // [-1]
3143
if (xae < yae)
3144
return -1;
3145
if (xae > yae)
3146
return 1;
3147
if (sdiff < 0) {
3148
// The cases sdiff <= Integer.MIN_VALUE intentionally fall through.
3149
if ( sdiff > Integer.MIN_VALUE &&
3150
(xs == INFLATED ||
3151
(xs = longMultiplyPowerTen(xs, (int)-sdiff)) == INFLATED) &&
3152
ys == INFLATED) {
3153
BigInteger rb = bigMultiplyPowerTen((int)-sdiff);
3154
return rb.compareMagnitude(val.intVal);
3155
}
3156
} else { // sdiff > 0
3157
// The cases sdiff > Integer.MAX_VALUE intentionally fall through.
3158
if ( sdiff <= Integer.MAX_VALUE &&
3159
(ys == INFLATED ||
3160
(ys = longMultiplyPowerTen(ys, (int)sdiff)) == INFLATED) &&
3161
xs == INFLATED) {
3162
BigInteger rb = val.bigMultiplyPowerTen((int)sdiff);
3163
return this.intVal.compareMagnitude(rb);
3164
}
3165
}
3166
}
3167
if (xs != INFLATED)
3168
return (ys != INFLATED) ? longCompareMagnitude(xs, ys) : -1;
3169
else if (ys != INFLATED)
3170
return 1;
3171
else
3172
return this.intVal.compareMagnitude(val.intVal);
3173
}
3174
3175
/**
3176
* Compares this {@code BigDecimal} with the specified {@code
3177
* Object} for equality. Unlike {@link #compareTo(BigDecimal)
3178
* compareTo}, this method considers two {@code BigDecimal}
3179
* objects equal only if they are equal in value and
3180
* scale. Therefore 2.0 is not equal to 2.00 when compared by this
3181
* method since the former has [{@code BigInteger}, {@code scale}]
3182
* components equal to [20, 1] while the latter has components
3183
* equal to [200, 2].
3184
*
3185
* @apiNote
3186
* One example that shows how 2.0 and 2.00 are <em>not</em>
3187
* substitutable for each other under some arithmetic operations
3188
* are the two expressions:<br>
3189
* {@code new BigDecimal("2.0" ).divide(BigDecimal.valueOf(3),
3190
* HALF_UP)} which evaluates to 0.7 and <br>
3191
* {@code new BigDecimal("2.00").divide(BigDecimal.valueOf(3),
3192
* HALF_UP)} which evaluates to 0.67.
3193
*
3194
* @param x {@code Object} to which this {@code BigDecimal} is
3195
* to be compared.
3196
* @return {@code true} if and only if the specified {@code Object} is a
3197
* {@code BigDecimal} whose value and scale are equal to this
3198
* {@code BigDecimal}'s.
3199
* @see #compareTo(java.math.BigDecimal)
3200
* @see #hashCode
3201
*/
3202
@Override
3203
public boolean equals(Object x) {
3204
if (!(x instanceof BigDecimal xDec))
3205
return false;
3206
if (x == this)
3207
return true;
3208
if (scale != xDec.scale)
3209
return false;
3210
long s = this.intCompact;
3211
long xs = xDec.intCompact;
3212
if (s != INFLATED) {
3213
if (xs == INFLATED)
3214
xs = compactValFor(xDec.intVal);
3215
return xs == s;
3216
} else if (xs != INFLATED)
3217
return xs == compactValFor(this.intVal);
3218
3219
return this.inflated().equals(xDec.inflated());
3220
}
3221
3222
/**
3223
* Returns the minimum of this {@code BigDecimal} and
3224
* {@code val}.
3225
*
3226
* @param val value with which the minimum is to be computed.
3227
* @return the {@code BigDecimal} whose value is the lesser of this
3228
* {@code BigDecimal} and {@code val}. If they are equal,
3229
* as defined by the {@link #compareTo(BigDecimal) compareTo}
3230
* method, {@code this} is returned.
3231
* @see #compareTo(java.math.BigDecimal)
3232
*/
3233
public BigDecimal min(BigDecimal val) {
3234
return (compareTo(val) <= 0 ? this : val);
3235
}
3236
3237
/**
3238
* Returns the maximum of this {@code BigDecimal} and {@code val}.
3239
*
3240
* @param val value with which the maximum is to be computed.
3241
* @return the {@code BigDecimal} whose value is the greater of this
3242
* {@code BigDecimal} and {@code val}. If they are equal,
3243
* as defined by the {@link #compareTo(BigDecimal) compareTo}
3244
* method, {@code this} is returned.
3245
* @see #compareTo(java.math.BigDecimal)
3246
*/
3247
public BigDecimal max(BigDecimal val) {
3248
return (compareTo(val) >= 0 ? this : val);
3249
}
3250
3251
// Hash Function
3252
3253
/**
3254
* Returns the hash code for this {@code BigDecimal}.
3255
* The hash code is computed as a function of the {@linkplain
3256
* unscaledValue() unscaled value} and the {@linkplain scale()
3257
* scale} of this {@code BigDecimal}.
3258
*
3259
* @apiNote
3260
* Two {@code BigDecimal} objects that are numerically equal but
3261
* differ in scale (like 2.0 and 2.00) will generally <em>not</em>
3262
* have the same hash code.
3263
*
3264
* @return hash code for this {@code BigDecimal}.
3265
* @see #equals(Object)
3266
*/
3267
@Override
3268
public int hashCode() {
3269
if (intCompact != INFLATED) {
3270
long val2 = (intCompact < 0)? -intCompact : intCompact;
3271
int temp = (int)( ((int)(val2 >>> 32)) * 31 +
3272
(val2 & LONG_MASK));
3273
return 31*((intCompact < 0) ?-temp:temp) + scale;
3274
} else
3275
return 31*intVal.hashCode() + scale;
3276
}
3277
3278
// Format Converters
3279
3280
/**
3281
* Returns the string representation of this {@code BigDecimal},
3282
* using scientific notation if an exponent is needed.
3283
*
3284
* <p>A standard canonical string form of the {@code BigDecimal}
3285
* is created as though by the following steps: first, the
3286
* absolute value of the unscaled value of the {@code BigDecimal}
3287
* is converted to a string in base ten using the characters
3288
* {@code '0'} through {@code '9'} with no leading zeros (except
3289
* if its value is zero, in which case a single {@code '0'}
3290
* character is used).
3291
*
3292
* <p>Next, an <i>adjusted exponent</i> is calculated; this is the
3293
* negated scale, plus the number of characters in the converted
3294
* unscaled value, less one. That is,
3295
* {@code -scale+(ulength-1)}, where {@code ulength} is the
3296
* length of the absolute value of the unscaled value in decimal
3297
* digits (its <i>precision</i>).
3298
*
3299
* <p>If the scale is greater than or equal to zero and the
3300
* adjusted exponent is greater than or equal to {@code -6}, the
3301
* number will be converted to a character form without using
3302
* exponential notation. In this case, if the scale is zero then
3303
* no decimal point is added and if the scale is positive a
3304
* decimal point will be inserted with the scale specifying the
3305
* number of characters to the right of the decimal point.
3306
* {@code '0'} characters are added to the left of the converted
3307
* unscaled value as necessary. If no character precedes the
3308
* decimal point after this insertion then a conventional
3309
* {@code '0'} character is prefixed.
3310
*
3311
* <p>Otherwise (that is, if the scale is negative, or the
3312
* adjusted exponent is less than {@code -6}), the number will be
3313
* converted to a character form using exponential notation. In
3314
* this case, if the converted {@code BigInteger} has more than
3315
* one digit a decimal point is inserted after the first digit.
3316
* An exponent in character form is then suffixed to the converted
3317
* unscaled value (perhaps with inserted decimal point); this
3318
* comprises the letter {@code 'E'} followed immediately by the
3319
* adjusted exponent converted to a character form. The latter is
3320
* in base ten, using the characters {@code '0'} through
3321
* {@code '9'} with no leading zeros, and is always prefixed by a
3322
* sign character {@code '-'} (<code>'&#92;u002D'</code>) if the
3323
* adjusted exponent is negative, {@code '+'}
3324
* (<code>'&#92;u002B'</code>) otherwise).
3325
*
3326
* <p>Finally, the entire string is prefixed by a minus sign
3327
* character {@code '-'} (<code>'&#92;u002D'</code>) if the unscaled
3328
* value is less than zero. No sign character is prefixed if the
3329
* unscaled value is zero or positive.
3330
*
3331
* <p><b>Examples:</b>
3332
* <p>For each representation [<i>unscaled value</i>, <i>scale</i>]
3333
* on the left, the resulting string is shown on the right.
3334
* <pre>
3335
* [123,0] "123"
3336
* [-123,0] "-123"
3337
* [123,-1] "1.23E+3"
3338
* [123,-3] "1.23E+5"
3339
* [123,1] "12.3"
3340
* [123,5] "0.00123"
3341
* [123,10] "1.23E-8"
3342
* [-123,12] "-1.23E-10"
3343
* </pre>
3344
*
3345
* <b>Notes:</b>
3346
* <ol>
3347
*
3348
* <li>There is a one-to-one mapping between the distinguishable
3349
* {@code BigDecimal} values and the result of this conversion.
3350
* That is, every distinguishable {@code BigDecimal} value
3351
* (unscaled value and scale) has a unique string representation
3352
* as a result of using {@code toString}. If that string
3353
* representation is converted back to a {@code BigDecimal} using
3354
* the {@link #BigDecimal(String)} constructor, then the original
3355
* value will be recovered.
3356
*
3357
* <li>The string produced for a given number is always the same;
3358
* it is not affected by locale. This means that it can be used
3359
* as a canonical string representation for exchanging decimal
3360
* data, or as a key for a Hashtable, etc. Locale-sensitive
3361
* number formatting and parsing is handled by the {@link
3362
* java.text.NumberFormat} class and its subclasses.
3363
*
3364
* <li>The {@link #toEngineeringString} method may be used for
3365
* presenting numbers with exponents in engineering notation, and the
3366
* {@link #setScale(int,RoundingMode) setScale} method may be used for
3367
* rounding a {@code BigDecimal} so it has a known number of digits after
3368
* the decimal point.
3369
*
3370
* <li>The digit-to-character mapping provided by
3371
* {@code Character.forDigit} is used.
3372
*
3373
* </ol>
3374
*
3375
* @return string representation of this {@code BigDecimal}.
3376
* @see Character#forDigit
3377
* @see #BigDecimal(java.lang.String)
3378
*/
3379
@Override
3380
public String toString() {
3381
String sc = stringCache;
3382
if (sc == null) {
3383
stringCache = sc = layoutChars(true);
3384
}
3385
return sc;
3386
}
3387
3388
/**
3389
* Returns a string representation of this {@code BigDecimal},
3390
* using engineering notation if an exponent is needed.
3391
*
3392
* <p>Returns a string that represents the {@code BigDecimal} as
3393
* described in the {@link #toString()} method, except that if
3394
* exponential notation is used, the power of ten is adjusted to
3395
* be a multiple of three (engineering notation) such that the
3396
* integer part of nonzero values will be in the range 1 through
3397
* 999. If exponential notation is used for zero values, a
3398
* decimal point and one or two fractional zero digits are used so
3399
* that the scale of the zero value is preserved. Note that
3400
* unlike the output of {@link #toString()}, the output of this
3401
* method is <em>not</em> guaranteed to recover the same [integer,
3402
* scale] pair of this {@code BigDecimal} if the output string is
3403
* converting back to a {@code BigDecimal} using the {@linkplain
3404
* #BigDecimal(String) string constructor}. The result of this method meets
3405
* the weaker constraint of always producing a numerically equal
3406
* result from applying the string constructor to the method's output.
3407
*
3408
* @return string representation of this {@code BigDecimal}, using
3409
* engineering notation if an exponent is needed.
3410
* @since 1.5
3411
*/
3412
public String toEngineeringString() {
3413
return layoutChars(false);
3414
}
3415
3416
/**
3417
* Returns a string representation of this {@code BigDecimal}
3418
* without an exponent field. For values with a positive scale,
3419
* the number of digits to the right of the decimal point is used
3420
* to indicate scale. For values with a zero or negative scale,
3421
* the resulting string is generated as if the value were
3422
* converted to a numerically equal value with zero scale and as
3423
* if all the trailing zeros of the zero scale value were present
3424
* in the result.
3425
*
3426
* The entire string is prefixed by a minus sign character '-'
3427
* (<code>'&#92;u002D'</code>) if the unscaled value is less than
3428
* zero. No sign character is prefixed if the unscaled value is
3429
* zero or positive.
3430
*
3431
* Note that if the result of this method is passed to the
3432
* {@linkplain #BigDecimal(String) string constructor}, only the
3433
* numerical value of this {@code BigDecimal} will necessarily be
3434
* recovered; the representation of the new {@code BigDecimal}
3435
* may have a different scale. In particular, if this
3436
* {@code BigDecimal} has a negative scale, the string resulting
3437
* from this method will have a scale of zero when processed by
3438
* the string constructor.
3439
*
3440
* (This method behaves analogously to the {@code toString}
3441
* method in 1.4 and earlier releases.)
3442
*
3443
* @return a string representation of this {@code BigDecimal}
3444
* without an exponent field.
3445
* @since 1.5
3446
* @see #toString()
3447
* @see #toEngineeringString()
3448
*/
3449
public String toPlainString() {
3450
if(scale==0) {
3451
if(intCompact!=INFLATED) {
3452
return Long.toString(intCompact);
3453
} else {
3454
return intVal.toString();
3455
}
3456
}
3457
if(this.scale<0) { // No decimal point
3458
if(signum()==0) {
3459
return "0";
3460
}
3461
int trailingZeros = checkScaleNonZero((-(long)scale));
3462
StringBuilder buf;
3463
if(intCompact!=INFLATED) {
3464
buf = new StringBuilder(20+trailingZeros);
3465
buf.append(intCompact);
3466
} else {
3467
String str = intVal.toString();
3468
buf = new StringBuilder(str.length()+trailingZeros);
3469
buf.append(str);
3470
}
3471
for (int i = 0; i < trailingZeros; i++) {
3472
buf.append('0');
3473
}
3474
return buf.toString();
3475
}
3476
String str ;
3477
if(intCompact!=INFLATED) {
3478
str = Long.toString(Math.abs(intCompact));
3479
} else {
3480
str = intVal.abs().toString();
3481
}
3482
return getValueString(signum(), str, scale);
3483
}
3484
3485
/* Returns a digit.digit string */
3486
private String getValueString(int signum, String intString, int scale) {
3487
/* Insert decimal point */
3488
StringBuilder buf;
3489
int insertionPoint = intString.length() - scale;
3490
if (insertionPoint == 0) { /* Point goes right before intVal */
3491
return (signum<0 ? "-0." : "0.") + intString;
3492
} else if (insertionPoint > 0) { /* Point goes inside intVal */
3493
buf = new StringBuilder(intString);
3494
buf.insert(insertionPoint, '.');
3495
if (signum < 0)
3496
buf.insert(0, '-');
3497
} else { /* We must insert zeros between point and intVal */
3498
buf = new StringBuilder(3-insertionPoint + intString.length());
3499
buf.append(signum<0 ? "-0." : "0.");
3500
for (int i=0; i<-insertionPoint; i++) {
3501
buf.append('0');
3502
}
3503
buf.append(intString);
3504
}
3505
return buf.toString();
3506
}
3507
3508
/**
3509
* Converts this {@code BigDecimal} to a {@code BigInteger}.
3510
* This conversion is analogous to the
3511
* <i>narrowing primitive conversion</i> from {@code double} to
3512
* {@code long} as defined in
3513
* <cite>The Java Language Specification</cite>:
3514
* any fractional part of this
3515
* {@code BigDecimal} will be discarded. Note that this
3516
* conversion can lose information about the precision of the
3517
* {@code BigDecimal} value.
3518
* <p>
3519
* To have an exception thrown if the conversion is inexact (in
3520
* other words if a nonzero fractional part is discarded), use the
3521
* {@link #toBigIntegerExact()} method.
3522
*
3523
* @return this {@code BigDecimal} converted to a {@code BigInteger}.
3524
* @jls 5.1.3 Narrowing Primitive Conversion
3525
*/
3526
public BigInteger toBigInteger() {
3527
// force to an integer, quietly
3528
return this.setScale(0, ROUND_DOWN).inflated();
3529
}
3530
3531
/**
3532
* Converts this {@code BigDecimal} to a {@code BigInteger},
3533
* checking for lost information. An exception is thrown if this
3534
* {@code BigDecimal} has a nonzero fractional part.
3535
*
3536
* @return this {@code BigDecimal} converted to a {@code BigInteger}.
3537
* @throws ArithmeticException if {@code this} has a nonzero
3538
* fractional part.
3539
* @since 1.5
3540
*/
3541
public BigInteger toBigIntegerExact() {
3542
// round to an integer, with Exception if decimal part non-0
3543
return this.setScale(0, ROUND_UNNECESSARY).inflated();
3544
}
3545
3546
/**
3547
* Converts this {@code BigDecimal} to a {@code long}.
3548
* This conversion is analogous to the
3549
* <i>narrowing primitive conversion</i> from {@code double} to
3550
* {@code short} as defined in
3551
* <cite>The Java Language Specification</cite>:
3552
* any fractional part of this
3553
* {@code BigDecimal} will be discarded, and if the resulting
3554
* "{@code BigInteger}" is too big to fit in a
3555
* {@code long}, only the low-order 64 bits are returned.
3556
* Note that this conversion can lose information about the
3557
* overall magnitude and precision of this {@code BigDecimal} value as well
3558
* as return a result with the opposite sign.
3559
*
3560
* @return this {@code BigDecimal} converted to a {@code long}.
3561
* @jls 5.1.3 Narrowing Primitive Conversion
3562
*/
3563
@Override
3564
public long longValue(){
3565
if (intCompact != INFLATED && scale == 0) {
3566
return intCompact;
3567
} else {
3568
// Fastpath zero and small values
3569
if (this.signum() == 0 || fractionOnly() ||
3570
// Fastpath very large-scale values that will result
3571
// in a truncated value of zero. If the scale is -64
3572
// or less, there are at least 64 powers of 10 in the
3573
// value of the numerical result. Since 10 = 2*5, in
3574
// that case there would also be 64 powers of 2 in the
3575
// result, meaning all 64 bits of a long will be zero.
3576
scale <= -64) {
3577
return 0;
3578
} else {
3579
return toBigInteger().longValue();
3580
}
3581
}
3582
}
3583
3584
/**
3585
* Return true if a nonzero BigDecimal has an absolute value less
3586
* than one; i.e. only has fraction digits.
3587
*/
3588
private boolean fractionOnly() {
3589
assert this.signum() != 0;
3590
return (this.precision() - this.scale) <= 0;
3591
}
3592
3593
/**
3594
* Converts this {@code BigDecimal} to a {@code long}, checking
3595
* for lost information. If this {@code BigDecimal} has a
3596
* nonzero fractional part or is out of the possible range for a
3597
* {@code long} result then an {@code ArithmeticException} is
3598
* thrown.
3599
*
3600
* @return this {@code BigDecimal} converted to a {@code long}.
3601
* @throws ArithmeticException if {@code this} has a nonzero
3602
* fractional part, or will not fit in a {@code long}.
3603
* @since 1.5
3604
*/
3605
public long longValueExact() {
3606
if (intCompact != INFLATED && scale == 0)
3607
return intCompact;
3608
3609
// Fastpath zero
3610
if (this.signum() == 0)
3611
return 0;
3612
3613
// Fastpath numbers less than 1.0 (the latter can be very slow
3614
// to round if very small)
3615
if (fractionOnly())
3616
throw new ArithmeticException("Rounding necessary");
3617
3618
// If more than 19 digits in integer part it cannot possibly fit
3619
if ((precision() - scale) > 19) // [OK for negative scale too]
3620
throw new java.lang.ArithmeticException("Overflow");
3621
3622
// round to an integer, with Exception if decimal part non-0
3623
BigDecimal num = this.setScale(0, ROUND_UNNECESSARY);
3624
if (num.precision() >= 19) // need to check carefully
3625
LongOverflow.check(num);
3626
return num.inflated().longValue();
3627
}
3628
3629
private static class LongOverflow {
3630
/** BigInteger equal to Long.MIN_VALUE. */
3631
private static final BigInteger LONGMIN = BigInteger.valueOf(Long.MIN_VALUE);
3632
3633
/** BigInteger equal to Long.MAX_VALUE. */
3634
private static final BigInteger LONGMAX = BigInteger.valueOf(Long.MAX_VALUE);
3635
3636
public static void check(BigDecimal num) {
3637
BigInteger intVal = num.inflated();
3638
if (intVal.compareTo(LONGMIN) < 0 ||
3639
intVal.compareTo(LONGMAX) > 0)
3640
throw new java.lang.ArithmeticException("Overflow");
3641
}
3642
}
3643
3644
/**
3645
* Converts this {@code BigDecimal} to an {@code int}.
3646
* This conversion is analogous to the
3647
* <i>narrowing primitive conversion</i> from {@code double} to
3648
* {@code short} as defined in
3649
* <cite>The Java Language Specification</cite>:
3650
* any fractional part of this
3651
* {@code BigDecimal} will be discarded, and if the resulting
3652
* "{@code BigInteger}" is too big to fit in an
3653
* {@code int}, only the low-order 32 bits are returned.
3654
* Note that this conversion can lose information about the
3655
* overall magnitude and precision of this {@code BigDecimal}
3656
* value as well as return a result with the opposite sign.
3657
*
3658
* @return this {@code BigDecimal} converted to an {@code int}.
3659
* @jls 5.1.3 Narrowing Primitive Conversion
3660
*/
3661
@Override
3662
public int intValue() {
3663
return (intCompact != INFLATED && scale == 0) ?
3664
(int)intCompact :
3665
(int)longValue();
3666
}
3667
3668
/**
3669
* Converts this {@code BigDecimal} to an {@code int}, checking
3670
* for lost information. If this {@code BigDecimal} has a
3671
* nonzero fractional part or is out of the possible range for an
3672
* {@code int} result then an {@code ArithmeticException} is
3673
* thrown.
3674
*
3675
* @return this {@code BigDecimal} converted to an {@code int}.
3676
* @throws ArithmeticException if {@code this} has a nonzero
3677
* fractional part, or will not fit in an {@code int}.
3678
* @since 1.5
3679
*/
3680
public int intValueExact() {
3681
long num;
3682
num = this.longValueExact(); // will check decimal part
3683
if ((int)num != num)
3684
throw new java.lang.ArithmeticException("Overflow");
3685
return (int)num;
3686
}
3687
3688
/**
3689
* Converts this {@code BigDecimal} to a {@code short}, checking
3690
* for lost information. If this {@code BigDecimal} has a
3691
* nonzero fractional part or is out of the possible range for a
3692
* {@code short} result then an {@code ArithmeticException} is
3693
* thrown.
3694
*
3695
* @return this {@code BigDecimal} converted to a {@code short}.
3696
* @throws ArithmeticException if {@code this} has a nonzero
3697
* fractional part, or will not fit in a {@code short}.
3698
* @since 1.5
3699
*/
3700
public short shortValueExact() {
3701
long num;
3702
num = this.longValueExact(); // will check decimal part
3703
if ((short)num != num)
3704
throw new java.lang.ArithmeticException("Overflow");
3705
return (short)num;
3706
}
3707
3708
/**
3709
* Converts this {@code BigDecimal} to a {@code byte}, checking
3710
* for lost information. If this {@code BigDecimal} has a
3711
* nonzero fractional part or is out of the possible range for a
3712
* {@code byte} result then an {@code ArithmeticException} is
3713
* thrown.
3714
*
3715
* @return this {@code BigDecimal} converted to a {@code byte}.
3716
* @throws ArithmeticException if {@code this} has a nonzero
3717
* fractional part, or will not fit in a {@code byte}.
3718
* @since 1.5
3719
*/
3720
public byte byteValueExact() {
3721
long num;
3722
num = this.longValueExact(); // will check decimal part
3723
if ((byte)num != num)
3724
throw new java.lang.ArithmeticException("Overflow");
3725
return (byte)num;
3726
}
3727
3728
/**
3729
* Converts this {@code BigDecimal} to a {@code float}.
3730
* This conversion is similar to the
3731
* <i>narrowing primitive conversion</i> from {@code double} to
3732
* {@code float} as defined in
3733
* <cite>The Java Language Specification</cite>:
3734
* if this {@code BigDecimal} has too great a
3735
* magnitude to represent as a {@code float}, it will be
3736
* converted to {@link Float#NEGATIVE_INFINITY} or {@link
3737
* Float#POSITIVE_INFINITY} as appropriate. Note that even when
3738
* the return value is finite, this conversion can lose
3739
* information about the precision of the {@code BigDecimal}
3740
* value.
3741
*
3742
* @return this {@code BigDecimal} converted to a {@code float}.
3743
* @jls 5.1.3 Narrowing Primitive Conversion
3744
*/
3745
@Override
3746
public float floatValue(){
3747
if(intCompact != INFLATED) {
3748
if (scale == 0) {
3749
return (float)intCompact;
3750
} else {
3751
/*
3752
* If both intCompact and the scale can be exactly
3753
* represented as float values, perform a single float
3754
* multiply or divide to compute the (properly
3755
* rounded) result.
3756
*/
3757
if (Math.abs(intCompact) < 1L<<22 ) {
3758
// Don't have too guard against
3759
// Math.abs(MIN_VALUE) because of outer check
3760
// against INFLATED.
3761
if (scale > 0 && scale < FLOAT_10_POW.length) {
3762
return (float)intCompact / FLOAT_10_POW[scale];
3763
} else if (scale < 0 && scale > -FLOAT_10_POW.length) {
3764
return (float)intCompact * FLOAT_10_POW[-scale];
3765
}
3766
}
3767
}
3768
}
3769
// Somewhat inefficient, but guaranteed to work.
3770
return Float.parseFloat(this.toString());
3771
}
3772
3773
/**
3774
* Converts this {@code BigDecimal} to a {@code double}.
3775
* This conversion is similar to the
3776
* <i>narrowing primitive conversion</i> from {@code double} to
3777
* {@code float} as defined in
3778
* <cite>The Java Language Specification</cite>:
3779
* if this {@code BigDecimal} has too great a
3780
* magnitude represent as a {@code double}, it will be
3781
* converted to {@link Double#NEGATIVE_INFINITY} or {@link
3782
* Double#POSITIVE_INFINITY} as appropriate. Note that even when
3783
* the return value is finite, this conversion can lose
3784
* information about the precision of the {@code BigDecimal}
3785
* value.
3786
*
3787
* @return this {@code BigDecimal} converted to a {@code double}.
3788
* @jls 5.1.3 Narrowing Primitive Conversion
3789
*/
3790
@Override
3791
public double doubleValue(){
3792
if(intCompact != INFLATED) {
3793
if (scale == 0) {
3794
return (double)intCompact;
3795
} else {
3796
/*
3797
* If both intCompact and the scale can be exactly
3798
* represented as double values, perform a single
3799
* double multiply or divide to compute the (properly
3800
* rounded) result.
3801
*/
3802
if (Math.abs(intCompact) < 1L<<52 ) {
3803
// Don't have too guard against
3804
// Math.abs(MIN_VALUE) because of outer check
3805
// against INFLATED.
3806
if (scale > 0 && scale < DOUBLE_10_POW.length) {
3807
return (double)intCompact / DOUBLE_10_POW[scale];
3808
} else if (scale < 0 && scale > -DOUBLE_10_POW.length) {
3809
return (double)intCompact * DOUBLE_10_POW[-scale];
3810
}
3811
}
3812
}
3813
}
3814
// Somewhat inefficient, but guaranteed to work.
3815
return Double.parseDouble(this.toString());
3816
}
3817
3818
/**
3819
* Powers of 10 which can be represented exactly in {@code
3820
* double}.
3821
*/
3822
private static final double DOUBLE_10_POW[] = {
3823
1.0e0, 1.0e1, 1.0e2, 1.0e3, 1.0e4, 1.0e5,
3824
1.0e6, 1.0e7, 1.0e8, 1.0e9, 1.0e10, 1.0e11,
3825
1.0e12, 1.0e13, 1.0e14, 1.0e15, 1.0e16, 1.0e17,
3826
1.0e18, 1.0e19, 1.0e20, 1.0e21, 1.0e22
3827
};
3828
3829
/**
3830
* Powers of 10 which can be represented exactly in {@code
3831
* float}.
3832
*/
3833
private static final float FLOAT_10_POW[] = {
3834
1.0e0f, 1.0e1f, 1.0e2f, 1.0e3f, 1.0e4f, 1.0e5f,
3835
1.0e6f, 1.0e7f, 1.0e8f, 1.0e9f, 1.0e10f
3836
};
3837
3838
/**
3839
* Returns the size of an ulp, a unit in the last place, of this
3840
* {@code BigDecimal}. An ulp of a nonzero {@code BigDecimal}
3841
* value is the positive distance between this value and the
3842
* {@code BigDecimal} value next larger in magnitude with the
3843
* same number of digits. An ulp of a zero value is numerically
3844
* equal to 1 with the scale of {@code this}. The result is
3845
* stored with the same scale as {@code this} so the result
3846
* for zero and nonzero values is equal to {@code [1,
3847
* this.scale()]}.
3848
*
3849
* @return the size of an ulp of {@code this}
3850
* @since 1.5
3851
*/
3852
public BigDecimal ulp() {
3853
return BigDecimal.valueOf(1, this.scale(), 1);
3854
}
3855
3856
// Private class to build a string representation for BigDecimal object. The
3857
// StringBuilder field acts as a buffer to hold the temporary representation
3858
// of BigDecimal. The cmpCharArray holds all the characters for the compact
3859
// representation of BigDecimal (except for '-' sign' if it is negative) if
3860
// its intCompact field is not INFLATED.
3861
static class StringBuilderHelper {
3862
final StringBuilder sb; // Placeholder for BigDecimal string
3863
final char[] cmpCharArray; // character array to place the intCompact
3864
3865
StringBuilderHelper() {
3866
sb = new StringBuilder(32);
3867
// All non negative longs can be made to fit into 19 character array.
3868
cmpCharArray = new char[19];
3869
}
3870
3871
// Accessors.
3872
StringBuilder getStringBuilder() {
3873
sb.setLength(0);
3874
return sb;
3875
}
3876
3877
char[] getCompactCharArray() {
3878
return cmpCharArray;
3879
}
3880
3881
/**
3882
* Places characters representing the intCompact in {@code long} into
3883
* cmpCharArray and returns the offset to the array where the
3884
* representation starts.
3885
*
3886
* @param intCompact the number to put into the cmpCharArray.
3887
* @return offset to the array where the representation starts.
3888
* Note: intCompact must be greater or equal to zero.
3889
*/
3890
int putIntCompact(long intCompact) {
3891
assert intCompact >= 0;
3892
3893
long q;
3894
int r;
3895
// since we start from the least significant digit, charPos points to
3896
// the last character in cmpCharArray.
3897
int charPos = cmpCharArray.length;
3898
3899
// Get 2 digits/iteration using longs until quotient fits into an int
3900
while (intCompact > Integer.MAX_VALUE) {
3901
q = intCompact / 100;
3902
r = (int)(intCompact - q * 100);
3903
intCompact = q;
3904
cmpCharArray[--charPos] = DIGIT_ONES[r];
3905
cmpCharArray[--charPos] = DIGIT_TENS[r];
3906
}
3907
3908
// Get 2 digits/iteration using ints when i2 >= 100
3909
int q2;
3910
int i2 = (int)intCompact;
3911
while (i2 >= 100) {
3912
q2 = i2 / 100;
3913
r = i2 - q2 * 100;
3914
i2 = q2;
3915
cmpCharArray[--charPos] = DIGIT_ONES[r];
3916
cmpCharArray[--charPos] = DIGIT_TENS[r];
3917
}
3918
3919
cmpCharArray[--charPos] = DIGIT_ONES[i2];
3920
if (i2 >= 10)
3921
cmpCharArray[--charPos] = DIGIT_TENS[i2];
3922
3923
return charPos;
3924
}
3925
3926
static final char[] DIGIT_TENS = {
3927
'0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
3928
'1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
3929
'2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
3930
'3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
3931
'4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
3932
'5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
3933
'6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
3934
'7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
3935
'8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
3936
'9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
3937
};
3938
3939
static final char[] DIGIT_ONES = {
3940
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3941
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3942
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3943
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3944
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3945
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3946
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3947
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3948
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3949
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3950
};
3951
}
3952
3953
/**
3954
* Lay out this {@code BigDecimal} into a {@code char[]} array.
3955
* The Java 1.2 equivalent to this was called {@code getValueString}.
3956
*
3957
* @param sci {@code true} for Scientific exponential notation;
3958
* {@code false} for Engineering
3959
* @return string with canonical string representation of this
3960
* {@code BigDecimal}
3961
*/
3962
private String layoutChars(boolean sci) {
3963
if (scale == 0) // zero scale is trivial
3964
return (intCompact != INFLATED) ?
3965
Long.toString(intCompact):
3966
intVal.toString();
3967
if (scale == 2 &&
3968
intCompact >= 0 && intCompact < Integer.MAX_VALUE) {
3969
// currency fast path
3970
int lowInt = (int)intCompact % 100;
3971
int highInt = (int)intCompact / 100;
3972
return (Integer.toString(highInt) + '.' +
3973
StringBuilderHelper.DIGIT_TENS[lowInt] +
3974
StringBuilderHelper.DIGIT_ONES[lowInt]) ;
3975
}
3976
3977
StringBuilderHelper sbHelper = new StringBuilderHelper();
3978
char[] coeff;
3979
int offset; // offset is the starting index for coeff array
3980
// Get the significand as an absolute value
3981
if (intCompact != INFLATED) {
3982
offset = sbHelper.putIntCompact(Math.abs(intCompact));
3983
coeff = sbHelper.getCompactCharArray();
3984
} else {
3985
offset = 0;
3986
coeff = intVal.abs().toString().toCharArray();
3987
}
3988
3989
// Construct a buffer, with sufficient capacity for all cases.
3990
// If E-notation is needed, length will be: +1 if negative, +1
3991
// if '.' needed, +2 for "E+", + up to 10 for adjusted exponent.
3992
// Otherwise it could have +1 if negative, plus leading "0.00000"
3993
StringBuilder buf = sbHelper.getStringBuilder();
3994
if (signum() < 0) // prefix '-' if negative
3995
buf.append('-');
3996
int coeffLen = coeff.length - offset;
3997
long adjusted = -(long)scale + (coeffLen -1);
3998
if ((scale >= 0) && (adjusted >= -6)) { // plain number
3999
int pad = scale - coeffLen; // count of padding zeros
4000
if (pad >= 0) { // 0.xxx form
4001
buf.append('0');
4002
buf.append('.');
4003
for (; pad>0; pad--) {
4004
buf.append('0');
4005
}
4006
buf.append(coeff, offset, coeffLen);
4007
} else { // xx.xx form
4008
buf.append(coeff, offset, -pad);
4009
buf.append('.');
4010
buf.append(coeff, -pad + offset, scale);
4011
}
4012
} else { // E-notation is needed
4013
if (sci) { // Scientific notation
4014
buf.append(coeff[offset]); // first character
4015
if (coeffLen > 1) { // more to come
4016
buf.append('.');
4017
buf.append(coeff, offset + 1, coeffLen - 1);
4018
}
4019
} else { // Engineering notation
4020
int sig = (int)(adjusted % 3);
4021
if (sig < 0)
4022
sig += 3; // [adjusted was negative]
4023
adjusted -= sig; // now a multiple of 3
4024
sig++;
4025
if (signum() == 0) {
4026
switch (sig) {
4027
case 1:
4028
buf.append('0'); // exponent is a multiple of three
4029
break;
4030
case 2:
4031
buf.append("0.00");
4032
adjusted += 3;
4033
break;
4034
case 3:
4035
buf.append("0.0");
4036
adjusted += 3;
4037
break;
4038
default:
4039
throw new AssertionError("Unexpected sig value " + sig);
4040
}
4041
} else if (sig >= coeffLen) { // significand all in integer
4042
buf.append(coeff, offset, coeffLen);
4043
// may need some zeros, too
4044
for (int i = sig - coeffLen; i > 0; i--) {
4045
buf.append('0');
4046
}
4047
} else { // xx.xxE form
4048
buf.append(coeff, offset, sig);
4049
buf.append('.');
4050
buf.append(coeff, offset + sig, coeffLen - sig);
4051
}
4052
}
4053
if (adjusted != 0) { // [!sci could have made 0]
4054
buf.append('E');
4055
if (adjusted > 0) // force sign for positive
4056
buf.append('+');
4057
buf.append(adjusted);
4058
}
4059
}
4060
return buf.toString();
4061
}
4062
4063
/**
4064
* Return 10 to the power n, as a {@code BigInteger}.
4065
*
4066
* @param n the power of ten to be returned (>=0)
4067
* @return a {@code BigInteger} with the value (10<sup>n</sup>)
4068
*/
4069
private static BigInteger bigTenToThe(int n) {
4070
if (n < 0)
4071
return BigInteger.ZERO;
4072
4073
if (n < BIG_TEN_POWERS_TABLE_MAX) {
4074
BigInteger[] pows = BIG_TEN_POWERS_TABLE;
4075
if (n < pows.length)
4076
return pows[n];
4077
else
4078
return expandBigIntegerTenPowers(n);
4079
}
4080
4081
return BigInteger.TEN.pow(n);
4082
}
4083
4084
/**
4085
* Expand the BIG_TEN_POWERS_TABLE array to contain at least 10**n.
4086
*
4087
* @param n the power of ten to be returned (>=0)
4088
* @return a {@code BigDecimal} with the value (10<sup>n</sup>) and
4089
* in the meantime, the BIG_TEN_POWERS_TABLE array gets
4090
* expanded to the size greater than n.
4091
*/
4092
private static BigInteger expandBigIntegerTenPowers(int n) {
4093
synchronized(BigDecimal.class) {
4094
BigInteger[] pows = BIG_TEN_POWERS_TABLE;
4095
int curLen = pows.length;
4096
// The following comparison and the above synchronized statement is
4097
// to prevent multiple threads from expanding the same array.
4098
if (curLen <= n) {
4099
int newLen = curLen << 1;
4100
while (newLen <= n) {
4101
newLen <<= 1;
4102
}
4103
pows = Arrays.copyOf(pows, newLen);
4104
for (int i = curLen; i < newLen; i++) {
4105
pows[i] = pows[i - 1].multiply(BigInteger.TEN);
4106
}
4107
// Based on the following facts:
4108
// 1. pows is a private local variable;
4109
// 2. the following store is a volatile store.
4110
// the newly created array elements can be safely published.
4111
BIG_TEN_POWERS_TABLE = pows;
4112
}
4113
return pows[n];
4114
}
4115
}
4116
4117
private static final long[] LONG_TEN_POWERS_TABLE = {
4118
1, // 0 / 10^0
4119
10, // 1 / 10^1
4120
100, // 2 / 10^2
4121
1000, // 3 / 10^3
4122
10000, // 4 / 10^4
4123
100000, // 5 / 10^5
4124
1000000, // 6 / 10^6
4125
10000000, // 7 / 10^7
4126
100000000, // 8 / 10^8
4127
1000000000, // 9 / 10^9
4128
10000000000L, // 10 / 10^10
4129
100000000000L, // 11 / 10^11
4130
1000000000000L, // 12 / 10^12
4131
10000000000000L, // 13 / 10^13
4132
100000000000000L, // 14 / 10^14
4133
1000000000000000L, // 15 / 10^15
4134
10000000000000000L, // 16 / 10^16
4135
100000000000000000L, // 17 / 10^17
4136
1000000000000000000L // 18 / 10^18
4137
};
4138
4139
private static volatile BigInteger BIG_TEN_POWERS_TABLE[] = {
4140
BigInteger.ONE,
4141
BigInteger.valueOf(10),
4142
BigInteger.valueOf(100),
4143
BigInteger.valueOf(1000),
4144
BigInteger.valueOf(10000),
4145
BigInteger.valueOf(100000),
4146
BigInteger.valueOf(1000000),
4147
BigInteger.valueOf(10000000),
4148
BigInteger.valueOf(100000000),
4149
BigInteger.valueOf(1000000000),
4150
BigInteger.valueOf(10000000000L),
4151
BigInteger.valueOf(100000000000L),
4152
BigInteger.valueOf(1000000000000L),
4153
BigInteger.valueOf(10000000000000L),
4154
BigInteger.valueOf(100000000000000L),
4155
BigInteger.valueOf(1000000000000000L),
4156
BigInteger.valueOf(10000000000000000L),
4157
BigInteger.valueOf(100000000000000000L),
4158
BigInteger.valueOf(1000000000000000000L)
4159
};
4160
4161
private static final int BIG_TEN_POWERS_TABLE_INITLEN =
4162
BIG_TEN_POWERS_TABLE.length;
4163
private static final int BIG_TEN_POWERS_TABLE_MAX =
4164
16 * BIG_TEN_POWERS_TABLE_INITLEN;
4165
4166
private static final long THRESHOLDS_TABLE[] = {
4167
Long.MAX_VALUE, // 0
4168
Long.MAX_VALUE/10L, // 1
4169
Long.MAX_VALUE/100L, // 2
4170
Long.MAX_VALUE/1000L, // 3
4171
Long.MAX_VALUE/10000L, // 4
4172
Long.MAX_VALUE/100000L, // 5
4173
Long.MAX_VALUE/1000000L, // 6
4174
Long.MAX_VALUE/10000000L, // 7
4175
Long.MAX_VALUE/100000000L, // 8
4176
Long.MAX_VALUE/1000000000L, // 9
4177
Long.MAX_VALUE/10000000000L, // 10
4178
Long.MAX_VALUE/100000000000L, // 11
4179
Long.MAX_VALUE/1000000000000L, // 12
4180
Long.MAX_VALUE/10000000000000L, // 13
4181
Long.MAX_VALUE/100000000000000L, // 14
4182
Long.MAX_VALUE/1000000000000000L, // 15
4183
Long.MAX_VALUE/10000000000000000L, // 16
4184
Long.MAX_VALUE/100000000000000000L, // 17
4185
Long.MAX_VALUE/1000000000000000000L // 18
4186
};
4187
4188
/**
4189
* Compute val * 10 ^ n; return this product if it is
4190
* representable as a long, INFLATED otherwise.
4191
*/
4192
private static long longMultiplyPowerTen(long val, int n) {
4193
if (val == 0 || n <= 0)
4194
return val;
4195
long[] tab = LONG_TEN_POWERS_TABLE;
4196
long[] bounds = THRESHOLDS_TABLE;
4197
if (n < tab.length && n < bounds.length) {
4198
long tenpower = tab[n];
4199
if (val == 1)
4200
return tenpower;
4201
if (Math.abs(val) <= bounds[n])
4202
return val * tenpower;
4203
}
4204
return INFLATED;
4205
}
4206
4207
/**
4208
* Compute this * 10 ^ n.
4209
* Needed mainly to allow special casing to trap zero value
4210
*/
4211
private BigInteger bigMultiplyPowerTen(int n) {
4212
if (n <= 0)
4213
return this.inflated();
4214
4215
if (intCompact != INFLATED)
4216
return bigTenToThe(n).multiply(intCompact);
4217
else
4218
return intVal.multiply(bigTenToThe(n));
4219
}
4220
4221
/**
4222
* Returns appropriate BigInteger from intVal field if intVal is
4223
* null, i.e. the compact representation is in use.
4224
*/
4225
private BigInteger inflated() {
4226
if (intVal == null) {
4227
return BigInteger.valueOf(intCompact);
4228
}
4229
return intVal;
4230
}
4231
4232
/**
4233
* Match the scales of two {@code BigDecimal}s to align their
4234
* least significant digits.
4235
*
4236
* <p>If the scales of val[0] and val[1] differ, rescale
4237
* (non-destructively) the lower-scaled {@code BigDecimal} so
4238
* they match. That is, the lower-scaled reference will be
4239
* replaced by a reference to a new object with the same scale as
4240
* the other {@code BigDecimal}.
4241
*
4242
* @param val array of two elements referring to the two
4243
* {@code BigDecimal}s to be aligned.
4244
*/
4245
private static void matchScale(BigDecimal[] val) {
4246
if (val[0].scale < val[1].scale) {
4247
val[0] = val[0].setScale(val[1].scale, ROUND_UNNECESSARY);
4248
} else if (val[1].scale < val[0].scale) {
4249
val[1] = val[1].setScale(val[0].scale, ROUND_UNNECESSARY);
4250
}
4251
}
4252
4253
private static class UnsafeHolder {
4254
private static final jdk.internal.misc.Unsafe unsafe
4255
= jdk.internal.misc.Unsafe.getUnsafe();
4256
private static final long intCompactOffset
4257
= unsafe.objectFieldOffset(BigDecimal.class, "intCompact");
4258
private static final long intValOffset
4259
= unsafe.objectFieldOffset(BigDecimal.class, "intVal");
4260
4261
static void setIntCompact(BigDecimal bd, long val) {
4262
unsafe.putLong(bd, intCompactOffset, val);
4263
}
4264
4265
static void setIntValVolatile(BigDecimal bd, BigInteger val) {
4266
unsafe.putReferenceVolatile(bd, intValOffset, val);
4267
}
4268
}
4269
4270
/**
4271
* Reconstitute the {@code BigDecimal} instance from a stream (that is,
4272
* deserialize it).
4273
*
4274
* @param s the stream being read.
4275
* @throws IOException if an I/O error occurs
4276
* @throws ClassNotFoundException if a serialized class cannot be loaded
4277
*/
4278
@java.io.Serial
4279
private void readObject(java.io.ObjectInputStream s)
4280
throws IOException, ClassNotFoundException {
4281
// Read in all fields
4282
s.defaultReadObject();
4283
// validate possibly bad fields
4284
if (intVal == null) {
4285
String message = "BigDecimal: null intVal in stream";
4286
throw new java.io.StreamCorruptedException(message);
4287
// [all values of scale are now allowed]
4288
}
4289
UnsafeHolder.setIntCompact(this, compactValFor(intVal));
4290
}
4291
4292
/**
4293
* Serialize this {@code BigDecimal} to the stream in question
4294
*
4295
* @param s the stream to serialize to.
4296
* @throws IOException if an I/O error occurs
4297
*/
4298
@java.io.Serial
4299
private void writeObject(java.io.ObjectOutputStream s)
4300
throws IOException {
4301
// Must inflate to maintain compatible serial form.
4302
if (this.intVal == null)
4303
UnsafeHolder.setIntValVolatile(this, BigInteger.valueOf(this.intCompact));
4304
// Could reset intVal back to null if it has to be set.
4305
s.defaultWriteObject();
4306
}
4307
4308
/**
4309
* Returns the length of the absolute value of a {@code long}, in decimal
4310
* digits.
4311
*
4312
* @param x the {@code long}
4313
* @return the length of the unscaled value, in deciaml digits.
4314
*/
4315
static int longDigitLength(long x) {
4316
/*
4317
* As described in "Bit Twiddling Hacks" by Sean Anderson,
4318
* (http://graphics.stanford.edu/~seander/bithacks.html)
4319
* integer log 10 of x is within 1 of (1233/4096)* (1 +
4320
* integer log 2 of x). The fraction 1233/4096 approximates
4321
* log10(2). So we first do a version of log2 (a variant of
4322
* Long class with pre-checks and opposite directionality) and
4323
* then scale and check against powers table. This is a little
4324
* simpler in present context than the version in Hacker's
4325
* Delight sec 11-4. Adding one to bit length allows comparing
4326
* downward from the LONG_TEN_POWERS_TABLE that we need
4327
* anyway.
4328
*/
4329
assert x != BigDecimal.INFLATED;
4330
if (x < 0)
4331
x = -x;
4332
if (x < 10) // must screen for 0, might as well 10
4333
return 1;
4334
int r = ((64 - Long.numberOfLeadingZeros(x) + 1) * 1233) >>> 12;
4335
long[] tab = LONG_TEN_POWERS_TABLE;
4336
// if r >= length, must have max possible digits for long
4337
return (r >= tab.length || x < tab[r]) ? r : r + 1;
4338
}
4339
4340
/**
4341
* Returns the length of the absolute value of a BigInteger, in
4342
* decimal digits.
4343
*
4344
* @param b the BigInteger
4345
* @return the length of the unscaled value, in decimal digits
4346
*/
4347
private static int bigDigitLength(BigInteger b) {
4348
/*
4349
* Same idea as the long version, but we need a better
4350
* approximation of log10(2). Using 646456993/2^31
4351
* is accurate up to max possible reported bitLength.
4352
*/
4353
if (b.signum == 0)
4354
return 1;
4355
int r = (int)((((long)b.bitLength() + 1) * 646456993) >>> 31);
4356
return b.compareMagnitude(bigTenToThe(r)) < 0? r : r+1;
4357
}
4358
4359
/**
4360
* Check a scale for Underflow or Overflow. If this BigDecimal is
4361
* nonzero, throw an exception if the scale is outof range. If this
4362
* is zero, saturate the scale to the extreme value of the right
4363
* sign if the scale is out of range.
4364
*
4365
* @param val The new scale.
4366
* @throws ArithmeticException (overflow or underflow) if the new
4367
* scale is out of range.
4368
* @return validated scale as an int.
4369
*/
4370
private int checkScale(long val) {
4371
int asInt = (int)val;
4372
if (asInt != val) {
4373
asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE;
4374
BigInteger b;
4375
if (intCompact != 0 &&
4376
((b = intVal) == null || b.signum() != 0))
4377
throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow");
4378
}
4379
return asInt;
4380
}
4381
4382
/**
4383
* Returns the compact value for given {@code BigInteger}, or
4384
* INFLATED if too big. Relies on internal representation of
4385
* {@code BigInteger}.
4386
*/
4387
private static long compactValFor(BigInteger b) {
4388
int[] m = b.mag;
4389
int len = m.length;
4390
if (len == 0)
4391
return 0;
4392
int d = m[0];
4393
if (len > 2 || (len == 2 && d < 0))
4394
return INFLATED;
4395
4396
long u = (len == 2)?
4397
(((long) m[1] & LONG_MASK) + (((long)d) << 32)) :
4398
(((long)d) & LONG_MASK);
4399
return (b.signum < 0)? -u : u;
4400
}
4401
4402
private static int longCompareMagnitude(long x, long y) {
4403
if (x < 0)
4404
x = -x;
4405
if (y < 0)
4406
y = -y;
4407
return (x < y) ? -1 : ((x == y) ? 0 : 1);
4408
}
4409
4410
private static int saturateLong(long s) {
4411
int i = (int)s;
4412
return (s == i) ? i : (s < 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE);
4413
}
4414
4415
/*
4416
* Internal printing routine
4417
*/
4418
private static void print(String name, BigDecimal bd) {
4419
System.err.format("%s:\tintCompact %d\tintVal %d\tscale %d\tprecision %d%n",
4420
name,
4421
bd.intCompact,
4422
bd.intVal,
4423
bd.scale,
4424
bd.precision);
4425
}
4426
4427
/**
4428
* Check internal invariants of this BigDecimal. These invariants
4429
* include:
4430
*
4431
* <ul>
4432
*
4433
* <li>The object must be initialized; either intCompact must not be
4434
* INFLATED or intVal is non-null. Both of these conditions may
4435
* be true.
4436
*
4437
* <li>If both intCompact and intVal and set, their values must be
4438
* consistent.
4439
*
4440
* <li>If precision is nonzero, it must have the right value.
4441
* </ul>
4442
*
4443
* Note: Since this is an audit method, we are not supposed to change the
4444
* state of this BigDecimal object.
4445
*/
4446
private BigDecimal audit() {
4447
if (intCompact == INFLATED) {
4448
if (intVal == null) {
4449
print("audit", this);
4450
throw new AssertionError("null intVal");
4451
}
4452
// Check precision
4453
if (precision > 0 && precision != bigDigitLength(intVal)) {
4454
print("audit", this);
4455
throw new AssertionError("precision mismatch");
4456
}
4457
} else {
4458
if (intVal != null) {
4459
long val = intVal.longValue();
4460
if (val != intCompact) {
4461
print("audit", this);
4462
throw new AssertionError("Inconsistent state, intCompact=" +
4463
intCompact + "\t intVal=" + val);
4464
}
4465
}
4466
// Check precision
4467
if (precision > 0 && precision != longDigitLength(intCompact)) {
4468
print("audit", this);
4469
throw new AssertionError("precision mismatch");
4470
}
4471
}
4472
return this;
4473
}
4474
4475
/* the same as checkScale where value!=0 */
4476
private static int checkScaleNonZero(long val) {
4477
int asInt = (int)val;
4478
if (asInt != val) {
4479
throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow");
4480
}
4481
return asInt;
4482
}
4483
4484
private static int checkScale(long intCompact, long val) {
4485
int asInt = (int)val;
4486
if (asInt != val) {
4487
asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE;
4488
if (intCompact != 0)
4489
throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow");
4490
}
4491
return asInt;
4492
}
4493
4494
private static int checkScale(BigInteger intVal, long val) {
4495
int asInt = (int)val;
4496
if (asInt != val) {
4497
asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE;
4498
if (intVal.signum() != 0)
4499
throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow");
4500
}
4501
return asInt;
4502
}
4503
4504
/**
4505
* Returns a {@code BigDecimal} rounded according to the MathContext
4506
* settings;
4507
* If rounding is needed a new {@code BigDecimal} is created and returned.
4508
*
4509
* @param val the value to be rounded
4510
* @param mc the context to use.
4511
* @return a {@code BigDecimal} rounded according to the MathContext
4512
* settings. May return {@code value}, if no rounding needed.
4513
* @throws ArithmeticException if the rounding mode is
4514
* {@code RoundingMode.UNNECESSARY} and the
4515
* result is inexact.
4516
*/
4517
private static BigDecimal doRound(BigDecimal val, MathContext mc) {
4518
int mcp = mc.precision;
4519
boolean wasDivided = false;
4520
if (mcp > 0) {
4521
BigInteger intVal = val.intVal;
4522
long compactVal = val.intCompact;
4523
int scale = val.scale;
4524
int prec = val.precision();
4525
int mode = mc.roundingMode.oldMode;
4526
int drop;
4527
if (compactVal == INFLATED) {
4528
drop = prec - mcp;
4529
while (drop > 0) {
4530
scale = checkScaleNonZero((long) scale - drop);
4531
intVal = divideAndRoundByTenPow(intVal, drop, mode);
4532
wasDivided = true;
4533
compactVal = compactValFor(intVal);
4534
if (compactVal != INFLATED) {
4535
prec = longDigitLength(compactVal);
4536
break;
4537
}
4538
prec = bigDigitLength(intVal);
4539
drop = prec - mcp;
4540
}
4541
}
4542
if (compactVal != INFLATED) {
4543
drop = prec - mcp; // drop can't be more than 18
4544
while (drop > 0) {
4545
scale = checkScaleNonZero((long) scale - drop);
4546
compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
4547
wasDivided = true;
4548
prec = longDigitLength(compactVal);
4549
drop = prec - mcp;
4550
intVal = null;
4551
}
4552
}
4553
return wasDivided ? new BigDecimal(intVal,compactVal,scale,prec) : val;
4554
}
4555
return val;
4556
}
4557
4558
/*
4559
* Returns a {@code BigDecimal} created from {@code long} value with
4560
* given scale rounded according to the MathContext settings
4561
*/
4562
private static BigDecimal doRound(long compactVal, int scale, MathContext mc) {
4563
int mcp = mc.precision;
4564
if (mcp > 0 && mcp < 19) {
4565
int prec = longDigitLength(compactVal);
4566
int drop = prec - mcp; // drop can't be more than 18
4567
while (drop > 0) {
4568
scale = checkScaleNonZero((long) scale - drop);
4569
compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
4570
prec = longDigitLength(compactVal);
4571
drop = prec - mcp;
4572
}
4573
return valueOf(compactVal, scale, prec);
4574
}
4575
return valueOf(compactVal, scale);
4576
}
4577
4578
/*
4579
* Returns a {@code BigDecimal} created from {@code BigInteger} value with
4580
* given scale rounded according to the MathContext settings
4581
*/
4582
private static BigDecimal doRound(BigInteger intVal, int scale, MathContext mc) {
4583
int mcp = mc.precision;
4584
int prec = 0;
4585
if (mcp > 0) {
4586
long compactVal = compactValFor(intVal);
4587
int mode = mc.roundingMode.oldMode;
4588
int drop;
4589
if (compactVal == INFLATED) {
4590
prec = bigDigitLength(intVal);
4591
drop = prec - mcp;
4592
while (drop > 0) {
4593
scale = checkScaleNonZero((long) scale - drop);
4594
intVal = divideAndRoundByTenPow(intVal, drop, mode);
4595
compactVal = compactValFor(intVal);
4596
if (compactVal != INFLATED) {
4597
break;
4598
}
4599
prec = bigDigitLength(intVal);
4600
drop = prec - mcp;
4601
}
4602
}
4603
if (compactVal != INFLATED) {
4604
prec = longDigitLength(compactVal);
4605
drop = prec - mcp; // drop can't be more than 18
4606
while (drop > 0) {
4607
scale = checkScaleNonZero((long) scale - drop);
4608
compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
4609
prec = longDigitLength(compactVal);
4610
drop = prec - mcp;
4611
}
4612
return valueOf(compactVal,scale,prec);
4613
}
4614
}
4615
return new BigDecimal(intVal,INFLATED,scale,prec);
4616
}
4617
4618
/*
4619
* Divides {@code BigInteger} value by ten power.
4620
*/
4621
private static BigInteger divideAndRoundByTenPow(BigInteger intVal, int tenPow, int roundingMode) {
4622
if (tenPow < LONG_TEN_POWERS_TABLE.length)
4623
intVal = divideAndRound(intVal, LONG_TEN_POWERS_TABLE[tenPow], roundingMode);
4624
else
4625
intVal = divideAndRound(intVal, bigTenToThe(tenPow), roundingMode);
4626
return intVal;
4627
}
4628
4629
/**
4630
* Internally used for division operation for division {@code long} by
4631
* {@code long}.
4632
* The returned {@code BigDecimal} object is the quotient whose scale is set
4633
* to the passed in scale. If the remainder is not zero, it will be rounded
4634
* based on the passed in roundingMode. Also, if the remainder is zero and
4635
* the last parameter, i.e. preferredScale is NOT equal to scale, the
4636
* trailing zeros of the result is stripped to match the preferredScale.
4637
*/
4638
private static BigDecimal divideAndRound(long ldividend, long ldivisor, int scale, int roundingMode,
4639
int preferredScale) {
4640
4641
int qsign; // quotient sign
4642
long q = ldividend / ldivisor; // store quotient in long
4643
if (roundingMode == ROUND_DOWN && scale == preferredScale)
4644
return valueOf(q, scale);
4645
long r = ldividend % ldivisor; // store remainder in long
4646
qsign = ((ldividend < 0) == (ldivisor < 0)) ? 1 : -1;
4647
if (r != 0) {
4648
boolean increment = needIncrement(ldivisor, roundingMode, qsign, q, r);
4649
return valueOf((increment ? q + qsign : q), scale);
4650
} else {
4651
if (preferredScale != scale)
4652
return createAndStripZerosToMatchScale(q, scale, preferredScale);
4653
else
4654
return valueOf(q, scale);
4655
}
4656
}
4657
4658
/**
4659
* Divides {@code long} by {@code long} and do rounding based on the
4660
* passed in roundingMode.
4661
*/
4662
private static long divideAndRound(long ldividend, long ldivisor, int roundingMode) {
4663
int qsign; // quotient sign
4664
long q = ldividend / ldivisor; // store quotient in long
4665
if (roundingMode == ROUND_DOWN)
4666
return q;
4667
long r = ldividend % ldivisor; // store remainder in long
4668
qsign = ((ldividend < 0) == (ldivisor < 0)) ? 1 : -1;
4669
if (r != 0) {
4670
boolean increment = needIncrement(ldivisor, roundingMode, qsign, q, r);
4671
return increment ? q + qsign : q;
4672
} else {
4673
return q;
4674
}
4675
}
4676
4677
/**
4678
* Shared logic of need increment computation.
4679
*/
4680
private static boolean commonNeedIncrement(int roundingMode, int qsign,
4681
int cmpFracHalf, boolean oddQuot) {
4682
switch(roundingMode) {
4683
case ROUND_UNNECESSARY:
4684
throw new ArithmeticException("Rounding necessary");
4685
4686
case ROUND_UP: // Away from zero
4687
return true;
4688
4689
case ROUND_DOWN: // Towards zero
4690
return false;
4691
4692
case ROUND_CEILING: // Towards +infinity
4693
return qsign > 0;
4694
4695
case ROUND_FLOOR: // Towards -infinity
4696
return qsign < 0;
4697
4698
default: // Some kind of half-way rounding
4699
assert roundingMode >= ROUND_HALF_UP &&
4700
roundingMode <= ROUND_HALF_EVEN: "Unexpected rounding mode" + RoundingMode.valueOf(roundingMode);
4701
4702
if (cmpFracHalf < 0 ) // We're closer to higher digit
4703
return false;
4704
else if (cmpFracHalf > 0 ) // We're closer to lower digit
4705
return true;
4706
else { // half-way
4707
assert cmpFracHalf == 0;
4708
4709
return switch (roundingMode) {
4710
case ROUND_HALF_DOWN -> false;
4711
case ROUND_HALF_UP -> true;
4712
case ROUND_HALF_EVEN -> oddQuot;
4713
4714
default -> throw new AssertionError("Unexpected rounding mode" + roundingMode);
4715
};
4716
}
4717
}
4718
}
4719
4720
/**
4721
* Tests if quotient has to be incremented according the roundingMode
4722
*/
4723
private static boolean needIncrement(long ldivisor, int roundingMode,
4724
int qsign, long q, long r) {
4725
assert r != 0L;
4726
4727
int cmpFracHalf;
4728
if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) {
4729
cmpFracHalf = 1; // 2 * r can't fit into long
4730
} else {
4731
cmpFracHalf = longCompareMagnitude(2 * r, ldivisor);
4732
}
4733
4734
return commonNeedIncrement(roundingMode, qsign, cmpFracHalf, (q & 1L) != 0L);
4735
}
4736
4737
/**
4738
* Divides {@code BigInteger} value by {@code long} value and
4739
* do rounding based on the passed in roundingMode.
4740
*/
4741
private static BigInteger divideAndRound(BigInteger bdividend, long ldivisor, int roundingMode) {
4742
// Descend into mutables for faster remainder checks
4743
MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);
4744
// store quotient
4745
MutableBigInteger mq = new MutableBigInteger();
4746
// store quotient & remainder in long
4747
long r = mdividend.divide(ldivisor, mq);
4748
// record remainder is zero or not
4749
boolean isRemainderZero = (r == 0);
4750
// quotient sign
4751
int qsign = (ldivisor < 0) ? -bdividend.signum : bdividend.signum;
4752
if (!isRemainderZero) {
4753
if(needIncrement(ldivisor, roundingMode, qsign, mq, r)) {
4754
mq.add(MutableBigInteger.ONE);
4755
}
4756
}
4757
return mq.toBigInteger(qsign);
4758
}
4759
4760
/**
4761
* Internally used for division operation for division {@code BigInteger}
4762
* by {@code long}.
4763
* The returned {@code BigDecimal} object is the quotient whose scale is set
4764
* to the passed in scale. If the remainder is not zero, it will be rounded
4765
* based on the passed in roundingMode. Also, if the remainder is zero and
4766
* the last parameter, i.e. preferredScale is NOT equal to scale, the
4767
* trailing zeros of the result is stripped to match the preferredScale.
4768
*/
4769
private static BigDecimal divideAndRound(BigInteger bdividend,
4770
long ldivisor, int scale, int roundingMode, int preferredScale) {
4771
// Descend into mutables for faster remainder checks
4772
MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);
4773
// store quotient
4774
MutableBigInteger mq = new MutableBigInteger();
4775
// store quotient & remainder in long
4776
long r = mdividend.divide(ldivisor, mq);
4777
// record remainder is zero or not
4778
boolean isRemainderZero = (r == 0);
4779
// quotient sign
4780
int qsign = (ldivisor < 0) ? -bdividend.signum : bdividend.signum;
4781
if (!isRemainderZero) {
4782
if(needIncrement(ldivisor, roundingMode, qsign, mq, r)) {
4783
mq.add(MutableBigInteger.ONE);
4784
}
4785
return mq.toBigDecimal(qsign, scale);
4786
} else {
4787
if (preferredScale != scale) {
4788
long compactVal = mq.toCompactValue(qsign);
4789
if(compactVal!=INFLATED) {
4790
return createAndStripZerosToMatchScale(compactVal, scale, preferredScale);
4791
}
4792
BigInteger intVal = mq.toBigInteger(qsign);
4793
return createAndStripZerosToMatchScale(intVal,scale, preferredScale);
4794
} else {
4795
return mq.toBigDecimal(qsign, scale);
4796
}
4797
}
4798
}
4799
4800
/**
4801
* Tests if quotient has to be incremented according the roundingMode
4802
*/
4803
private static boolean needIncrement(long ldivisor, int roundingMode,
4804
int qsign, MutableBigInteger mq, long r) {
4805
assert r != 0L;
4806
4807
int cmpFracHalf;
4808
if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) {
4809
cmpFracHalf = 1; // 2 * r can't fit into long
4810
} else {
4811
cmpFracHalf = longCompareMagnitude(2 * r, ldivisor);
4812
}
4813
4814
return commonNeedIncrement(roundingMode, qsign, cmpFracHalf, mq.isOdd());
4815
}
4816
4817
/**
4818
* Divides {@code BigInteger} value by {@code BigInteger} value and
4819
* do rounding based on the passed in roundingMode.
4820
*/
4821
private static BigInteger divideAndRound(BigInteger bdividend, BigInteger bdivisor, int roundingMode) {
4822
boolean isRemainderZero; // record remainder is zero or not
4823
int qsign; // quotient sign
4824
// Descend into mutables for faster remainder checks
4825
MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);
4826
MutableBigInteger mq = new MutableBigInteger();
4827
MutableBigInteger mdivisor = new MutableBigInteger(bdivisor.mag);
4828
MutableBigInteger mr = mdividend.divide(mdivisor, mq);
4829
isRemainderZero = mr.isZero();
4830
qsign = (bdividend.signum != bdivisor.signum) ? -1 : 1;
4831
if (!isRemainderZero) {
4832
if (needIncrement(mdivisor, roundingMode, qsign, mq, mr)) {
4833
mq.add(MutableBigInteger.ONE);
4834
}
4835
}
4836
return mq.toBigInteger(qsign);
4837
}
4838
4839
/**
4840
* Internally used for division operation for division {@code BigInteger}
4841
* by {@code BigInteger}.
4842
* The returned {@code BigDecimal} object is the quotient whose scale is set
4843
* to the passed in scale. If the remainder is not zero, it will be rounded
4844
* based on the passed in roundingMode. Also, if the remainder is zero and
4845
* the last parameter, i.e. preferredScale is NOT equal to scale, the
4846
* trailing zeros of the result is stripped to match the preferredScale.
4847
*/
4848
private static BigDecimal divideAndRound(BigInteger bdividend, BigInteger bdivisor, int scale, int roundingMode,
4849
int preferredScale) {
4850
boolean isRemainderZero; // record remainder is zero or not
4851
int qsign; // quotient sign
4852
// Descend into mutables for faster remainder checks
4853
MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);
4854
MutableBigInteger mq = new MutableBigInteger();
4855
MutableBigInteger mdivisor = new MutableBigInteger(bdivisor.mag);
4856
MutableBigInteger mr = mdividend.divide(mdivisor, mq);
4857
isRemainderZero = mr.isZero();
4858
qsign = (bdividend.signum != bdivisor.signum) ? -1 : 1;
4859
if (!isRemainderZero) {
4860
if (needIncrement(mdivisor, roundingMode, qsign, mq, mr)) {
4861
mq.add(MutableBigInteger.ONE);
4862
}
4863
return mq.toBigDecimal(qsign, scale);
4864
} else {
4865
if (preferredScale != scale) {
4866
long compactVal = mq.toCompactValue(qsign);
4867
if (compactVal != INFLATED) {
4868
return createAndStripZerosToMatchScale(compactVal, scale, preferredScale);
4869
}
4870
BigInteger intVal = mq.toBigInteger(qsign);
4871
return createAndStripZerosToMatchScale(intVal, scale, preferredScale);
4872
} else {
4873
return mq.toBigDecimal(qsign, scale);
4874
}
4875
}
4876
}
4877
4878
/**
4879
* Tests if quotient has to be incremented according the roundingMode
4880
*/
4881
private static boolean needIncrement(MutableBigInteger mdivisor, int roundingMode,
4882
int qsign, MutableBigInteger mq, MutableBigInteger mr) {
4883
assert !mr.isZero();
4884
int cmpFracHalf = mr.compareHalf(mdivisor);
4885
return commonNeedIncrement(roundingMode, qsign, cmpFracHalf, mq.isOdd());
4886
}
4887
4888
/**
4889
* Remove insignificant trailing zeros from this
4890
* {@code BigInteger} value until the preferred scale is reached or no
4891
* more zeros can be removed. If the preferred scale is less than
4892
* Integer.MIN_VALUE, all the trailing zeros will be removed.
4893
*
4894
* @return new {@code BigDecimal} with a scale possibly reduced
4895
* to be closed to the preferred scale.
4896
* @throws ArithmeticException if scale overflows.
4897
*/
4898
private static BigDecimal createAndStripZerosToMatchScale(BigInteger intVal, int scale, long preferredScale) {
4899
BigInteger qr[]; // quotient-remainder pair
4900
while (intVal.compareMagnitude(BigInteger.TEN) >= 0
4901
&& scale > preferredScale) {
4902
if (intVal.testBit(0))
4903
break; // odd number cannot end in 0
4904
qr = intVal.divideAndRemainder(BigInteger.TEN);
4905
if (qr[1].signum() != 0)
4906
break; // non-0 remainder
4907
intVal = qr[0];
4908
scale = checkScale(intVal,(long) scale - 1); // could Overflow
4909
}
4910
return valueOf(intVal, scale, 0);
4911
}
4912
4913
/**
4914
* Remove insignificant trailing zeros from this
4915
* {@code long} value until the preferred scale is reached or no
4916
* more zeros can be removed. If the preferred scale is less than
4917
* Integer.MIN_VALUE, all the trailing zeros will be removed.
4918
*
4919
* @return new {@code BigDecimal} with a scale possibly reduced
4920
* to be closed to the preferred scale.
4921
* @throws ArithmeticException if scale overflows.
4922
*/
4923
private static BigDecimal createAndStripZerosToMatchScale(long compactVal, int scale, long preferredScale) {
4924
while (Math.abs(compactVal) >= 10L && scale > preferredScale) {
4925
if ((compactVal & 1L) != 0L)
4926
break; // odd number cannot end in 0
4927
long r = compactVal % 10L;
4928
if (r != 0L)
4929
break; // non-0 remainder
4930
compactVal /= 10;
4931
scale = checkScale(compactVal, (long) scale - 1); // could Overflow
4932
}
4933
return valueOf(compactVal, scale);
4934
}
4935
4936
private static BigDecimal stripZerosToMatchScale(BigInteger intVal, long intCompact, int scale, int preferredScale) {
4937
if(intCompact!=INFLATED) {
4938
return createAndStripZerosToMatchScale(intCompact, scale, preferredScale);
4939
} else {
4940
return createAndStripZerosToMatchScale(intVal==null ? INFLATED_BIGINT : intVal,
4941
scale, preferredScale);
4942
}
4943
}
4944
4945
/*
4946
* returns INFLATED if oveflow
4947
*/
4948
private static long add(long xs, long ys){
4949
long sum = xs + ys;
4950
// See "Hacker's Delight" section 2-12 for explanation of
4951
// the overflow test.
4952
if ( (((sum ^ xs) & (sum ^ ys))) >= 0L) { // not overflowed
4953
return sum;
4954
}
4955
return INFLATED;
4956
}
4957
4958
private static BigDecimal add(long xs, long ys, int scale){
4959
long sum = add(xs, ys);
4960
if (sum!=INFLATED)
4961
return BigDecimal.valueOf(sum, scale);
4962
return new BigDecimal(BigInteger.valueOf(xs).add(ys), scale);
4963
}
4964
4965
private static BigDecimal add(final long xs, int scale1, final long ys, int scale2) {
4966
long sdiff = (long) scale1 - scale2;
4967
if (sdiff == 0) {
4968
return add(xs, ys, scale1);
4969
} else if (sdiff < 0) {
4970
int raise = checkScale(xs,-sdiff);
4971
long scaledX = longMultiplyPowerTen(xs, raise);
4972
if (scaledX != INFLATED) {
4973
return add(scaledX, ys, scale2);
4974
} else {
4975
BigInteger bigsum = bigMultiplyPowerTen(xs,raise).add(ys);
4976
return ((xs^ys)>=0) ? // same sign test
4977
new BigDecimal(bigsum, INFLATED, scale2, 0)
4978
: valueOf(bigsum, scale2, 0);
4979
}
4980
} else {
4981
int raise = checkScale(ys,sdiff);
4982
long scaledY = longMultiplyPowerTen(ys, raise);
4983
if (scaledY != INFLATED) {
4984
return add(xs, scaledY, scale1);
4985
} else {
4986
BigInteger bigsum = bigMultiplyPowerTen(ys,raise).add(xs);
4987
return ((xs^ys)>=0) ?
4988
new BigDecimal(bigsum, INFLATED, scale1, 0)
4989
: valueOf(bigsum, scale1, 0);
4990
}
4991
}
4992
}
4993
4994
private static BigDecimal add(final long xs, int scale1, BigInteger snd, int scale2) {
4995
int rscale = scale1;
4996
long sdiff = (long)rscale - scale2;
4997
boolean sameSigns = (Long.signum(xs) == snd.signum);
4998
BigInteger sum;
4999
if (sdiff < 0) {
5000
int raise = checkScale(xs,-sdiff);
5001
rscale = scale2;
5002
long scaledX = longMultiplyPowerTen(xs, raise);
5003
if (scaledX == INFLATED) {
5004
sum = snd.add(bigMultiplyPowerTen(xs,raise));
5005
} else {
5006
sum = snd.add(scaledX);
5007
}
5008
} else { //if (sdiff > 0) {
5009
int raise = checkScale(snd,sdiff);
5010
snd = bigMultiplyPowerTen(snd,raise);
5011
sum = snd.add(xs);
5012
}
5013
return (sameSigns) ?
5014
new BigDecimal(sum, INFLATED, rscale, 0) :
5015
valueOf(sum, rscale, 0);
5016
}
5017
5018
private static BigDecimal add(BigInteger fst, int scale1, BigInteger snd, int scale2) {
5019
int rscale = scale1;
5020
long sdiff = (long)rscale - scale2;
5021
if (sdiff != 0) {
5022
if (sdiff < 0) {
5023
int raise = checkScale(fst,-sdiff);
5024
rscale = scale2;
5025
fst = bigMultiplyPowerTen(fst,raise);
5026
} else {
5027
int raise = checkScale(snd,sdiff);
5028
snd = bigMultiplyPowerTen(snd,raise);
5029
}
5030
}
5031
BigInteger sum = fst.add(snd);
5032
return (fst.signum == snd.signum) ?
5033
new BigDecimal(sum, INFLATED, rscale, 0) :
5034
valueOf(sum, rscale, 0);
5035
}
5036
5037
private static BigInteger bigMultiplyPowerTen(long value, int n) {
5038
if (n <= 0)
5039
return BigInteger.valueOf(value);
5040
return bigTenToThe(n).multiply(value);
5041
}
5042
5043
private static BigInteger bigMultiplyPowerTen(BigInteger value, int n) {
5044
if (n <= 0)
5045
return value;
5046
if(n<LONG_TEN_POWERS_TABLE.length) {
5047
return value.multiply(LONG_TEN_POWERS_TABLE[n]);
5048
}
5049
return value.multiply(bigTenToThe(n));
5050
}
5051
5052
/**
5053
* Returns a {@code BigDecimal} whose value is {@code (xs /
5054
* ys)}, with rounding according to the context settings.
5055
*
5056
* Fast path - used only when (xscale <= yscale && yscale < 18
5057
* && mc.presision<18) {
5058
*/
5059
private static BigDecimal divideSmallFastPath(final long xs, int xscale,
5060
final long ys, int yscale,
5061
long preferredScale, MathContext mc) {
5062
int mcp = mc.precision;
5063
int roundingMode = mc.roundingMode.oldMode;
5064
5065
assert (xscale <= yscale) && (yscale < 18) && (mcp < 18);
5066
int xraise = yscale - xscale; // xraise >=0
5067
long scaledX = (xraise==0) ? xs :
5068
longMultiplyPowerTen(xs, xraise); // can't overflow here!
5069
BigDecimal quotient;
5070
5071
int cmp = longCompareMagnitude(scaledX, ys);
5072
if(cmp > 0) { // satisfy constraint (b)
5073
yscale -= 1; // [that is, divisor *= 10]
5074
int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);
5075
if (checkScaleNonZero((long) mcp + yscale - xscale) > 0) {
5076
// assert newScale >= xscale
5077
int raise = checkScaleNonZero((long) mcp + yscale - xscale);
5078
long scaledXs;
5079
if ((scaledXs = longMultiplyPowerTen(xs, raise)) == INFLATED) {
5080
quotient = null;
5081
if((mcp-1) >=0 && (mcp-1)<LONG_TEN_POWERS_TABLE.length) {
5082
quotient = multiplyDivideAndRound(LONG_TEN_POWERS_TABLE[mcp-1], scaledX, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
5083
}
5084
if(quotient==null) {
5085
BigInteger rb = bigMultiplyPowerTen(scaledX,mcp-1);
5086
quotient = divideAndRound(rb, ys,
5087
scl, roundingMode, checkScaleNonZero(preferredScale));
5088
}
5089
} else {
5090
quotient = divideAndRound(scaledXs, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
5091
}
5092
} else {
5093
int newScale = checkScaleNonZero((long) xscale - mcp);
5094
// assert newScale >= yscale
5095
if (newScale == yscale) { // easy case
5096
quotient = divideAndRound(xs, ys, scl, roundingMode,checkScaleNonZero(preferredScale));
5097
} else {
5098
int raise = checkScaleNonZero((long) newScale - yscale);
5099
long scaledYs;
5100
if ((scaledYs = longMultiplyPowerTen(ys, raise)) == INFLATED) {
5101
BigInteger rb = bigMultiplyPowerTen(ys,raise);
5102
quotient = divideAndRound(BigInteger.valueOf(xs),
5103
rb, scl, roundingMode,checkScaleNonZero(preferredScale));
5104
} else {
5105
quotient = divideAndRound(xs, scaledYs, scl, roundingMode,checkScaleNonZero(preferredScale));
5106
}
5107
}
5108
}
5109
} else {
5110
// abs(scaledX) <= abs(ys)
5111
// result is "scaledX * 10^msp / ys"
5112
int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);
5113
if(cmp==0) {
5114
// abs(scaleX)== abs(ys) => result will be scaled 10^mcp + correct sign
5115
quotient = roundedTenPower(((scaledX < 0) == (ys < 0)) ? 1 : -1, mcp, scl, checkScaleNonZero(preferredScale));
5116
} else {
5117
// abs(scaledX) < abs(ys)
5118
long scaledXs;
5119
if ((scaledXs = longMultiplyPowerTen(scaledX, mcp)) == INFLATED) {
5120
quotient = null;
5121
if(mcp<LONG_TEN_POWERS_TABLE.length) {
5122
quotient = multiplyDivideAndRound(LONG_TEN_POWERS_TABLE[mcp], scaledX, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
5123
}
5124
if(quotient==null) {
5125
BigInteger rb = bigMultiplyPowerTen(scaledX,mcp);
5126
quotient = divideAndRound(rb, ys,
5127
scl, roundingMode, checkScaleNonZero(preferredScale));
5128
}
5129
} else {
5130
quotient = divideAndRound(scaledXs, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
5131
}
5132
}
5133
}
5134
// doRound, here, only affects 1000000000 case.
5135
return doRound(quotient,mc);
5136
}
5137
5138
/**
5139
* Returns a {@code BigDecimal} whose value is {@code (xs /
5140
* ys)}, with rounding according to the context settings.
5141
*/
5142
private static BigDecimal divide(final long xs, int xscale, final long ys, int yscale, long preferredScale, MathContext mc) {
5143
int mcp = mc.precision;
5144
if(xscale <= yscale && yscale < 18 && mcp<18) {
5145
return divideSmallFastPath(xs, xscale, ys, yscale, preferredScale, mc);
5146
}
5147
if (compareMagnitudeNormalized(xs, xscale, ys, yscale) > 0) {// satisfy constraint (b)
5148
yscale -= 1; // [that is, divisor *= 10]
5149
}
5150
int roundingMode = mc.roundingMode.oldMode;
5151
// In order to find out whether the divide generates the exact result,
5152
// we avoid calling the above divide method. 'quotient' holds the
5153
// return BigDecimal object whose scale will be set to 'scl'.
5154
int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);
5155
BigDecimal quotient;
5156
if (checkScaleNonZero((long) mcp + yscale - xscale) > 0) {
5157
int raise = checkScaleNonZero((long) mcp + yscale - xscale);
5158
long scaledXs;
5159
if ((scaledXs = longMultiplyPowerTen(xs, raise)) == INFLATED) {
5160
BigInteger rb = bigMultiplyPowerTen(xs,raise);
5161
quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
5162
} else {
5163
quotient = divideAndRound(scaledXs, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
5164
}
5165
} else {
5166
int newScale = checkScaleNonZero((long) xscale - mcp);
5167
// assert newScale >= yscale
5168
if (newScale == yscale) { // easy case
5169
quotient = divideAndRound(xs, ys, scl, roundingMode,checkScaleNonZero(preferredScale));
5170
} else {
5171
int raise = checkScaleNonZero((long) newScale - yscale);
5172
long scaledYs;
5173
if ((scaledYs = longMultiplyPowerTen(ys, raise)) == INFLATED) {
5174
BigInteger rb = bigMultiplyPowerTen(ys,raise);
5175
quotient = divideAndRound(BigInteger.valueOf(xs),
5176
rb, scl, roundingMode,checkScaleNonZero(preferredScale));
5177
} else {
5178
quotient = divideAndRound(xs, scaledYs, scl, roundingMode,checkScaleNonZero(preferredScale));
5179
}
5180
}
5181
}
5182
// doRound, here, only affects 1000000000 case.
5183
return doRound(quotient,mc);
5184
}
5185
5186
/**
5187
* Returns a {@code BigDecimal} whose value is {@code (xs /
5188
* ys)}, with rounding according to the context settings.
5189
*/
5190
private static BigDecimal divide(BigInteger xs, int xscale, long ys, int yscale, long preferredScale, MathContext mc) {
5191
// Normalize dividend & divisor so that both fall into [0.1, 0.999...]
5192
if ((-compareMagnitudeNormalized(ys, yscale, xs, xscale)) > 0) {// satisfy constraint (b)
5193
yscale -= 1; // [that is, divisor *= 10]
5194
}
5195
int mcp = mc.precision;
5196
int roundingMode = mc.roundingMode.oldMode;
5197
5198
// In order to find out whether the divide generates the exact result,
5199
// we avoid calling the above divide method. 'quotient' holds the
5200
// return BigDecimal object whose scale will be set to 'scl'.
5201
BigDecimal quotient;
5202
int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);
5203
if (checkScaleNonZero((long) mcp + yscale - xscale) > 0) {
5204
int raise = checkScaleNonZero((long) mcp + yscale - xscale);
5205
BigInteger rb = bigMultiplyPowerTen(xs,raise);
5206
quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
5207
} else {
5208
int newScale = checkScaleNonZero((long) xscale - mcp);
5209
// assert newScale >= yscale
5210
if (newScale == yscale) { // easy case
5211
quotient = divideAndRound(xs, ys, scl, roundingMode,checkScaleNonZero(preferredScale));
5212
} else {
5213
int raise = checkScaleNonZero((long) newScale - yscale);
5214
long scaledYs;
5215
if ((scaledYs = longMultiplyPowerTen(ys, raise)) == INFLATED) {
5216
BigInteger rb = bigMultiplyPowerTen(ys,raise);
5217
quotient = divideAndRound(xs, rb, scl, roundingMode,checkScaleNonZero(preferredScale));
5218
} else {
5219
quotient = divideAndRound(xs, scaledYs, scl, roundingMode,checkScaleNonZero(preferredScale));
5220
}
5221
}
5222
}
5223
// doRound, here, only affects 1000000000 case.
5224
return doRound(quotient, mc);
5225
}
5226
5227
/**
5228
* Returns a {@code BigDecimal} whose value is {@code (xs /
5229
* ys)}, with rounding according to the context settings.
5230
*/
5231
private static BigDecimal divide(long xs, int xscale, BigInteger ys, int yscale, long preferredScale, MathContext mc) {
5232
// Normalize dividend & divisor so that both fall into [0.1, 0.999...]
5233
if (compareMagnitudeNormalized(xs, xscale, ys, yscale) > 0) {// satisfy constraint (b)
5234
yscale -= 1; // [that is, divisor *= 10]
5235
}
5236
int mcp = mc.precision;
5237
int roundingMode = mc.roundingMode.oldMode;
5238
5239
// In order to find out whether the divide generates the exact result,
5240
// we avoid calling the above divide method. 'quotient' holds the
5241
// return BigDecimal object whose scale will be set to 'scl'.
5242
BigDecimal quotient;
5243
int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);
5244
if (checkScaleNonZero((long) mcp + yscale - xscale) > 0) {
5245
int raise = checkScaleNonZero((long) mcp + yscale - xscale);
5246
BigInteger rb = bigMultiplyPowerTen(xs,raise);
5247
quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
5248
} else {
5249
int newScale = checkScaleNonZero((long) xscale - mcp);
5250
int raise = checkScaleNonZero((long) newScale - yscale);
5251
BigInteger rb = bigMultiplyPowerTen(ys,raise);
5252
quotient = divideAndRound(BigInteger.valueOf(xs), rb, scl, roundingMode,checkScaleNonZero(preferredScale));
5253
}
5254
// doRound, here, only affects 1000000000 case.
5255
return doRound(quotient, mc);
5256
}
5257
5258
/**
5259
* Returns a {@code BigDecimal} whose value is {@code (xs /
5260
* ys)}, with rounding according to the context settings.
5261
*/
5262
private static BigDecimal divide(BigInteger xs, int xscale, BigInteger ys, int yscale, long preferredScale, MathContext mc) {
5263
// Normalize dividend & divisor so that both fall into [0.1, 0.999...]
5264
if (compareMagnitudeNormalized(xs, xscale, ys, yscale) > 0) {// satisfy constraint (b)
5265
yscale -= 1; // [that is, divisor *= 10]
5266
}
5267
int mcp = mc.precision;
5268
int roundingMode = mc.roundingMode.oldMode;
5269
5270
// In order to find out whether the divide generates the exact result,
5271
// we avoid calling the above divide method. 'quotient' holds the
5272
// return BigDecimal object whose scale will be set to 'scl'.
5273
BigDecimal quotient;
5274
int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);
5275
if (checkScaleNonZero((long) mcp + yscale - xscale) > 0) {
5276
int raise = checkScaleNonZero((long) mcp + yscale - xscale);
5277
BigInteger rb = bigMultiplyPowerTen(xs,raise);
5278
quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
5279
} else {
5280
int newScale = checkScaleNonZero((long) xscale - mcp);
5281
int raise = checkScaleNonZero((long) newScale - yscale);
5282
BigInteger rb = bigMultiplyPowerTen(ys,raise);
5283
quotient = divideAndRound(xs, rb, scl, roundingMode,checkScaleNonZero(preferredScale));
5284
}
5285
// doRound, here, only affects 1000000000 case.
5286
return doRound(quotient, mc);
5287
}
5288
5289
/*
5290
* performs divideAndRound for (dividend0*dividend1, divisor)
5291
* returns null if quotient can't fit into long value;
5292
*/
5293
private static BigDecimal multiplyDivideAndRound(long dividend0, long dividend1, long divisor, int scale, int roundingMode,
5294
int preferredScale) {
5295
int qsign = Long.signum(dividend0)*Long.signum(dividend1)*Long.signum(divisor);
5296
dividend0 = Math.abs(dividend0);
5297
dividend1 = Math.abs(dividend1);
5298
divisor = Math.abs(divisor);
5299
// multiply dividend0 * dividend1
5300
long d0_hi = dividend0 >>> 32;
5301
long d0_lo = dividend0 & LONG_MASK;
5302
long d1_hi = dividend1 >>> 32;
5303
long d1_lo = dividend1 & LONG_MASK;
5304
long product = d0_lo * d1_lo;
5305
long d0 = product & LONG_MASK;
5306
long d1 = product >>> 32;
5307
product = d0_hi * d1_lo + d1;
5308
d1 = product & LONG_MASK;
5309
long d2 = product >>> 32;
5310
product = d0_lo * d1_hi + d1;
5311
d1 = product & LONG_MASK;
5312
d2 += product >>> 32;
5313
long d3 = d2>>>32;
5314
d2 &= LONG_MASK;
5315
product = d0_hi*d1_hi + d2;
5316
d2 = product & LONG_MASK;
5317
d3 = ((product>>>32) + d3) & LONG_MASK;
5318
final long dividendHi = make64(d3,d2);
5319
final long dividendLo = make64(d1,d0);
5320
// divide
5321
return divideAndRound128(dividendHi, dividendLo, divisor, qsign, scale, roundingMode, preferredScale);
5322
}
5323
5324
private static final long DIV_NUM_BASE = (1L<<32); // Number base (32 bits).
5325
5326
/*
5327
* divideAndRound 128-bit value by long divisor.
5328
* returns null if quotient can't fit into long value;
5329
* Specialized version of Knuth's division
5330
*/
5331
private static BigDecimal divideAndRound128(final long dividendHi, final long dividendLo, long divisor, int sign,
5332
int scale, int roundingMode, int preferredScale) {
5333
if (dividendHi >= divisor) {
5334
return null;
5335
}
5336
5337
final int shift = Long.numberOfLeadingZeros(divisor);
5338
divisor <<= shift;
5339
5340
final long v1 = divisor >>> 32;
5341
final long v0 = divisor & LONG_MASK;
5342
5343
long tmp = dividendLo << shift;
5344
long u1 = tmp >>> 32;
5345
long u0 = tmp & LONG_MASK;
5346
5347
tmp = (dividendHi << shift) | (dividendLo >>> 64 - shift);
5348
long u2 = tmp & LONG_MASK;
5349
long q1, r_tmp;
5350
if (v1 == 1) {
5351
q1 = tmp;
5352
r_tmp = 0;
5353
} else if (tmp >= 0) {
5354
q1 = tmp / v1;
5355
r_tmp = tmp - q1 * v1;
5356
} else {
5357
long[] rq = divRemNegativeLong(tmp, v1);
5358
q1 = rq[1];
5359
r_tmp = rq[0];
5360
}
5361
5362
while(q1 >= DIV_NUM_BASE || unsignedLongCompare(q1*v0, make64(r_tmp, u1))) {
5363
q1--;
5364
r_tmp += v1;
5365
if (r_tmp >= DIV_NUM_BASE)
5366
break;
5367
}
5368
5369
tmp = mulsub(u2,u1,v1,v0,q1);
5370
u1 = tmp & LONG_MASK;
5371
long q0;
5372
if (v1 == 1) {
5373
q0 = tmp;
5374
r_tmp = 0;
5375
} else if (tmp >= 0) {
5376
q0 = tmp / v1;
5377
r_tmp = tmp - q0 * v1;
5378
} else {
5379
long[] rq = divRemNegativeLong(tmp, v1);
5380
q0 = rq[1];
5381
r_tmp = rq[0];
5382
}
5383
5384
while(q0 >= DIV_NUM_BASE || unsignedLongCompare(q0*v0,make64(r_tmp,u0))) {
5385
q0--;
5386
r_tmp += v1;
5387
if (r_tmp >= DIV_NUM_BASE)
5388
break;
5389
}
5390
5391
if((int)q1 < 0) {
5392
// result (which is positive and unsigned here)
5393
// can't fit into long due to sign bit is used for value
5394
MutableBigInteger mq = new MutableBigInteger(new int[]{(int)q1, (int)q0});
5395
if (roundingMode == ROUND_DOWN && scale == preferredScale) {
5396
return mq.toBigDecimal(sign, scale);
5397
}
5398
long r = mulsub(u1, u0, v1, v0, q0) >>> shift;
5399
if (r != 0) {
5400
if(needIncrement(divisor >>> shift, roundingMode, sign, mq, r)){
5401
mq.add(MutableBigInteger.ONE);
5402
}
5403
return mq.toBigDecimal(sign, scale);
5404
} else {
5405
if (preferredScale != scale) {
5406
BigInteger intVal = mq.toBigInteger(sign);
5407
return createAndStripZerosToMatchScale(intVal,scale, preferredScale);
5408
} else {
5409
return mq.toBigDecimal(sign, scale);
5410
}
5411
}
5412
}
5413
5414
long q = make64(q1,q0);
5415
q*=sign;
5416
5417
if (roundingMode == ROUND_DOWN && scale == preferredScale)
5418
return valueOf(q, scale);
5419
5420
long r = mulsub(u1, u0, v1, v0, q0) >>> shift;
5421
if (r != 0) {
5422
boolean increment = needIncrement(divisor >>> shift, roundingMode, sign, q, r);
5423
return valueOf((increment ? q + sign : q), scale);
5424
} else {
5425
if (preferredScale != scale) {
5426
return createAndStripZerosToMatchScale(q, scale, preferredScale);
5427
} else {
5428
return valueOf(q, scale);
5429
}
5430
}
5431
}
5432
5433
/*
5434
* calculate divideAndRound for ldividend*10^raise / divisor
5435
* when abs(dividend)==abs(divisor);
5436
*/
5437
private static BigDecimal roundedTenPower(int qsign, int raise, int scale, int preferredScale) {
5438
if (scale > preferredScale) {
5439
int diff = scale - preferredScale;
5440
if(diff < raise) {
5441
return scaledTenPow(raise - diff, qsign, preferredScale);
5442
} else {
5443
return valueOf(qsign,scale-raise);
5444
}
5445
} else {
5446
return scaledTenPow(raise, qsign, scale);
5447
}
5448
}
5449
5450
static BigDecimal scaledTenPow(int n, int sign, int scale) {
5451
if (n < LONG_TEN_POWERS_TABLE.length)
5452
return valueOf(sign*LONG_TEN_POWERS_TABLE[n],scale);
5453
else {
5454
BigInteger unscaledVal = bigTenToThe(n);
5455
if(sign==-1) {
5456
unscaledVal = unscaledVal.negate();
5457
}
5458
return new BigDecimal(unscaledVal, INFLATED, scale, n+1);
5459
}
5460
}
5461
5462
/**
5463
* Calculate the quotient and remainder of dividing a negative long by
5464
* another long.
5465
*
5466
* @param n the numerator; must be negative
5467
* @param d the denominator; must not be unity
5468
* @return a two-element {@code long} array with the remainder and quotient in
5469
* the initial and final elements, respectively
5470
*/
5471
private static long[] divRemNegativeLong(long n, long d) {
5472
assert n < 0 : "Non-negative numerator " + n;
5473
assert d != 1 : "Unity denominator";
5474
5475
// Approximate the quotient and remainder
5476
long q = (n >>> 1) / (d >>> 1);
5477
long r = n - q * d;
5478
5479
// Correct the approximation
5480
while (r < 0) {
5481
r += d;
5482
q--;
5483
}
5484
while (r >= d) {
5485
r -= d;
5486
q++;
5487
}
5488
5489
// n - q*d == r && 0 <= r < d, hence we're done.
5490
return new long[] {r, q};
5491
}
5492
5493
private static long make64(long hi, long lo) {
5494
return hi<<32 | lo;
5495
}
5496
5497
private static long mulsub(long u1, long u0, final long v1, final long v0, long q0) {
5498
long tmp = u0 - q0*v0;
5499
return make64(u1 + (tmp>>>32) - q0*v1,tmp & LONG_MASK);
5500
}
5501
5502
private static boolean unsignedLongCompare(long one, long two) {
5503
return (one+Long.MIN_VALUE) > (two+Long.MIN_VALUE);
5504
}
5505
5506
private static boolean unsignedLongCompareEq(long one, long two) {
5507
return (one+Long.MIN_VALUE) >= (two+Long.MIN_VALUE);
5508
}
5509
5510
5511
// Compare Normalize dividend & divisor so that both fall into [0.1, 0.999...]
5512
private static int compareMagnitudeNormalized(long xs, int xscale, long ys, int yscale) {
5513
// assert xs!=0 && ys!=0
5514
int sdiff = xscale - yscale;
5515
if (sdiff != 0) {
5516
if (sdiff < 0) {
5517
xs = longMultiplyPowerTen(xs, -sdiff);
5518
} else { // sdiff > 0
5519
ys = longMultiplyPowerTen(ys, sdiff);
5520
}
5521
}
5522
if (xs != INFLATED)
5523
return (ys != INFLATED) ? longCompareMagnitude(xs, ys) : -1;
5524
else
5525
return 1;
5526
}
5527
5528
// Compare Normalize dividend & divisor so that both fall into [0.1, 0.999...]
5529
private static int compareMagnitudeNormalized(long xs, int xscale, BigInteger ys, int yscale) {
5530
// assert "ys can't be represented as long"
5531
if (xs == 0)
5532
return -1;
5533
int sdiff = xscale - yscale;
5534
if (sdiff < 0) {
5535
if (longMultiplyPowerTen(xs, -sdiff) == INFLATED ) {
5536
return bigMultiplyPowerTen(xs, -sdiff).compareMagnitude(ys);
5537
}
5538
}
5539
return -1;
5540
}
5541
5542
// Compare Normalize dividend & divisor so that both fall into [0.1, 0.999...]
5543
private static int compareMagnitudeNormalized(BigInteger xs, int xscale, BigInteger ys, int yscale) {
5544
int sdiff = xscale - yscale;
5545
if (sdiff < 0) {
5546
return bigMultiplyPowerTen(xs, -sdiff).compareMagnitude(ys);
5547
} else { // sdiff >= 0
5548
return xs.compareMagnitude(bigMultiplyPowerTen(ys, sdiff));
5549
}
5550
}
5551
5552
private static long multiply(long x, long y){
5553
long product = x * y;
5554
long ax = Math.abs(x);
5555
long ay = Math.abs(y);
5556
if (((ax | ay) >>> 31 == 0) || (y == 0) || (product / y == x)){
5557
return product;
5558
}
5559
return INFLATED;
5560
}
5561
5562
private static BigDecimal multiply(long x, long y, int scale) {
5563
long product = multiply(x, y);
5564
if(product!=INFLATED) {
5565
return valueOf(product,scale);
5566
}
5567
return new BigDecimal(BigInteger.valueOf(x).multiply(y),INFLATED,scale,0);
5568
}
5569
5570
private static BigDecimal multiply(long x, BigInteger y, int scale) {
5571
if(x==0) {
5572
return zeroValueOf(scale);
5573
}
5574
return new BigDecimal(y.multiply(x),INFLATED,scale,0);
5575
}
5576
5577
private static BigDecimal multiply(BigInteger x, BigInteger y, int scale) {
5578
return new BigDecimal(x.multiply(y),INFLATED,scale,0);
5579
}
5580
5581
/**
5582
* Multiplies two long values and rounds according {@code MathContext}
5583
*/
5584
private static BigDecimal multiplyAndRound(long x, long y, int scale, MathContext mc) {
5585
long product = multiply(x, y);
5586
if(product!=INFLATED) {
5587
return doRound(product, scale, mc);
5588
}
5589
// attempt to do it in 128 bits
5590
int rsign = 1;
5591
if(x < 0) {
5592
x = -x;
5593
rsign = -1;
5594
}
5595
if(y < 0) {
5596
y = -y;
5597
rsign *= -1;
5598
}
5599
// multiply dividend0 * dividend1
5600
long m0_hi = x >>> 32;
5601
long m0_lo = x & LONG_MASK;
5602
long m1_hi = y >>> 32;
5603
long m1_lo = y & LONG_MASK;
5604
product = m0_lo * m1_lo;
5605
long m0 = product & LONG_MASK;
5606
long m1 = product >>> 32;
5607
product = m0_hi * m1_lo + m1;
5608
m1 = product & LONG_MASK;
5609
long m2 = product >>> 32;
5610
product = m0_lo * m1_hi + m1;
5611
m1 = product & LONG_MASK;
5612
m2 += product >>> 32;
5613
long m3 = m2>>>32;
5614
m2 &= LONG_MASK;
5615
product = m0_hi*m1_hi + m2;
5616
m2 = product & LONG_MASK;
5617
m3 = ((product>>>32) + m3) & LONG_MASK;
5618
final long mHi = make64(m3,m2);
5619
final long mLo = make64(m1,m0);
5620
BigDecimal res = doRound128(mHi, mLo, rsign, scale, mc);
5621
if(res!=null) {
5622
return res;
5623
}
5624
res = new BigDecimal(BigInteger.valueOf(x).multiply(y*rsign), INFLATED, scale, 0);
5625
return doRound(res,mc);
5626
}
5627
5628
private static BigDecimal multiplyAndRound(long x, BigInteger y, int scale, MathContext mc) {
5629
if(x==0) {
5630
return zeroValueOf(scale);
5631
}
5632
return doRound(y.multiply(x), scale, mc);
5633
}
5634
5635
private static BigDecimal multiplyAndRound(BigInteger x, BigInteger y, int scale, MathContext mc) {
5636
return doRound(x.multiply(y), scale, mc);
5637
}
5638
5639
/**
5640
* rounds 128-bit value according {@code MathContext}
5641
* returns null if result can't be repsented as compact BigDecimal.
5642
*/
5643
private static BigDecimal doRound128(long hi, long lo, int sign, int scale, MathContext mc) {
5644
int mcp = mc.precision;
5645
int drop;
5646
BigDecimal res = null;
5647
if(((drop = precision(hi, lo) - mcp) > 0)&&(drop<LONG_TEN_POWERS_TABLE.length)) {
5648
scale = checkScaleNonZero((long)scale - drop);
5649
res = divideAndRound128(hi, lo, LONG_TEN_POWERS_TABLE[drop], sign, scale, mc.roundingMode.oldMode, scale);
5650
}
5651
if(res!=null) {
5652
return doRound(res,mc);
5653
}
5654
return null;
5655
}
5656
5657
private static final long[][] LONGLONG_TEN_POWERS_TABLE = {
5658
{ 0L, 0x8AC7230489E80000L }, //10^19
5659
{ 0x5L, 0x6bc75e2d63100000L }, //10^20
5660
{ 0x36L, 0x35c9adc5dea00000L }, //10^21
5661
{ 0x21eL, 0x19e0c9bab2400000L }, //10^22
5662
{ 0x152dL, 0x02c7e14af6800000L }, //10^23
5663
{ 0xd3c2L, 0x1bcecceda1000000L }, //10^24
5664
{ 0x84595L, 0x161401484a000000L }, //10^25
5665
{ 0x52b7d2L, 0xdcc80cd2e4000000L }, //10^26
5666
{ 0x33b2e3cL, 0x9fd0803ce8000000L }, //10^27
5667
{ 0x204fce5eL, 0x3e25026110000000L }, //10^28
5668
{ 0x1431e0faeL, 0x6d7217caa0000000L }, //10^29
5669
{ 0xc9f2c9cd0L, 0x4674edea40000000L }, //10^30
5670
{ 0x7e37be2022L, 0xc0914b2680000000L }, //10^31
5671
{ 0x4ee2d6d415bL, 0x85acef8100000000L }, //10^32
5672
{ 0x314dc6448d93L, 0x38c15b0a00000000L }, //10^33
5673
{ 0x1ed09bead87c0L, 0x378d8e6400000000L }, //10^34
5674
{ 0x13426172c74d82L, 0x2b878fe800000000L }, //10^35
5675
{ 0xc097ce7bc90715L, 0xb34b9f1000000000L }, //10^36
5676
{ 0x785ee10d5da46d9L, 0x00f436a000000000L }, //10^37
5677
{ 0x4b3b4ca85a86c47aL, 0x098a224000000000L }, //10^38
5678
};
5679
5680
/*
5681
* returns precision of 128-bit value
5682
*/
5683
private static int precision(long hi, long lo){
5684
if(hi==0) {
5685
if(lo>=0) {
5686
return longDigitLength(lo);
5687
}
5688
return (unsignedLongCompareEq(lo, LONGLONG_TEN_POWERS_TABLE[0][1])) ? 20 : 19;
5689
// 0x8AC7230489E80000L = unsigned 2^19
5690
}
5691
int r = ((128 - Long.numberOfLeadingZeros(hi) + 1) * 1233) >>> 12;
5692
int idx = r-19;
5693
return (idx >= LONGLONG_TEN_POWERS_TABLE.length || longLongCompareMagnitude(hi, lo,
5694
LONGLONG_TEN_POWERS_TABLE[idx][0], LONGLONG_TEN_POWERS_TABLE[idx][1])) ? r : r + 1;
5695
}
5696
5697
/*
5698
* returns true if 128 bit number <hi0,lo0> is less than <hi1,lo1>
5699
* hi0 & hi1 should be non-negative
5700
*/
5701
private static boolean longLongCompareMagnitude(long hi0, long lo0, long hi1, long lo1) {
5702
if(hi0!=hi1) {
5703
return hi0<hi1;
5704
}
5705
return (lo0+Long.MIN_VALUE) <(lo1+Long.MIN_VALUE);
5706
}
5707
5708
private static BigDecimal divide(long dividend, int dividendScale, long divisor, int divisorScale, int scale, int roundingMode) {
5709
if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) {
5710
int newScale = scale + divisorScale;
5711
int raise = newScale - dividendScale;
5712
if(raise<LONG_TEN_POWERS_TABLE.length) {
5713
long xs = dividend;
5714
if ((xs = longMultiplyPowerTen(xs, raise)) != INFLATED) {
5715
return divideAndRound(xs, divisor, scale, roundingMode, scale);
5716
}
5717
BigDecimal q = multiplyDivideAndRound(LONG_TEN_POWERS_TABLE[raise], dividend, divisor, scale, roundingMode, scale);
5718
if(q!=null) {
5719
return q;
5720
}
5721
}
5722
BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise);
5723
return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale);
5724
} else {
5725
int newScale = checkScale(divisor,(long)dividendScale - scale);
5726
int raise = newScale - divisorScale;
5727
if(raise<LONG_TEN_POWERS_TABLE.length) {
5728
long ys = divisor;
5729
if ((ys = longMultiplyPowerTen(ys, raise)) != INFLATED) {
5730
return divideAndRound(dividend, ys, scale, roundingMode, scale);
5731
}
5732
}
5733
BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise);
5734
return divideAndRound(BigInteger.valueOf(dividend), scaledDivisor, scale, roundingMode, scale);
5735
}
5736
}
5737
5738
private static BigDecimal divide(BigInteger dividend, int dividendScale, long divisor, int divisorScale, int scale, int roundingMode) {
5739
if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) {
5740
int newScale = scale + divisorScale;
5741
int raise = newScale - dividendScale;
5742
BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise);
5743
return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale);
5744
} else {
5745
int newScale = checkScale(divisor,(long)dividendScale - scale);
5746
int raise = newScale - divisorScale;
5747
if(raise<LONG_TEN_POWERS_TABLE.length) {
5748
long ys = divisor;
5749
if ((ys = longMultiplyPowerTen(ys, raise)) != INFLATED) {
5750
return divideAndRound(dividend, ys, scale, roundingMode, scale);
5751
}
5752
}
5753
BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise);
5754
return divideAndRound(dividend, scaledDivisor, scale, roundingMode, scale);
5755
}
5756
}
5757
5758
private static BigDecimal divide(long dividend, int dividendScale, BigInteger divisor, int divisorScale, int scale, int roundingMode) {
5759
if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) {
5760
int newScale = scale + divisorScale;
5761
int raise = newScale - dividendScale;
5762
BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise);
5763
return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale);
5764
} else {
5765
int newScale = checkScale(divisor,(long)dividendScale - scale);
5766
int raise = newScale - divisorScale;
5767
BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise);
5768
return divideAndRound(BigInteger.valueOf(dividend), scaledDivisor, scale, roundingMode, scale);
5769
}
5770
}
5771
5772
private static BigDecimal divide(BigInteger dividend, int dividendScale, BigInteger divisor, int divisorScale, int scale, int roundingMode) {
5773
if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) {
5774
int newScale = scale + divisorScale;
5775
int raise = newScale - dividendScale;
5776
BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise);
5777
return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale);
5778
} else {
5779
int newScale = checkScale(divisor,(long)dividendScale - scale);
5780
int raise = newScale - divisorScale;
5781
BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise);
5782
return divideAndRound(dividend, scaledDivisor, scale, roundingMode, scale);
5783
}
5784
}
5785
5786
}
5787
5788