• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  * Copyright (c) 1994, 2021, Oracle and/or its affiliates. All rights reserved.
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This code is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 only, as
8  * published by the Free Software Foundation.  Oracle designates this
9  * particular file as subject to the "Classpath" exception as provided
10  * by Oracle in the LICENSE file that accompanied this code.
11  *
12  * This code is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15  * version 2 for more details (a copy is included in the LICENSE file that
16  * accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License version
19  * 2 along with this work; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21  *
22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23  * or visit www.oracle.com if you need additional information or have any
24  * questions.
25  */
26 
27 package java.lang;
28 
29 import dalvik.annotation.optimization.CriticalNative;
30 
31 import java.math.BigDecimal;
32 import java.util.Random;
33 import jdk.internal.math.FloatConsts;
34 import jdk.internal.math.DoubleConsts;
35 import jdk.internal.vm.annotation.IntrinsicCandidate;
36 
37 // Android-note: Document that the results from Math are based on libm's behavior.
38 // For performance, Android implements many of the methods in this class in terms of the underlying
39 // OS's libm functions. libm has well-defined behavior for special cases. Where known these are
40 // marked with the tag above and the documentation has been modified as needed.
41 // Android-changed: Fixed method links in the last paragraph.
42 /**
43  * The class {@code Math} contains methods for performing basic
44  * numeric operations such as the elementary exponential, logarithm,
45  * square root, and trigonometric functions.
46  *
47  * <p>Unlike some of the numeric methods of class
48  * {@link java.lang.StrictMath StrictMath}, all implementations of the equivalent
49  * functions of class {@code Math} are not defined to return the
50  * bit-for-bit same results.  This relaxation permits
51  * better-performing implementations where strict reproducibility is
52  * not required.
53  *
54  * <p>By default many of the {@code Math} methods simply call
55  * the equivalent method in {@code StrictMath} for their
56  * implementation.  Code generators are encouraged to use
57  * platform-specific native libraries or microprocessor instructions,
58  * where available, to provide higher-performance implementations of
59  * {@code Math} methods.  Such higher-performance
60  * implementations still must conform to the specification for
61  * {@code Math}.
62  *
63  * <p>The quality of implementation specifications concern two
64  * properties, accuracy of the returned result and monotonicity of the
65  * method.  Accuracy of the floating-point {@code Math} methods is
66  * measured in terms of <i>ulps</i>, units in the last place.  For a
67  * given floating-point format, an {@linkplain #ulp(double) ulp} of a
68  * specific real number value is the distance between the two
69  * floating-point values bracketing that numerical value.  When
70  * discussing the accuracy of a method as a whole rather than at a
71  * specific argument, the number of ulps cited is for the worst-case
72  * error at any argument.  If a method always has an error less than
73  * 0.5 ulps, the method always returns the floating-point number
74  * nearest the exact result; such a method is <i>correctly
75  * rounded</i>.  A correctly rounded method is generally the best a
76  * floating-point approximation can be; however, it is impractical for
77  * many floating-point methods to be correctly rounded.  Instead, for
78  * the {@code Math} class, a larger error bound of 1 or 2 ulps is
79  * allowed for certain methods.  Informally, with a 1 ulp error bound,
80  * when the exact result is a representable number, the exact result
81  * should be returned as the computed result; otherwise, either of the
82  * two floating-point values which bracket the exact result may be
83  * returned.  For exact results large in magnitude, one of the
84  * endpoints of the bracket may be infinite.  Besides accuracy at
85  * individual arguments, maintaining proper relations between the
86  * method at different arguments is also important.  Therefore, most
87  * methods with more than 0.5 ulp errors are required to be
88  * <i>semi-monotonic</i>: whenever the mathematical function is
89  * non-decreasing, so is the floating-point approximation, likewise,
90  * whenever the mathematical function is non-increasing, so is the
91  * floating-point approximation.  Not all approximations that have 1
92  * ulp accuracy will automatically meet the monotonicity requirements.
93  *
94  * <p>
95  * The platform uses signed two's complement integer arithmetic with
96  * int and long primitive types.  The developer should choose
97  * the primitive type to ensure that arithmetic operations consistently
98  * produce correct results, which in some cases means the operations
99  * will not overflow the range of values of the computation.
100  * The best practice is to choose the primitive type and algorithm to avoid
101  * overflow. In cases where the size is {@code int} or {@code long} and
102  * overflow errors need to be detected, the methods {@code addExact},
103  * {@code subtractExact}, {@code multiplyExact}, {@code toIntExact},
104  * {@code incrementExact}, {@code decrementExact} and {@code negateExact}
105  * throw an {@code ArithmeticException} when the results overflow.
106  * For the arithmetic operations divide and absolute value, overflow
107  * occurs only with a specific minimum or maximum value and
108  * should be checked against the minimum or maximum as appropriate.
109  *
110  * <h2><a id=Ieee754RecommendedOps>IEEE 754 Recommended
111  * Operations</a></h2>
112  *
113  * The 2019 revision of the IEEE 754 floating-point standard includes
114  * a section of recommended operations and the semantics of those
115  * operations if they are included in a programming environment. The
116  * recommended operations present in this class include {@link #sin(double)
117  * sin}, {@link #cos(double) cos}, {@link #tan(double) tan}, {@link #asin(double) asin}, {@link
118  * #acos(double) acos}, {@link #atan(double) atan}, {@link #exp(double) exp}, {@link #expm1(double)
119  * expm1}, {@link #log(double) log}, {@link #log10(double) log10}, {@link #log1p(double) log1p},
120  * {@link #sinh(double) sinh}, {@link #cosh(double) cosh}, {@link #tanh(double) tanh}, {@link
121  * #hypot(double, double) hypot}, and {@link #pow(double, double) pow}.  (The {@link #sqrt(double) sqrt}
122  * operation is a required part of IEEE 754 from a different section
123  * of the standard.) The special case behavior of the recommended
124  * operations generally follows the guidance of the IEEE 754
125  * standard. However, the {@code pow} method defines different
126  * behavior for some arguments, as noted in its {@linkplain #pow(double, double)
127  * specification}. The IEEE 754 standard defines its operations to be
128  * correctly rounded, which is a more stringent quality of
129  * implementation condition than required for most of the methods in
130  * question that are also included in this class.
131  *
132  * @author  Joseph D. Darcy
133  * @since   1.0
134  */
135 
136 public final class Math {
137 
138     // Android-changed: Numerous methods in this class are re-implemented in native for performance.
139     // Those methods are also annotated @CriticalNative.
140 
141     /**
142      * Don't let anyone instantiate this class.
143      */
Math()144     private Math() {}
145 
146     /**
147      * The {@code double} value that is closer than any other to
148      * <i>e</i>, the base of the natural logarithms.
149      */
150     public static final double E = 2.7182818284590452354;
151 
152     /**
153      * The {@code double} value that is closer than any other to
154      * <i>pi</i>, the ratio of the circumference of a circle to its
155      * diameter.
156      */
157     public static final double PI = 3.14159265358979323846;
158 
159     /**
160      * Constant by which to multiply an angular value in degrees to obtain an
161      * angular value in radians.
162      */
163     private static final double DEGREES_TO_RADIANS = 0.017453292519943295;
164 
165     /**
166      * Constant by which to multiply an angular value in radians to obtain an
167      * angular value in degrees.
168      */
169     private static final double RADIANS_TO_DEGREES = 57.29577951308232;
170 
171     /**
172      * Returns the trigonometric sine of an angle.  Special cases:
173      * <ul><li>If the argument is NaN or an infinity, then the
174      * result is NaN.
175      * <li>If the argument is zero, then the result is a zero with the
176      * same sign as the argument.</ul>
177      *
178      * <p>The computed result must be within 1 ulp of the exact result.
179      * Results must be semi-monotonic.
180      *
181      * @param   a   an angle, in radians.
182      * @return  the sine of the argument.
183      */
184     // BEGIN Android-changed: Reimplement in native
185     /*
186     @IntrinsicCandidate
187     public static double sin(double a) {
188         return StrictMath.sin(a); // default impl. delegates to StrictMath
189     }
190     */
191     // END Android-changed: Reimplement in native
192     @CriticalNative
sin(double a)193     public static native double sin(double a);
194 
195     /**
196      * Returns the trigonometric cosine of an angle. Special cases:
197      * <ul><li>If the argument is NaN or an infinity, then the
198      * result is NaN.
199      * <li>If the argument is zero, then the result is {@code 1.0}.
200      *</ul>
201      *
202      * <p>The computed result must be within 1 ulp of the exact result.
203      * Results must be semi-monotonic.
204      *
205      * @param   a   an angle, in radians.
206      * @return  the cosine of the argument.
207      */
208     // BEGIN Android-changed: Reimplement in native
209     /*
210     @IntrinsicCandidate
211     public static double cos(double a) {
212         return StrictMath.cos(a); // default impl. delegates to StrictMath
213     }
214     */
215     // END Android-changed: Reimplement in native
216     @CriticalNative
cos(double a)217     public static native double cos(double a);
218 
219     /**
220      * Returns the trigonometric tangent of an angle.  Special cases:
221      * <ul><li>If the argument is NaN or an infinity, then the result
222      * is NaN.
223      * <li>If the argument is zero, then the result is a zero with the
224      * same sign as the argument.</ul>
225      *
226      * <p>The computed result must be within 1 ulp of the exact result.
227      * Results must be semi-monotonic.
228      *
229      * @param   a   an angle, in radians.
230      * @return  the tangent of the argument.
231      */
232     // BEGIN Android-changed: Reimplement in native
233     /*
234     @IntrinsicCandidate
235     public static double tan(double a) {
236         return StrictMath.tan(a); // default impl. delegates to StrictMath
237     }
238     */
239     // END Android-changed: Reimplement in native
240     @CriticalNative
tan(double a)241     public static native double tan(double a);
242 
243     /**
244      * Returns the arc sine of a value; the returned angle is in the
245      * range -<i>pi</i>/2 through <i>pi</i>/2.  Special cases:
246      * <ul><li>If the argument is NaN or its absolute value is greater
247      * than 1, then the result is NaN.
248      * <li>If the argument is zero, then the result is a zero with the
249      * same sign as the argument.</ul>
250      *
251      * <p>The computed result must be within 1 ulp of the exact result.
252      * Results must be semi-monotonic.
253      *
254      * @param   a   the value whose arc sine is to be returned.
255      * @return  the arc sine of the argument.
256      */
257     // BEGIN Android-changed: Reimplement in native
258     /*
259     public static double asin(double a) {
260         return StrictMath.asin(a); // default impl. delegates to StrictMath
261     }
262     */
263     // END Android-changed: Reimplement in native
264     @CriticalNative
asin(double a)265     public static native double asin(double a);
266 
267     /**
268      * Returns the arc cosine of a value; the returned angle is in the
269      * range 0.0 through <i>pi</i>.  Special case:
270      * <ul><li>If the argument is NaN or its absolute value is greater
271      * than 1, then the result is NaN.
272      * <li>If the argument is {@code 1.0}, the result is positive zero.
273      * </ul>
274      *
275      * <p>The computed result must be within 1 ulp of the exact result.
276      * Results must be semi-monotonic.
277      *
278      * @param   a   the value whose arc cosine is to be returned.
279      * @return  the arc cosine of the argument.
280      */
281     // BEGIN Android-changed: Reimplement in native
282     /*
283     public static double acos(double a) {
284         return StrictMath.acos(a); // default impl. delegates to StrictMath
285     }
286     */
287     // END Android-changed: Reimplement in native
288     @CriticalNative
acos(double a)289     public static native double acos(double a);
290 
291     /**
292      * Returns the arc tangent of a value; the returned angle is in the
293      * range -<i>pi</i>/2 through <i>pi</i>/2.  Special cases:
294      * <ul><li>If the argument is NaN, then the result is NaN.
295      * <li>If the argument is zero, then the result is a zero with the
296      * same sign as the argument.
297      * <li>If the argument is {@linkplain Double#isInfinite infinite},
298      * then the result is the closest value to <i>pi</i>/2 with the
299      * same sign as the input.
300      * </ul>
301      *
302      * <p>The computed result must be within 1 ulp of the exact result.
303      * Results must be semi-monotonic.
304      *
305      * @param   a   the value whose arc tangent is to be returned.
306      * @return  the arc tangent of the argument.
307      */
308     // BEGIN Android-changed: Reimplement in native
309     /*
310     public static double atan(double a) {
311         return StrictMath.atan(a); // default impl. delegates to StrictMath
312     }
313     */
314     // END Android-changed: Reimplement in native
315     @CriticalNative
atan(double a)316     public static native double atan(double a);
317 
318     /**
319      * Converts an angle measured in degrees to an approximately
320      * equivalent angle measured in radians.  The conversion from
321      * degrees to radians is generally inexact.
322      *
323      * @param   angdeg   an angle, in degrees
324      * @return  the measurement of the angle {@code angdeg}
325      *          in radians.
326      * @since   1.2
327      */
toRadians(double angdeg)328     public static double toRadians(double angdeg) {
329         return angdeg * DEGREES_TO_RADIANS;
330     }
331 
332     /**
333      * Converts an angle measured in radians to an approximately
334      * equivalent angle measured in degrees.  The conversion from
335      * radians to degrees is generally inexact; users should
336      * <i>not</i> expect {@code cos(toRadians(90.0))} to exactly
337      * equal {@code 0.0}.
338      *
339      * @param   angrad   an angle, in radians
340      * @return  the measurement of the angle {@code angrad}
341      *          in degrees.
342      * @since   1.2
343      */
toDegrees(double angrad)344     public static double toDegrees(double angrad) {
345         return angrad * RADIANS_TO_DEGREES;
346     }
347 
348     /**
349      * Returns Euler's number <i>e</i> raised to the power of a
350      * {@code double} value.  Special cases:
351      * <ul><li>If the argument is NaN, the result is NaN.
352      * <li>If the argument is positive infinity, then the result is
353      * positive infinity.
354      * <li>If the argument is negative infinity, then the result is
355      * positive zero.
356      * <li>If the argument is zero, then the result is {@code 1.0}.
357      * </ul>
358      *
359      * <p>The computed result must be within 1 ulp of the exact result.
360      * Results must be semi-monotonic.
361      *
362      * @param   a   the exponent to raise <i>e</i> to.
363      * @return  the value <i>e</i><sup>{@code a}</sup>,
364      *          where <i>e</i> is the base of the natural logarithms.
365      */
366     // BEGIN Android-changed: Reimplement in native
367     /*
368     @IntrinsicCandidate
369     public static double exp(double a) {
370         return StrictMath.exp(a); // default impl. delegates to StrictMath
371     }
372     */
373     // END Android-changed: Reimplement in native
374     @CriticalNative
exp(double a)375     public static native double exp(double a);
376 
377     /**
378      * Returns the natural logarithm (base <i>e</i>) of a {@code double}
379      * value.  Special cases:
380      * <ul><li>If the argument is NaN or less than zero, then the result
381      * is NaN.
382      * <li>If the argument is positive infinity, then the result is
383      * positive infinity.
384      * <li>If the argument is positive zero or negative zero, then the
385      * result is negative infinity.
386      * <li>If the argument is {@code 1.0}, then the result is positive
387      * zero.
388      * </ul>
389      *
390      * <p>The computed result must be within 1 ulp of the exact result.
391      * Results must be semi-monotonic.
392      *
393      * @param   a   a value
394      * @return  the value ln&nbsp;{@code a}, the natural logarithm of
395      *          {@code a}.
396      */
397     // BEGIN Android-changed: Reimplement in native
398     /*
399     @IntrinsicCandidate
400     public static double log(double a) {
401         return StrictMath.log(a); // default impl. delegates to StrictMath
402     }
403     */
404     // END Android-changed: Reimplement in native
405     @CriticalNative
log(double a)406     public static native double log(double a);
407 
408     /**
409      * Returns the base 10 logarithm of a {@code double} value.
410      * Special cases:
411      *
412      * <ul><li>If the argument is NaN or less than zero, then the result
413      * is NaN.
414      * <li>If the argument is positive infinity, then the result is
415      * positive infinity.
416      * <li>If the argument is positive zero or negative zero, then the
417      * result is negative infinity.
418      * <li>If the argument is equal to 10<sup><i>n</i></sup> for
419      * integer <i>n</i>, then the result is <i>n</i>. In particular,
420      * if the argument is {@code 1.0} (10<sup>0</sup>), then the
421      * result is positive zero.
422      * </ul>
423      *
424      * <p>The computed result must be within 1 ulp of the exact result.
425      * Results must be semi-monotonic.
426      *
427      * @param   a   a value
428      * @return  the base 10 logarithm of  {@code a}.
429      * @since 1.5
430      */
431     // BEGIN Android-changed: Reimplement in native
432     /*
433     @IntrinsicCandidate
434     public static double log10(double a) {
435         return StrictMath.log10(a); // default impl. delegates to StrictMath
436     }
437     */
438     // END Android-changed: Reimplement in native
439     @CriticalNative
log10(double a)440     public static native double log10(double a);
441 
442     /**
443      * Returns the correctly rounded positive square root of a
444      * {@code double} value.
445      * Special cases:
446      * <ul><li>If the argument is NaN or less than zero, then the result
447      * is NaN.
448      * <li>If the argument is positive infinity, then the result is positive
449      * infinity.
450      * <li>If the argument is positive zero or negative zero, then the
451      * result is the same as the argument.</ul>
452      * Otherwise, the result is the {@code double} value closest to
453      * the true mathematical square root of the argument value.
454      *
455      * @param   a   a value.
456      * @return  the positive square root of {@code a}.
457      *          If the argument is NaN or less than zero, the result is NaN.
458      */
459     // BEGIN Android-changed: Reimplement in native
460     /*
461     @IntrinsicCandidate
462     public static double sqrt(double a) {
463         return StrictMath.sqrt(a); // default impl. delegates to StrictMath
464                                    // Note that hardware sqrt instructions
465                                    // frequently can be directly used by JITs
466                                    // and should be much faster than doing
467                                    // Math.sqrt in software.
468     }
469     */
470     // END Android-changed: Reimplement in native
471     @CriticalNative
sqrt(double a)472     public static native double sqrt(double a);
473 
474 
475     /**
476      * Returns the cube root of a {@code double} value.  For
477      * positive finite {@code x}, {@code cbrt(-x) ==
478      * -cbrt(x)}; that is, the cube root of a negative value is
479      * the negative of the cube root of that value's magnitude.
480      *
481      * Special cases:
482      *
483      * <ul>
484      *
485      * <li>If the argument is NaN, then the result is NaN.
486      *
487      * <li>If the argument is infinite, then the result is an infinity
488      * with the same sign as the argument.
489      *
490      * <li>If the argument is zero, then the result is a zero with the
491      * same sign as the argument.
492      *
493      * </ul>
494      *
495      * <p>The computed result must be within 1 ulp of the exact result.
496      *
497      * @param   a   a value.
498      * @return  the cube root of {@code a}.
499      * @since 1.5
500      */
501     // BEGIN Android-changed: Reimplement in native
502     /*
503     public static double cbrt(double a) {
504         return StrictMath.cbrt(a);
505     }
506     */
507     // END Android-changed: Reimplement in native
508     @CriticalNative
cbrt(double a)509     public static native double cbrt(double a);
510 
511     /**
512      * Computes the remainder operation on two arguments as prescribed
513      * by the IEEE 754 standard.
514      * The remainder value is mathematically equal to
515      * <code>f1&nbsp;-&nbsp;f2</code>&nbsp;&times;&nbsp;<i>n</i>,
516      * where <i>n</i> is the mathematical integer closest to the exact
517      * mathematical value of the quotient {@code f1/f2}, and if two
518      * mathematical integers are equally close to {@code f1/f2},
519      * then <i>n</i> is the integer that is even. If the remainder is
520      * zero, its sign is the same as the sign of the first argument.
521      * Special cases:
522      * <ul><li>If either argument is NaN, or the first argument is infinite,
523      * or the second argument is positive zero or negative zero, then the
524      * result is NaN.
525      * <li>If the first argument is finite and the second argument is
526      * infinite, then the result is the same as the first argument.</ul>
527      *
528      * @param   f1   the dividend.
529      * @param   f2   the divisor.
530      * @return  the remainder when {@code f1} is divided by
531      *          {@code f2}.
532      */
533     // BEGIN Android-changed: Reimplement in native
534     /*
535     public static double IEEEremainder(double f1, double f2) {
536         return StrictMath.IEEEremainder(f1, f2); // delegate to StrictMath
537     }
538     */
539     // END Android-changed: Reimplement in native
540     @CriticalNative
IEEEremainder(double f1, double f2)541     public static native double IEEEremainder(double f1, double f2);
542 
543     /**
544      * Returns the smallest (closest to negative infinity)
545      * {@code double} value that is greater than or equal to the
546      * argument and is equal to a mathematical integer. Special cases:
547      * <ul><li>If the argument value is already equal to a
548      * mathematical integer, then the result is the same as the
549      * argument.  <li>If the argument is NaN or an infinity or
550      * positive zero or negative zero, then the result is the same as
551      * the argument.  <li>If the argument value is less than zero but
552      * greater than -1.0, then the result is negative zero.</ul> Note
553      * that the value of {@code Math.ceil(x)} is exactly the
554      * value of {@code -Math.floor(-x)}.
555      *
556      *
557      * @param   a   a value.
558      * @return  the smallest (closest to negative infinity)
559      *          floating-point value that is greater than or equal to
560      *          the argument and is equal to a mathematical integer.
561      */
562     // BEGIN Android-changed: Reimplement in native
563     /*
564     @IntrinsicCandidate
565     public static double ceil(double a) {
566         return StrictMath.ceil(a); // default impl. delegates to StrictMath
567     }
568     */
569     // END Android-changed: Reimplement in native
570     @CriticalNative
ceil(double a)571     public static native double ceil(double a);
572 
573     /**
574      * Returns the largest (closest to positive infinity)
575      * {@code double} value that is less than or equal to the
576      * argument and is equal to a mathematical integer. Special cases:
577      * <ul><li>If the argument value is already equal to a
578      * mathematical integer, then the result is the same as the
579      * argument.  <li>If the argument is NaN or an infinity or
580      * positive zero or negative zero, then the result is the same as
581      * the argument.</ul>
582      *
583      * @param   a   a value.
584      * @return  the largest (closest to positive infinity)
585      *          floating-point value that less than or equal to the argument
586      *          and is equal to a mathematical integer.
587      */
588     // BEGIN Android-changed: Reimplement in native
589     /*
590     @IntrinsicCandidate
591     public static double floor(double a) {
592         return StrictMath.floor(a); // default impl. delegates to StrictMath
593     }
594     */
595     // END Android-changed: Reimplement in native
596     @CriticalNative
floor(double a)597     public static native double floor(double a);
598 
599     /**
600      * Returns the {@code double} value that is closest in value
601      * to the argument and is equal to a mathematical integer. If two
602      * {@code double} values that are mathematical integers are
603      * equally close, the result is the integer value that is
604      * even. Special cases:
605      * <ul><li>If the argument value is already equal to a mathematical
606      * integer, then the result is the same as the argument.
607      * <li>If the argument is NaN or an infinity or positive zero or negative
608      * zero, then the result is the same as the argument.</ul>
609      *
610      * @param   a   a {@code double} value.
611      * @return  the closest floating-point value to {@code a} that is
612      *          equal to a mathematical integer.
613      */
614     // BEGIN Android-changed: Reimplement in native
615     /*
616     @IntrinsicCandidate
617     public static double rint(double a) {
618         return StrictMath.rint(a); // default impl. delegates to StrictMath
619     }
620     */
621     // END Android-changed: Reimplement in native
622     @CriticalNative
rint(double a)623     public static native double rint(double a);
624 
625     /**
626      * Returns the angle <i>theta</i> from the conversion of rectangular
627      * coordinates ({@code x},&nbsp;{@code y}) to polar
628      * coordinates (r,&nbsp;<i>theta</i>).
629      * This method computes the phase <i>theta</i> by computing an arc tangent
630      * of {@code y/x} in the range of -<i>pi</i> to <i>pi</i>. Special
631      * cases:
632      * <ul><li>If either argument is NaN, then the result is NaN.
633      * <li>If the first argument is positive zero and the second argument
634      * is positive, or the first argument is positive and finite and the
635      * second argument is positive infinity, then the result is positive
636      * zero.
637      * <li>If the first argument is negative zero and the second argument
638      * is positive, or the first argument is negative and finite and the
639      * second argument is positive infinity, then the result is negative zero.
640      * <li>If the first argument is positive zero and the second argument
641      * is negative, or the first argument is positive and finite and the
642      * second argument is negative infinity, then the result is the
643      * {@code double} value closest to <i>pi</i>.
644      * <li>If the first argument is negative zero and the second argument
645      * is negative, or the first argument is negative and finite and the
646      * second argument is negative infinity, then the result is the
647      * {@code double} value closest to -<i>pi</i>.
648      * <li>If the first argument is positive and the second argument is
649      * positive zero or negative zero, or the first argument is positive
650      * infinity and the second argument is finite, then the result is the
651      * {@code double} value closest to <i>pi</i>/2.
652      * <li>If the first argument is negative and the second argument is
653      * positive zero or negative zero, or the first argument is negative
654      * infinity and the second argument is finite, then the result is the
655      * {@code double} value closest to -<i>pi</i>/2.
656      * <li>If both arguments are positive infinity, then the result is the
657      * {@code double} value closest to <i>pi</i>/4.
658      * <li>If the first argument is positive infinity and the second argument
659      * is negative infinity, then the result is the {@code double}
660      * value closest to 3*<i>pi</i>/4.
661      * <li>If the first argument is negative infinity and the second argument
662      * is positive infinity, then the result is the {@code double} value
663      * closest to -<i>pi</i>/4.
664      * <li>If both arguments are negative infinity, then the result is the
665      * {@code double} value closest to -3*<i>pi</i>/4.</ul>
666      *
667      * <p>The computed result must be within 2 ulps of the exact result.
668      * Results must be semi-monotonic.
669      *
670      * @apiNote
671      * For <i>y</i> with a positive sign and finite nonzero
672      * <i>x</i>, the exact mathematical value of {@code atan2} is
673      * equal to:
674      * <ul>
675      * <li>If <i>x</i> {@literal >} 0, atan(abs(<i>y</i>/<i>x</i>))
676      * <li>If <i>x</i> {@literal <} 0, &pi; - atan(abs(<i>y</i>/<i>x</i>))
677      * </ul>
678      *
679      * @param   y   the ordinate coordinate
680      * @param   x   the abscissa coordinate
681      * @return  the <i>theta</i> component of the point
682      *          (<i>r</i>,&nbsp;<i>theta</i>)
683      *          in polar coordinates that corresponds to the point
684      *          (<i>x</i>,&nbsp;<i>y</i>) in Cartesian coordinates.
685      */
686     // BEGIN Android-changed: Reimplement in native
687     /*
688     @IntrinsicCandidate
689     public static double atan2(double y, double x) {
690         return StrictMath.atan2(y, x); // default impl. delegates to StrictMath
691     }
692     */
693     // END Android-changed: Reimplement in native
694     @CriticalNative
atan2(double y, double x)695     public static native double atan2(double y, double x);
696 
697     // Android-changed: Document that the results from Math are based on libm's behavior.
698     // The cases known to differ with libm's pow():
699     //   If the first argument is 1.0 then result is always 1.0 (not NaN).
700     //   If the first argument is -1.0 and the second argument is infinite, the result is 1.0 (not
701     //   NaN).
702     /**
703      * Returns the value of the first argument raised to the power of the
704      * second argument. Special cases:
705      *
706      * <ul><li>If the second argument is positive or negative zero, then the
707      * result is 1.0.
708      * <li>If the second argument is 1.0, then the result is the same as the
709      * first argument.
710      * <li>If the first argument is 1.0, then the result is 1.0.
711      * <li>If the second argument is NaN, then the result is NaN except where the first argument is
712      * 1.0.
713      * <li>If the first argument is NaN and the second argument is nonzero,
714      * then the result is NaN.
715      *
716      * <li>If
717      * <ul>
718      * <li>the absolute value of the first argument is greater than 1
719      * and the second argument is positive infinity, or
720      * <li>the absolute value of the first argument is less than 1 and
721      * the second argument is negative infinity,
722      * </ul>
723      * then the result is positive infinity.
724      *
725      * <li>If
726      * <ul>
727      * <li>the absolute value of the first argument is greater than 1 and
728      * the second argument is negative infinity, or
729      * <li>the absolute value of the
730      * first argument is less than 1 and the second argument is positive
731      * infinity,
732      * </ul>
733      * then the result is positive zero.
734      *
735      * <li>If the absolute value of the first argument equals 1 and the
736      * second argument is infinite, then the result is 1.0.
737      *
738      * <li>If
739      * <ul>
740      * <li>the first argument is positive zero and the second argument
741      * is greater than zero, or
742      * <li>the first argument is positive infinity and the second
743      * argument is less than zero,
744      * </ul>
745      * then the result is positive zero.
746      *
747      * <li>If
748      * <ul>
749      * <li>the first argument is positive zero and the second argument
750      * is less than zero, or
751      * <li>the first argument is positive infinity and the second
752      * argument is greater than zero,
753      * </ul>
754      * then the result is positive infinity.
755      *
756      * <li>If
757      * <ul>
758      * <li>the first argument is negative zero and the second argument
759      * is greater than zero but not a finite odd integer, or
760      * <li>the first argument is negative infinity and the second
761      * argument is less than zero but not a finite odd integer,
762      * </ul>
763      * then the result is positive zero.
764      *
765      * <li>If
766      * <ul>
767      * <li>the first argument is negative zero and the second argument
768      * is a positive finite odd integer, or
769      * <li>the first argument is negative infinity and the second
770      * argument is a negative finite odd integer,
771      * </ul>
772      * then the result is negative zero.
773      *
774      * <li>If
775      * <ul>
776      * <li>the first argument is negative zero and the second argument
777      * is less than zero but not a finite odd integer, or
778      * <li>the first argument is negative infinity and the second
779      * argument is greater than zero but not a finite odd integer,
780      * </ul>
781      * then the result is positive infinity.
782      *
783      * <li>If
784      * <ul>
785      * <li>the first argument is negative zero and the second argument
786      * is a negative finite odd integer, or
787      * <li>the first argument is negative infinity and the second
788      * argument is a positive finite odd integer,
789      * </ul>
790      * then the result is negative infinity.
791      *
792      * <li>If the first argument is finite and less than zero
793      * <ul>
794      * <li> if the second argument is a finite even integer, the
795      * result is equal to the result of raising the absolute value of
796      * the first argument to the power of the second argument
797      *
798      * <li>if the second argument is a finite odd integer, the result
799      * is equal to the negative of the result of raising the absolute
800      * value of the first argument to the power of the second
801      * argument
802      *
803      * <li>if the second argument is finite and not an integer, then
804      * the result is NaN.
805      * </ul>
806      *
807      * <li>If both arguments are integers, then the result is exactly equal
808      * to the mathematical result of raising the first argument to the power
809      * of the second argument if that result can in fact be represented
810      * exactly as a {@code double} value.</ul>
811      *
812      * <p>(In the foregoing descriptions, a floating-point value is
813      * considered to be an integer if and only if it is finite and a
814      * fixed point of the method {@link #ceil ceil} or,
815      * equivalently, a fixed point of the method {@link #floor
816      * floor}. A value is a fixed point of a one-argument
817      * method if and only if the result of applying the method to the
818      * value is equal to the value.)
819      *
820      * <p>The computed result must be within 1 ulp of the exact result.
821      * Results must be semi-monotonic.
822      *
823      * @apiNote
824      * The special cases definitions of this method differ from the
825      * special case definitions of the IEEE 754 recommended {@code
826      * pow} operation for &plusmn;{@code 1.0} raised to an infinite
827      * power. This method treats such cases as indeterminate and
828      * specifies a NaN is returned. The IEEE 754 specification treats
829      * the infinite power as a large integer (large-magnitude
830      * floating-point numbers are numerically integers, specifically
831      * even integers) and therefore specifies {@code 1.0} be returned.
832      *
833      * @param   a   the base.
834      * @param   b   the exponent.
835      * @return  the value {@code a}<sup>{@code b}</sup>.
836      */
837     // BEGIN Android-changed: Reimplement in native
838     /*
839     @IntrinsicCandidate
840     public static double pow(double a, double b) {
841         return StrictMath.pow(a, b); // default impl. delegates to StrictMath
842     }
843     */
844     // END Android-changed: Reimplement in native
845     @CriticalNative
pow(double a, double b)846     public static native double pow(double a, double b);
847 
848     /**
849      * Returns the closest {@code int} to the argument, with ties
850      * rounding to positive infinity.
851      *
852      * <p>
853      * Special cases:
854      * <ul><li>If the argument is NaN, the result is 0.
855      * <li>If the argument is negative infinity or any value less than or
856      * equal to the value of {@code Integer.MIN_VALUE}, the result is
857      * equal to the value of {@code Integer.MIN_VALUE}.
858      * <li>If the argument is positive infinity or any value greater than or
859      * equal to the value of {@code Integer.MAX_VALUE}, the result is
860      * equal to the value of {@code Integer.MAX_VALUE}.</ul>
861      *
862      * @param   a   a floating-point value to be rounded to an integer.
863      * @return  the value of the argument rounded to the nearest
864      *          {@code int} value.
865      * @see     java.lang.Integer#MAX_VALUE
866      * @see     java.lang.Integer#MIN_VALUE
867      */
round(float a)868     public static int round(float a) {
869         int intBits = Float.floatToRawIntBits(a);
870         int biasedExp = (intBits & FloatConsts.EXP_BIT_MASK)
871                 >> (FloatConsts.SIGNIFICAND_WIDTH - 1);
872         int shift = (FloatConsts.SIGNIFICAND_WIDTH - 2
873                 + FloatConsts.EXP_BIAS) - biasedExp;
874         if ((shift & -32) == 0) { // shift >= 0 && shift < 32
875             // a is a finite number such that pow(2,-32) <= ulp(a) < 1
876             int r = ((intBits & FloatConsts.SIGNIF_BIT_MASK)
877                     | (FloatConsts.SIGNIF_BIT_MASK + 1));
878             if (intBits < 0) {
879                 r = -r;
880             }
881             // In the comments below each Java expression evaluates to the value
882             // the corresponding mathematical expression:
883             // (r) evaluates to a / ulp(a)
884             // (r >> shift) evaluates to floor(a * 2)
885             // ((r >> shift) + 1) evaluates to floor((a + 1/2) * 2)
886             // (((r >> shift) + 1) >> 1) evaluates to floor(a + 1/2)
887             return ((r >> shift) + 1) >> 1;
888         } else {
889             // a is either
890             // - a finite number with abs(a) < exp(2,FloatConsts.SIGNIFICAND_WIDTH-32) < 1/2
891             // - a finite number with ulp(a) >= 1 and hence a is a mathematical integer
892             // - an infinity or NaN
893             return (int) a;
894         }
895     }
896 
897     /**
898      * Returns the closest {@code long} to the argument, with ties
899      * rounding to positive infinity.
900      *
901      * <p>Special cases:
902      * <ul><li>If the argument is NaN, the result is 0.
903      * <li>If the argument is negative infinity or any value less than or
904      * equal to the value of {@code Long.MIN_VALUE}, the result is
905      * equal to the value of {@code Long.MIN_VALUE}.
906      * <li>If the argument is positive infinity or any value greater than or
907      * equal to the value of {@code Long.MAX_VALUE}, the result is
908      * equal to the value of {@code Long.MAX_VALUE}.</ul>
909      *
910      * @param   a   a floating-point value to be rounded to a
911      *          {@code long}.
912      * @return  the value of the argument rounded to the nearest
913      *          {@code long} value.
914      * @see     java.lang.Long#MAX_VALUE
915      * @see     java.lang.Long#MIN_VALUE
916      */
round(double a)917     public static long round(double a) {
918         long longBits = Double.doubleToRawLongBits(a);
919         long biasedExp = (longBits & DoubleConsts.EXP_BIT_MASK)
920                 >> (DoubleConsts.SIGNIFICAND_WIDTH - 1);
921         long shift = (DoubleConsts.SIGNIFICAND_WIDTH - 2
922                 + DoubleConsts.EXP_BIAS) - biasedExp;
923         if ((shift & -64) == 0) { // shift >= 0 && shift < 64
924             // a is a finite number such that pow(2,-64) <= ulp(a) < 1
925             long r = ((longBits & DoubleConsts.SIGNIF_BIT_MASK)
926                     | (DoubleConsts.SIGNIF_BIT_MASK + 1));
927             if (longBits < 0) {
928                 r = -r;
929             }
930             // In the comments below each Java expression evaluates to the value
931             // the corresponding mathematical expression:
932             // (r) evaluates to a / ulp(a)
933             // (r >> shift) evaluates to floor(a * 2)
934             // ((r >> shift) + 1) evaluates to floor((a + 1/2) * 2)
935             // (((r >> shift) + 1) >> 1) evaluates to floor(a + 1/2)
936             return ((r >> shift) + 1) >> 1;
937         } else {
938             // a is either
939             // - a finite number with abs(a) < exp(2,DoubleConsts.SIGNIFICAND_WIDTH-64) < 1/2
940             // - a finite number with ulp(a) >= 1 and hence a is a mathematical integer
941             // - an infinity or NaN
942             return (long) a;
943         }
944     }
945 
946     private static final class RandomNumberGeneratorHolder {
947         static final Random randomNumberGenerator = new Random();
948     }
949 
950     /**
951      * Returns a {@code double} value with a positive sign, greater
952      * than or equal to {@code 0.0} and less than {@code 1.0}.
953      * Returned values are chosen pseudorandomly with (approximately)
954      * uniform distribution from that range.
955      *
956      * <p>When this method is first called, it creates a single new
957      * pseudorandom-number generator, exactly as if by the expression
958      *
959      * <blockquote>{@code new java.util.Random()}</blockquote>
960      *
961      * This new pseudorandom-number generator is used thereafter for
962      * all calls to this method and is used nowhere else.
963      *
964      * <p>This method is properly synchronized to allow correct use by
965      * more than one thread. However, if many threads need to generate
966      * pseudorandom numbers at a great rate, it may reduce contention
967      * for each thread to have its own pseudorandom-number generator.
968      *
969      * @apiNote
970      * As the largest {@code double} value less than {@code 1.0}
971      * is {@code Math.nextDown(1.0)}, a value {@code x} in the closed range
972      * {@code [x1,x2]} where {@code x1<=x2} may be defined by the statements
973      *
974      * <blockquote><pre>{@code
975      * double f = Math.random()/Math.nextDown(1.0);
976      * double x = x1*(1.0 - f) + x2*f;
977      * }</pre></blockquote>
978      *
979      * @return  a pseudorandom {@code double} greater than or equal
980      * to {@code 0.0} and less than {@code 1.0}.
981      * @see #nextDown(double)
982      * @see Random#nextDouble()
983      */
random()984     public static double random() {
985         return RandomNumberGeneratorHolder.randomNumberGenerator.nextDouble();
986     }
987 
988     // Android-added: setRandomSeedInternal(long), called after zygote forks.
989     // This allows different processes to have different random seeds.
990     /**
991      * Set the seed for the pseudo random generator used by {@link #random()}
992      * and {@link #randomIntInternal()}.
993      *
994      * @hide for internal use only.
995      */
setRandomSeedInternal(long seed)996     public static void setRandomSeedInternal(long seed) {
997         RandomNumberGeneratorHolder.randomNumberGenerator.setSeed(seed);
998     }
999 
1000     // Android-added: randomIntInternal() method: like random() but for int.
1001     /**
1002      * @hide for internal use only.
1003      */
randomIntInternal()1004     public static int randomIntInternal() {
1005         return RandomNumberGeneratorHolder.randomNumberGenerator.nextInt();
1006     }
1007 
1008     // Android-added: randomLongInternal() method: like random() but for long.
1009     /**
1010      * @hide for internal use only.
1011      */
randomLongInternal()1012     public static long randomLongInternal() {
1013         return RandomNumberGeneratorHolder.randomNumberGenerator.nextLong();
1014     }
1015 
1016     /**
1017      * Returns the sum of its arguments,
1018      * throwing an exception if the result overflows an {@code int}.
1019      *
1020      * @param x the first value
1021      * @param y the second value
1022      * @return the result
1023      * @throws ArithmeticException if the result overflows an int
1024      * @since 1.8
1025      */
1026     @IntrinsicCandidate
addExact(int x, int y)1027     public static int addExact(int x, int y) {
1028         int r = x + y;
1029         // HD 2-12 Overflow iff both arguments have the opposite sign of the result
1030         if (((x ^ r) & (y ^ r)) < 0) {
1031             throw new ArithmeticException("integer overflow");
1032         }
1033         return r;
1034     }
1035 
1036     /**
1037      * Returns the sum of its arguments,
1038      * throwing an exception if the result overflows a {@code long}.
1039      *
1040      * @param x the first value
1041      * @param y the second value
1042      * @return the result
1043      * @throws ArithmeticException if the result overflows a long
1044      * @since 1.8
1045      */
1046     @IntrinsicCandidate
addExact(long x, long y)1047     public static long addExact(long x, long y) {
1048         long r = x + y;
1049         // HD 2-12 Overflow iff both arguments have the opposite sign of the result
1050         if (((x ^ r) & (y ^ r)) < 0) {
1051             throw new ArithmeticException("long overflow");
1052         }
1053         return r;
1054     }
1055 
1056     /**
1057      * Returns the difference of the arguments,
1058      * throwing an exception if the result overflows an {@code int}.
1059      *
1060      * @param x the first value
1061      * @param y the second value to subtract from the first
1062      * @return the result
1063      * @throws ArithmeticException if the result overflows an int
1064      * @since 1.8
1065      */
1066     @IntrinsicCandidate
subtractExact(int x, int y)1067     public static int subtractExact(int x, int y) {
1068         int r = x - y;
1069         // HD 2-12 Overflow iff the arguments have different signs and
1070         // the sign of the result is different from the sign of x
1071         if (((x ^ y) & (x ^ r)) < 0) {
1072             throw new ArithmeticException("integer overflow");
1073         }
1074         return r;
1075     }
1076 
1077     /**
1078      * Returns the difference of the arguments,
1079      * throwing an exception if the result overflows a {@code long}.
1080      *
1081      * @param x the first value
1082      * @param y the second value to subtract from the first
1083      * @return the result
1084      * @throws ArithmeticException if the result overflows a long
1085      * @since 1.8
1086      */
1087     @IntrinsicCandidate
subtractExact(long x, long y)1088     public static long subtractExact(long x, long y) {
1089         long r = x - y;
1090         // HD 2-12 Overflow iff the arguments have different signs and
1091         // the sign of the result is different from the sign of x
1092         if (((x ^ y) & (x ^ r)) < 0) {
1093             throw new ArithmeticException("long overflow");
1094         }
1095         return r;
1096     }
1097 
1098     /**
1099      * Returns the product of the arguments,
1100      * throwing an exception if the result overflows an {@code int}.
1101      *
1102      * @param x the first value
1103      * @param y the second value
1104      * @return the result
1105      * @throws ArithmeticException if the result overflows an int
1106      * @since 1.8
1107      */
1108     @IntrinsicCandidate
multiplyExact(int x, int y)1109     public static int multiplyExact(int x, int y) {
1110         long r = (long)x * (long)y;
1111         if ((int)r != r) {
1112             throw new ArithmeticException("integer overflow");
1113         }
1114         return (int)r;
1115     }
1116 
1117     /**
1118      * Returns the product of the arguments, throwing an exception if the result
1119      * overflows a {@code long}.
1120      *
1121      * @param x the first value
1122      * @param y the second value
1123      * @return the result
1124      * @throws ArithmeticException if the result overflows a long
1125      * @since 9
1126      */
multiplyExact(long x, int y)1127     public static long multiplyExact(long x, int y) {
1128         return multiplyExact(x, (long)y);
1129     }
1130 
1131     /**
1132      * Returns the product of the arguments,
1133      * throwing an exception if the result overflows a {@code long}.
1134      *
1135      * @param x the first value
1136      * @param y the second value
1137      * @return the result
1138      * @throws ArithmeticException if the result overflows a long
1139      * @since 1.8
1140      */
1141     @IntrinsicCandidate
multiplyExact(long x, long y)1142     public static long multiplyExact(long x, long y) {
1143         long r = x * y;
1144         long ax = Math.abs(x);
1145         long ay = Math.abs(y);
1146         if (((ax | ay) >>> 31 != 0)) {
1147             // Some bits greater than 2^31 that might cause overflow
1148             // Check the result using the divide operator
1149             // and check for the special case of Long.MIN_VALUE * -1
1150            if (((y != 0) && (r / y != x)) ||
1151                (x == Long.MIN_VALUE && y == -1)) {
1152                 throw new ArithmeticException("long overflow");
1153             }
1154         }
1155         return r;
1156     }
1157 
1158     /**
1159      * Returns the argument incremented by one, throwing an exception if the
1160      * result overflows an {@code int}.
1161      * The overflow only occurs for {@linkplain Integer#MAX_VALUE the maximum value}.
1162      *
1163      * @param a the value to increment
1164      * @return the result
1165      * @throws ArithmeticException if the result overflows an int
1166      * @since 1.8
1167      */
1168     @IntrinsicCandidate
incrementExact(int a)1169     public static int incrementExact(int a) {
1170         if (a == Integer.MAX_VALUE) {
1171             throw new ArithmeticException("integer overflow");
1172         }
1173 
1174         return a + 1;
1175     }
1176 
1177     /**
1178      * Returns the argument incremented by one, throwing an exception if the
1179      * result overflows a {@code long}.
1180      * The overflow only occurs for {@linkplain Long#MAX_VALUE the maximum value}.
1181      *
1182      * @param a the value to increment
1183      * @return the result
1184      * @throws ArithmeticException if the result overflows a long
1185      * @since 1.8
1186      */
1187     @IntrinsicCandidate
incrementExact(long a)1188     public static long incrementExact(long a) {
1189         if (a == Long.MAX_VALUE) {
1190             throw new ArithmeticException("long overflow");
1191         }
1192 
1193         return a + 1L;
1194     }
1195 
1196     /**
1197      * Returns the argument decremented by one, throwing an exception if the
1198      * result overflows an {@code int}.
1199      * The overflow only occurs for {@linkplain Integer#MIN_VALUE the minimum value}.
1200      *
1201      * @param a the value to decrement
1202      * @return the result
1203      * @throws ArithmeticException if the result overflows an int
1204      * @since 1.8
1205      */
1206     @IntrinsicCandidate
decrementExact(int a)1207     public static int decrementExact(int a) {
1208         if (a == Integer.MIN_VALUE) {
1209             throw new ArithmeticException("integer overflow");
1210         }
1211 
1212         return a - 1;
1213     }
1214 
1215     /**
1216      * Returns the argument decremented by one, throwing an exception if the
1217      * result overflows a {@code long}.
1218      * The overflow only occurs for {@linkplain Long#MIN_VALUE the minimum value}.
1219      *
1220      * @param a the value to decrement
1221      * @return the result
1222      * @throws ArithmeticException if the result overflows a long
1223      * @since 1.8
1224      */
1225     @IntrinsicCandidate
decrementExact(long a)1226     public static long decrementExact(long a) {
1227         if (a == Long.MIN_VALUE) {
1228             throw new ArithmeticException("long overflow");
1229         }
1230 
1231         return a - 1L;
1232     }
1233 
1234     /**
1235      * Returns the negation of the argument, throwing an exception if the
1236      * result overflows an {@code int}.
1237      * The overflow only occurs for {@linkplain Integer#MIN_VALUE the minimum value}.
1238      *
1239      * @param a the value to negate
1240      * @return the result
1241      * @throws ArithmeticException if the result overflows an int
1242      * @since 1.8
1243      */
1244     @IntrinsicCandidate
negateExact(int a)1245     public static int negateExact(int a) {
1246         if (a == Integer.MIN_VALUE) {
1247             throw new ArithmeticException("integer overflow");
1248         }
1249 
1250         return -a;
1251     }
1252 
1253     /**
1254      * Returns the negation of the argument, throwing an exception if the
1255      * result overflows a {@code long}.
1256      * The overflow only occurs for {@linkplain Long#MIN_VALUE the minimum value}.
1257      *
1258      * @param a the value to negate
1259      * @return the result
1260      * @throws ArithmeticException if the result overflows a long
1261      * @since 1.8
1262      */
1263     @IntrinsicCandidate
negateExact(long a)1264     public static long negateExact(long a) {
1265         if (a == Long.MIN_VALUE) {
1266             throw new ArithmeticException("long overflow");
1267         }
1268 
1269         return -a;
1270     }
1271 
1272     /**
1273      * Returns the value of the {@code long} argument,
1274      * throwing an exception if the value overflows an {@code int}.
1275      *
1276      * @param value the long value
1277      * @return the argument as an int
1278      * @throws ArithmeticException if the {@code argument} overflows an int
1279      * @since 1.8
1280      */
toIntExact(long value)1281     public static int toIntExact(long value) {
1282         if ((int)value != value) {
1283             throw new ArithmeticException("integer overflow");
1284         }
1285         return (int)value;
1286     }
1287 
1288     /**
1289      * Returns the exact mathematical product of the arguments.
1290      *
1291      * @param x the first value
1292      * @param y the second value
1293      * @return the result
1294      * @since 9
1295      */
multiplyFull(int x, int y)1296     public static long multiplyFull(int x, int y) {
1297         return (long)x * (long)y;
1298     }
1299 
1300     /**
1301      * Returns as a {@code long} the most significant 64 bits of the 128-bit
1302      * product of two 64-bit factors.
1303      *
1304      * @param x the first value
1305      * @param y the second value
1306      * @return the result
1307      * @since 9
1308      */
1309     @IntrinsicCandidate
multiplyHigh(long x, long y)1310     public static long multiplyHigh(long x, long y) {
1311         if (x < 0 || y < 0) {
1312             // Use technique from section 8-2 of Henry S. Warren, Jr.,
1313             // Hacker's Delight (2nd ed.) (Addison Wesley, 2013), 173-174.
1314             long x1 = x >> 32;
1315             long x2 = x & 0xFFFFFFFFL;
1316             long y1 = y >> 32;
1317             long y2 = y & 0xFFFFFFFFL;
1318             long z2 = x2 * y2;
1319             long t = x1 * y2 + (z2 >>> 32);
1320             long z1 = t & 0xFFFFFFFFL;
1321             long z0 = t >> 32;
1322             z1 += x2 * y1;
1323             return x1 * y1 + z0 + (z1 >> 32);
1324         } else {
1325             // Use Karatsuba technique with two base 2^32 digits.
1326             long x1 = x >>> 32;
1327             long y1 = y >>> 32;
1328             long x2 = x & 0xFFFFFFFFL;
1329             long y2 = y & 0xFFFFFFFFL;
1330             long A = x1 * y1;
1331             long B = x2 * y2;
1332             long C = (x1 + x2) * (y1 + y2);
1333             long K = C - A - B;
1334             return (((B >>> 32) + K) >>> 32) + A;
1335         }
1336     }
1337 
1338     /**
1339      * Returns the largest (closest to positive infinity)
1340      * {@code int} value that is less than or equal to the algebraic quotient.
1341      * There is one special case, if the dividend is the
1342      * {@linkplain Integer#MIN_VALUE Integer.MIN_VALUE} and the divisor is {@code -1},
1343      * then integer overflow occurs and
1344      * the result is equal to {@code Integer.MIN_VALUE}.
1345      * <p>
1346      * Normal integer division operates under the round to zero rounding mode
1347      * (truncation).  This operation instead acts under the round toward
1348      * negative infinity (floor) rounding mode.
1349      * The floor rounding mode gives different results from truncation
1350      * when the exact result is negative.
1351      * <ul>
1352      *   <li>If the signs of the arguments are the same, the results of
1353      *       {@code floorDiv} and the {@code /} operator are the same.  <br>
1354      *       For example, {@code floorDiv(4, 3) == 1} and {@code (4 / 3) == 1}.</li>
1355      *   <li>If the signs of the arguments are different,  the quotient is negative and
1356      *       {@code floorDiv} returns the integer less than or equal to the quotient
1357      *       and the {@code /} operator returns the integer closest to zero.<br>
1358      *       For example, {@code floorDiv(-4, 3) == -2},
1359      *       whereas {@code (-4 / 3) == -1}.
1360      *   </li>
1361      * </ul>
1362      *
1363      * @param x the dividend
1364      * @param y the divisor
1365      * @return the largest (closest to positive infinity)
1366      * {@code int} value that is less than or equal to the algebraic quotient.
1367      * @throws ArithmeticException if the divisor {@code y} is zero
1368      * @see #floorMod(int, int)
1369      * @see #floor(double)
1370      * @since 1.8
1371      */
floorDiv(int x, int y)1372     public static int floorDiv(int x, int y) {
1373         int r = x / y;
1374         // if the signs are different and modulo not zero, round down
1375         if ((x ^ y) < 0 && (r * y != x)) {
1376             r--;
1377         }
1378         return r;
1379     }
1380 
1381     /**
1382      * Returns the largest (closest to positive infinity)
1383      * {@code long} value that is less than or equal to the algebraic quotient.
1384      * There is one special case, if the dividend is the
1385      * {@linkplain Long#MIN_VALUE Long.MIN_VALUE} and the divisor is {@code -1},
1386      * then integer overflow occurs and
1387      * the result is equal to {@code Long.MIN_VALUE}.
1388      * <p>
1389      * Normal integer division operates under the round to zero rounding mode
1390      * (truncation).  This operation instead acts under the round toward
1391      * negative infinity (floor) rounding mode.
1392      * The floor rounding mode gives different results from truncation
1393      * when the exact result is negative.
1394      * <p>
1395      * For examples, see {@link #floorDiv(int, int)}.
1396      *
1397      * @param x the dividend
1398      * @param y the divisor
1399      * @return the largest (closest to positive infinity)
1400      * {@code int} value that is less than or equal to the algebraic quotient.
1401      * @throws ArithmeticException if the divisor {@code y} is zero
1402      * @see #floorMod(long, int)
1403      * @see #floor(double)
1404      * @since 9
1405      */
floorDiv(long x, int y)1406     public static long floorDiv(long x, int y) {
1407         return floorDiv(x, (long)y);
1408     }
1409 
1410     /**
1411      * Returns the largest (closest to positive infinity)
1412      * {@code long} value that is less than or equal to the algebraic quotient.
1413      * There is one special case, if the dividend is the
1414      * {@linkplain Long#MIN_VALUE Long.MIN_VALUE} and the divisor is {@code -1},
1415      * then integer overflow occurs and
1416      * the result is equal to {@code Long.MIN_VALUE}.
1417      * <p>
1418      * Normal integer division operates under the round to zero rounding mode
1419      * (truncation).  This operation instead acts under the round toward
1420      * negative infinity (floor) rounding mode.
1421      * The floor rounding mode gives different results from truncation
1422      * when the exact result is negative.
1423      * <p>
1424      * For examples, see {@link #floorDiv(int, int)}.
1425      *
1426      * @param x the dividend
1427      * @param y the divisor
1428      * @return the largest (closest to positive infinity)
1429      * {@code long} value that is less than or equal to the algebraic quotient.
1430      * @throws ArithmeticException if the divisor {@code y} is zero
1431      * @see #floorMod(long, long)
1432      * @see #floor(double)
1433      * @since 1.8
1434      */
floorDiv(long x, long y)1435     public static long floorDiv(long x, long y) {
1436         long r = x / y;
1437         // if the signs are different and modulo not zero, round down
1438         if ((x ^ y) < 0 && (r * y != x)) {
1439             r--;
1440         }
1441         return r;
1442     }
1443 
1444     /**
1445      * Returns the floor modulus of the {@code int} arguments.
1446      * <p>
1447      * The floor modulus is {@code x - (floorDiv(x, y) * y)},
1448      * has the same sign as the divisor {@code y}, and
1449      * is in the range of {@code -abs(y) < r < +abs(y)}.
1450      *
1451      * <p>
1452      * The relationship between {@code floorDiv} and {@code floorMod} is such that:
1453      * <ul>
1454      *   <li>{@code floorDiv(x, y) * y + floorMod(x, y) == x}
1455      * </ul>
1456      * <p>
1457      * The difference in values between {@code floorMod} and
1458      * the {@code %} operator is due to the difference between
1459      * {@code floorDiv} that returns the integer less than or equal to the quotient
1460      * and the {@code /} operator that returns the integer closest to zero.
1461      * <p>
1462      * Examples:
1463      * <ul>
1464      *   <li>If the signs of the arguments are the same, the results
1465      *       of {@code floorMod} and the {@code %} operator are the same.<br>
1466      *       <ul>
1467      *       <li>{@code floorMod(+4, +3) == +1}; &nbsp; and {@code (+4 % +3) == +1}</li>
1468      *       <li>{@code floorMod(-4, -3) == -1}; &nbsp; and {@code (-4 % -3) == -1}</li>
1469      *       </ul>
1470      *   <li>If the signs of the arguments are different, the results
1471      *       differ from the {@code %} operator.<br>
1472      *       <ul>
1473      *       <li>{@code floorMod(+4, -3) == -2}; &nbsp; and {@code (+4 % -3) == +1}</li>
1474      *       <li>{@code floorMod(-4, +3) == +2}; &nbsp; and {@code (-4 % +3) == -1}</li>
1475      *       </ul>
1476      *   </li>
1477      * </ul>
1478      * <p>
1479      * If the signs of arguments are unknown and a positive modulus
1480      * is needed it can be computed as {@code (floorMod(x, y) + abs(y)) % abs(y)}.
1481      *
1482      * @param x the dividend
1483      * @param y the divisor
1484      * @return the floor modulus {@code x - (floorDiv(x, y) * y)}
1485      * @throws ArithmeticException if the divisor {@code y} is zero
1486      * @see #floorDiv(int, int)
1487      * @since 1.8
1488      */
floorMod(int x, int y)1489     public static int floorMod(int x, int y) {
1490         int mod = x % y;
1491         // if the signs are different and modulo not zero, adjust result
1492         if ((mod ^ y) < 0 && mod != 0) {
1493             mod += y;
1494         }
1495         return mod;
1496     }
1497 
1498     /**
1499      * Returns the floor modulus of the {@code long} and {@code int} arguments.
1500      * <p>
1501      * The floor modulus is {@code x - (floorDiv(x, y) * y)},
1502      * has the same sign as the divisor {@code y}, and
1503      * is in the range of {@code -abs(y) < r < +abs(y)}.
1504      *
1505      * <p>
1506      * The relationship between {@code floorDiv} and {@code floorMod} is such that:
1507      * <ul>
1508      *   <li>{@code floorDiv(x, y) * y + floorMod(x, y) == x}
1509      * </ul>
1510      * <p>
1511      * For examples, see {@link #floorMod(int, int)}.
1512      *
1513      * @param x the dividend
1514      * @param y the divisor
1515      * @return the floor modulus {@code x - (floorDiv(x, y) * y)}
1516      * @throws ArithmeticException if the divisor {@code y} is zero
1517      * @see #floorDiv(long, int)
1518      * @since 9
1519      */
floorMod(long x, int y)1520     public static int floorMod(long x, int y) {
1521         // Result cannot overflow the range of int.
1522         return (int)floorMod(x, (long)y);
1523     }
1524 
1525     /**
1526      * Returns the floor modulus of the {@code long} arguments.
1527      * <p>
1528      * The floor modulus is {@code x - (floorDiv(x, y) * y)},
1529      * has the same sign as the divisor {@code y}, and
1530      * is in the range of {@code -abs(y) < r < +abs(y)}.
1531      *
1532      * <p>
1533      * The relationship between {@code floorDiv} and {@code floorMod} is such that:
1534      * <ul>
1535      *   <li>{@code floorDiv(x, y) * y + floorMod(x, y) == x}
1536      * </ul>
1537      * <p>
1538      * For examples, see {@link #floorMod(int, int)}.
1539      *
1540      * @param x the dividend
1541      * @param y the divisor
1542      * @return the floor modulus {@code x - (floorDiv(x, y) * y)}
1543      * @throws ArithmeticException if the divisor {@code y} is zero
1544      * @see #floorDiv(long, long)
1545      * @since 1.8
1546      */
floorMod(long x, long y)1547     public static long floorMod(long x, long y) {
1548         long mod = x % y;
1549         // if the signs are different and modulo not zero, adjust result
1550         if ((x ^ y) < 0 && mod != 0) {
1551             mod += y;
1552         }
1553         return mod;
1554     }
1555 
1556     /**
1557      * Returns the absolute value of an {@code int} value.
1558      * If the argument is not negative, the argument is returned.
1559      * If the argument is negative, the negation of the argument is returned.
1560      *
1561      * <p>Note that if the argument is equal to the value of {@link
1562      * Integer#MIN_VALUE}, the most negative representable {@code int}
1563      * value, the result is that same value, which is negative. In
1564      * contrast, the {@link Math#absExact(int)} method throws an
1565      * {@code ArithmeticException} for this value.
1566      *
1567      * @param   a   the argument whose absolute value is to be determined
1568      * @return  the absolute value of the argument.
1569      * @see Math#absExact(int)
1570      */
1571     @IntrinsicCandidate
abs(int a)1572     public static int abs(int a) {
1573         return (a < 0) ? -a : a;
1574     }
1575 
1576     /**
1577      * Returns the mathematical absolute value of an {@code int} value
1578      * if it is exactly representable as an {@code int}, throwing
1579      * {@code ArithmeticException} if the result overflows the
1580      * positive {@code int} range.
1581      *
1582      * <p>Since the range of two's complement integers is asymmetric
1583      * with one additional negative value (JLS {@jls 4.2.1}), the
1584      * mathematical absolute value of {@link Integer#MIN_VALUE}
1585      * overflows the positive {@code int} range, so an exception is
1586      * thrown for that argument.
1587      *
1588      * @param  a  the argument whose absolute value is to be determined
1589      * @return the absolute value of the argument, unless overflow occurs
1590      * @throws ArithmeticException if the argument is {@link Integer#MIN_VALUE}
1591      * @see Math#abs(int)
1592      * @since 15
1593      */
absExact(int a)1594     public static int absExact(int a) {
1595         if (a == Integer.MIN_VALUE)
1596             throw new ArithmeticException(
1597                 "Overflow to represent absolute value of Integer.MIN_VALUE");
1598         else
1599             return abs(a);
1600     }
1601 
1602     /**
1603      * Returns the absolute value of a {@code long} value.
1604      * If the argument is not negative, the argument is returned.
1605      * If the argument is negative, the negation of the argument is returned.
1606      *
1607      * <p>Note that if the argument is equal to the value of {@link
1608      * Long#MIN_VALUE}, the most negative representable {@code long}
1609      * value, the result is that same value, which is negative. In
1610      * contrast, the {@link Math#absExact(long)} method throws an
1611      * {@code ArithmeticException} for this value.
1612      *
1613      * @param   a   the argument whose absolute value is to be determined
1614      * @return  the absolute value of the argument.
1615      * @see Math#absExact(long)
1616      */
1617     @IntrinsicCandidate
abs(long a)1618     public static long abs(long a) {
1619         return (a < 0) ? -a : a;
1620     }
1621 
1622     /**
1623      * Returns the mathematical absolute value of an {@code long} value
1624      * if it is exactly representable as an {@code long}, throwing
1625      * {@code ArithmeticException} if the result overflows the
1626      * positive {@code long} range.
1627      *
1628      * <p>Since the range of two's complement integers is asymmetric
1629      * with one additional negative value (JLS {@jls 4.2.1}), the
1630      * mathematical absolute value of {@link Long#MIN_VALUE} overflows
1631      * the positive {@code long} range, so an exception is thrown for
1632      * that argument.
1633      *
1634      * @param  a  the argument whose absolute value is to be determined
1635      * @return the absolute value of the argument, unless overflow occurs
1636      * @throws ArithmeticException if the argument is {@link Long#MIN_VALUE}
1637      * @see Math#abs(long)
1638      * @since 15
1639      */
absExact(long a)1640     public static long absExact(long a) {
1641         if (a == Long.MIN_VALUE)
1642             throw new ArithmeticException(
1643                 "Overflow to represent absolute value of Long.MIN_VALUE");
1644         else
1645             return abs(a);
1646     }
1647 
1648     /**
1649      * Returns the absolute value of a {@code float} value.
1650      * If the argument is not negative, the argument is returned.
1651      * If the argument is negative, the negation of the argument is returned.
1652      * Special cases:
1653      * <ul><li>If the argument is positive zero or negative zero, the
1654      * result is positive zero.
1655      * <li>If the argument is infinite, the result is positive infinity.
1656      * <li>If the argument is NaN, the result is NaN.</ul>
1657      *
1658      * @apiNote As implied by the above, one valid implementation of
1659      * this method is given by the expression below which computes a
1660      * {@code float} with the same exponent and significand as the
1661      * argument but with a guaranteed zero sign bit indicating a
1662      * positive value:<br>
1663      * {@code Float.intBitsToFloat(0x7fffffff & Float.floatToRawIntBits(a))}
1664      *
1665      * @param   a   the argument whose absolute value is to be determined
1666      * @return  the absolute value of the argument.
1667      */
1668     @IntrinsicCandidate
abs(float a)1669     public static float abs(float a) {
1670         // Android-changed: Implementation modified to exactly match ART intrinsics behavior.
1671         // Note, as a "quality of implementation", rather than pure "spec compliance",
1672         // we require that Math.abs() clears the sign bit (but changes nothing else)
1673         // for all numbers, including NaN (signaling NaN may become quiet though).
1674         // http://b/30758343
1675         // return (a <= 0.0F) ? 0.0F - a : a;
1676         return Float.intBitsToFloat(0x7fffffff & Float.floatToRawIntBits(a));
1677     }
1678 
1679     /**
1680      * Returns the absolute value of a {@code double} value.
1681      * If the argument is not negative, the argument is returned.
1682      * If the argument is negative, the negation of the argument is returned.
1683      * Special cases:
1684      * <ul><li>If the argument is positive zero or negative zero, the result
1685      * is positive zero.
1686      * <li>If the argument is infinite, the result is positive infinity.
1687      * <li>If the argument is NaN, the result is NaN.</ul>
1688      *
1689      * @apiNote As implied by the above, one valid implementation of
1690      * this method is given by the expression below which computes a
1691      * {@code double} with the same exponent and significand as the
1692      * argument but with a guaranteed zero sign bit indicating a
1693      * positive value:<br>
1694      * {@code Double.longBitsToDouble((Double.doubleToRawLongBits(a)<<1)>>>1)}
1695      *
1696      * @param   a   the argument whose absolute value is to be determined
1697      * @return  the absolute value of the argument.
1698      */
1699     @IntrinsicCandidate
abs(double a)1700     public static double abs(double a) {
1701         // Android-changed: Implementation modified to exactly match ART intrinsics behavior.
1702         // Note, as a "quality of implementation", rather than pure "spec compliance",
1703         // we require that Math.abs() clears the sign bit (but changes nothing else)
1704         // for all numbers, including NaN (signaling NaN may become quiet though).
1705         // http://b/30758343
1706         // return (a <= 0.0D) ? 0.0D - a : a;
1707         return Double.longBitsToDouble(0x7fffffffffffffffL & Double.doubleToRawLongBits(a));
1708     }
1709 
1710     /**
1711      * Returns the greater of two {@code int} values. That is, the
1712      * result is the argument closer to the value of
1713      * {@link Integer#MAX_VALUE}. If the arguments have the same value,
1714      * the result is that same value.
1715      *
1716      * @param   a   an argument.
1717      * @param   b   another argument.
1718      * @return  the larger of {@code a} and {@code b}.
1719      */
1720     @IntrinsicCandidate
max(int a, int b)1721     public static int max(int a, int b) {
1722         return (a >= b) ? a : b;
1723     }
1724 
1725     /**
1726      * Returns the greater of two {@code long} values. That is, the
1727      * result is the argument closer to the value of
1728      * {@link Long#MAX_VALUE}. If the arguments have the same value,
1729      * the result is that same value.
1730      *
1731      * @param   a   an argument.
1732      * @param   b   another argument.
1733      * @return  the larger of {@code a} and {@code b}.
1734      */
max(long a, long b)1735     public static long max(long a, long b) {
1736         return (a >= b) ? a : b;
1737     }
1738 
1739     // Use raw bit-wise conversions on guaranteed non-NaN arguments.
1740     private static final long negativeZeroFloatBits  = Float.floatToRawIntBits(-0.0f);
1741     private static final long negativeZeroDoubleBits = Double.doubleToRawLongBits(-0.0d);
1742 
1743     /**
1744      * Returns the greater of two {@code float} values.  That is,
1745      * the result is the argument closer to positive infinity. If the
1746      * arguments have the same value, the result is that same
1747      * value. If either value is NaN, then the result is NaN.  Unlike
1748      * the numerical comparison operators, this method considers
1749      * negative zero to be strictly smaller than positive zero. If one
1750      * argument is positive zero and the other negative zero, the
1751      * result is positive zero.
1752      *
1753      * @param   a   an argument.
1754      * @param   b   another argument.
1755      * @return  the larger of {@code a} and {@code b}.
1756      */
1757     @IntrinsicCandidate
max(float a, float b)1758     public static float max(float a, float b) {
1759         if (a != a)
1760             return a;   // a is NaN
1761         if ((a == 0.0f) &&
1762             (b == 0.0f) &&
1763             (Float.floatToRawIntBits(a) == negativeZeroFloatBits)) {
1764             // Raw conversion ok since NaN can't map to -0.0.
1765             return b;
1766         }
1767         return (a >= b) ? a : b;
1768     }
1769 
1770     /**
1771      * Returns the greater of two {@code double} values.  That
1772      * is, the result is the argument closer to positive infinity. If
1773      * the arguments have the same value, the result is that same
1774      * value. If either value is NaN, then the result is NaN.  Unlike
1775      * the numerical comparison operators, this method considers
1776      * negative zero to be strictly smaller than positive zero. If one
1777      * argument is positive zero and the other negative zero, the
1778      * result is positive zero.
1779      *
1780      * @param   a   an argument.
1781      * @param   b   another argument.
1782      * @return  the larger of {@code a} and {@code b}.
1783      */
1784     @IntrinsicCandidate
max(double a, double b)1785     public static double max(double a, double b) {
1786         if (a != a)
1787             return a;   // a is NaN
1788         if ((a == 0.0d) &&
1789             (b == 0.0d) &&
1790             (Double.doubleToRawLongBits(a) == negativeZeroDoubleBits)) {
1791             // Raw conversion ok since NaN can't map to -0.0.
1792             return b;
1793         }
1794         return (a >= b) ? a : b;
1795     }
1796 
1797     /**
1798      * Returns the smaller of two {@code int} values. That is,
1799      * the result the argument closer to the value of
1800      * {@link Integer#MIN_VALUE}.  If the arguments have the same
1801      * value, the result is that same value.
1802      *
1803      * @param   a   an argument.
1804      * @param   b   another argument.
1805      * @return  the smaller of {@code a} and {@code b}.
1806      */
1807     @IntrinsicCandidate
min(int a, int b)1808     public static int min(int a, int b) {
1809         return (a <= b) ? a : b;
1810     }
1811 
1812     /**
1813      * Returns the smaller of two {@code long} values. That is,
1814      * the result is the argument closer to the value of
1815      * {@link Long#MIN_VALUE}. If the arguments have the same
1816      * value, the result is that same value.
1817      *
1818      * @param   a   an argument.
1819      * @param   b   another argument.
1820      * @return  the smaller of {@code a} and {@code b}.
1821      */
min(long a, long b)1822     public static long min(long a, long b) {
1823         return (a <= b) ? a : b;
1824     }
1825 
1826     /**
1827      * Returns the smaller of two {@code float} values.  That is,
1828      * the result is the value closer to negative infinity. If the
1829      * arguments have the same value, the result is that same
1830      * value. If either value is NaN, then the result is NaN.  Unlike
1831      * the numerical comparison operators, this method considers
1832      * negative zero to be strictly smaller than positive zero.  If
1833      * one argument is positive zero and the other is negative zero,
1834      * the result is negative zero.
1835      *
1836      * @param   a   an argument.
1837      * @param   b   another argument.
1838      * @return  the smaller of {@code a} and {@code b}.
1839      */
1840     @IntrinsicCandidate
min(float a, float b)1841     public static float min(float a, float b) {
1842         if (a != a)
1843             return a;   // a is NaN
1844         if ((a == 0.0f) &&
1845             (b == 0.0f) &&
1846             (Float.floatToRawIntBits(b) == negativeZeroFloatBits)) {
1847             // Raw conversion ok since NaN can't map to -0.0.
1848             return b;
1849         }
1850         return (a <= b) ? a : b;
1851     }
1852 
1853     /**
1854      * Returns the smaller of two {@code double} values.  That
1855      * is, the result is the value closer to negative infinity. If the
1856      * arguments have the same value, the result is that same
1857      * value. If either value is NaN, then the result is NaN.  Unlike
1858      * the numerical comparison operators, this method considers
1859      * negative zero to be strictly smaller than positive zero. If one
1860      * argument is positive zero and the other is negative zero, the
1861      * result is negative zero.
1862      *
1863      * @param   a   an argument.
1864      * @param   b   another argument.
1865      * @return  the smaller of {@code a} and {@code b}.
1866      */
1867     @IntrinsicCandidate
min(double a, double b)1868     public static double min(double a, double b) {
1869         if (a != a)
1870             return a;   // a is NaN
1871         if ((a == 0.0d) &&
1872             (b == 0.0d) &&
1873             (Double.doubleToRawLongBits(b) == negativeZeroDoubleBits)) {
1874             // Raw conversion ok since NaN can't map to -0.0.
1875             return b;
1876         }
1877         return (a <= b) ? a : b;
1878     }
1879 
1880     /**
1881      * Returns the fused multiply add of the three arguments; that is,
1882      * returns the exact product of the first two arguments summed
1883      * with the third argument and then rounded once to the nearest
1884      * {@code double}.
1885      *
1886      * The rounding is done using the {@linkplain
1887      * java.math.RoundingMode#HALF_EVEN round to nearest even
1888      * rounding mode}.
1889      *
1890      * In contrast, if {@code a * b + c} is evaluated as a regular
1891      * floating-point expression, two rounding errors are involved,
1892      * the first for the multiply operation, the second for the
1893      * addition operation.
1894      *
1895      * <p>Special cases:
1896      * <ul>
1897      * <li> If any argument is NaN, the result is NaN.
1898      *
1899      * <li> If one of the first two arguments is infinite and the
1900      * other is zero, the result is NaN.
1901      *
1902      * <li> If the exact product of the first two arguments is infinite
1903      * (in other words, at least one of the arguments is infinite and
1904      * the other is neither zero nor NaN) and the third argument is an
1905      * infinity of the opposite sign, the result is NaN.
1906      *
1907      * </ul>
1908      *
1909      * <p>Note that {@code fma(a, 1.0, c)} returns the same
1910      * result as ({@code a + c}).  However,
1911      * {@code fma(a, b, +0.0)} does <em>not</em> always return the
1912      * same result as ({@code a * b}) since
1913      * {@code fma(-0.0, +0.0, +0.0)} is {@code +0.0} while
1914      * ({@code -0.0 * +0.0}) is {@code -0.0}; {@code fma(a, b, -0.0)} is
1915      * equivalent to ({@code a * b}) however.
1916      *
1917      * @apiNote This method corresponds to the fusedMultiplyAdd
1918      * operation defined in IEEE 754-2008.
1919      *
1920      * @param a a value
1921      * @param b a value
1922      * @param c a value
1923      *
1924      * @return (<i>a</i>&nbsp;&times;&nbsp;<i>b</i>&nbsp;+&nbsp;<i>c</i>)
1925      * computed, as if with unlimited range and precision, and rounded
1926      * once to the nearest {@code double} value
1927      *
1928      * @since 9
1929      */
1930     @IntrinsicCandidate
fma(double a, double b, double c)1931     public static double fma(double a, double b, double c) {
1932         /*
1933          * Infinity and NaN arithmetic is not quite the same with two
1934          * roundings as opposed to just one so the simple expression
1935          * "a * b + c" cannot always be used to compute the correct
1936          * result.  With two roundings, the product can overflow and
1937          * if the addend is infinite, a spurious NaN can be produced
1938          * if the infinity from the overflow and the infinite addend
1939          * have opposite signs.
1940          */
1941 
1942         // First, screen for and handle non-finite input values whose
1943         // arithmetic is not supported by BigDecimal.
1944         if (Double.isNaN(a) || Double.isNaN(b) || Double.isNaN(c)) {
1945             return Double.NaN;
1946         } else { // All inputs non-NaN
1947             boolean infiniteA = Double.isInfinite(a);
1948             boolean infiniteB = Double.isInfinite(b);
1949             boolean infiniteC = Double.isInfinite(c);
1950             double result;
1951 
1952             if (infiniteA || infiniteB || infiniteC) {
1953                 if (infiniteA && b == 0.0 ||
1954                     infiniteB && a == 0.0 ) {
1955                     return Double.NaN;
1956                 }
1957                 // Store product in a double field to cause an
1958                 // overflow even if non-strictfp evaluation is being
1959                 // used.
1960                 double product = a * b;
1961                 if (Double.isInfinite(product) && !infiniteA && !infiniteB) {
1962                     // Intermediate overflow; might cause a
1963                     // spurious NaN if added to infinite c.
1964                     assert Double.isInfinite(c);
1965                     return c;
1966                 } else {
1967                     result = product + c;
1968                     assert !Double.isFinite(result);
1969                     return result;
1970                 }
1971             } else { // All inputs finite
1972                 BigDecimal product = (new BigDecimal(a)).multiply(new BigDecimal(b));
1973                 if (c == 0.0) { // Positive or negative zero
1974                     // If the product is an exact zero, use a
1975                     // floating-point expression to compute the sign
1976                     // of the zero final result. The product is an
1977                     // exact zero if and only if at least one of a and
1978                     // b is zero.
1979                     if (a == 0.0 || b == 0.0) {
1980                         return a * b + c;
1981                     } else {
1982                         // The sign of a zero addend doesn't matter if
1983                         // the product is nonzero. The sign of a zero
1984                         // addend is not factored in the result if the
1985                         // exact product is nonzero but underflows to
1986                         // zero; see IEEE-754 2008 section 6.3 "The
1987                         // sign bit".
1988                         return product.doubleValue();
1989                     }
1990                 } else {
1991                     return product.add(new BigDecimal(c)).doubleValue();
1992                 }
1993             }
1994         }
1995     }
1996 
1997     /**
1998      * Returns the fused multiply add of the three arguments; that is,
1999      * returns the exact product of the first two arguments summed
2000      * with the third argument and then rounded once to the nearest
2001      * {@code float}.
2002      *
2003      * The rounding is done using the {@linkplain
2004      * java.math.RoundingMode#HALF_EVEN round to nearest even
2005      * rounding mode}.
2006      *
2007      * In contrast, if {@code a * b + c} is evaluated as a regular
2008      * floating-point expression, two rounding errors are involved,
2009      * the first for the multiply operation, the second for the
2010      * addition operation.
2011      *
2012      * <p>Special cases:
2013      * <ul>
2014      * <li> If any argument is NaN, the result is NaN.
2015      *
2016      * <li> If one of the first two arguments is infinite and the
2017      * other is zero, the result is NaN.
2018      *
2019      * <li> If the exact product of the first two arguments is infinite
2020      * (in other words, at least one of the arguments is infinite and
2021      * the other is neither zero nor NaN) and the third argument is an
2022      * infinity of the opposite sign, the result is NaN.
2023      *
2024      * </ul>
2025      *
2026      * <p>Note that {@code fma(a, 1.0f, c)} returns the same
2027      * result as ({@code a + c}).  However,
2028      * {@code fma(a, b, +0.0f)} does <em>not</em> always return the
2029      * same result as ({@code a * b}) since
2030      * {@code fma(-0.0f, +0.0f, +0.0f)} is {@code +0.0f} while
2031      * ({@code -0.0f * +0.0f}) is {@code -0.0f}; {@code fma(a, b, -0.0f)} is
2032      * equivalent to ({@code a * b}) however.
2033      *
2034      * @apiNote This method corresponds to the fusedMultiplyAdd
2035      * operation defined in IEEE 754-2008.
2036      *
2037      * @param a a value
2038      * @param b a value
2039      * @param c a value
2040      *
2041      * @return (<i>a</i>&nbsp;&times;&nbsp;<i>b</i>&nbsp;+&nbsp;<i>c</i>)
2042      * computed, as if with unlimited range and precision, and rounded
2043      * once to the nearest {@code float} value
2044      *
2045      * @since 9
2046      */
2047     @IntrinsicCandidate
fma(float a, float b, float c)2048     public static float fma(float a, float b, float c) {
2049         if (Float.isFinite(a) && Float.isFinite(b) && Float.isFinite(c)) {
2050             if (a == 0.0 || b == 0.0) {
2051                 return a * b + c; // Handled signed zero cases
2052             } else {
2053                 return (new BigDecimal((double)a * (double)b) // Exact multiply
2054                         .add(new BigDecimal((double)c)))      // Exact sum
2055                     .floatValue();                            // One rounding
2056                                                               // to a float value
2057             }
2058         } else {
2059             // At least one of a,b, and c is non-finite. The result
2060             // will be non-finite as well and will be the same
2061             // non-finite value under double as float arithmetic.
2062             return (float)fma((double)a, (double)b, (double)c);
2063         }
2064     }
2065 
2066     /**
2067      * Returns the size of an ulp of the argument.  An ulp, unit in
2068      * the last place, of a {@code double} value is the positive
2069      * distance between this floating-point value and the {@code
2070      * double} value next larger in magnitude.  Note that for non-NaN
2071      * <i>x</i>, <code>ulp(-<i>x</i>) == ulp(<i>x</i>)</code>.
2072      *
2073      * <p>Special Cases:
2074      * <ul>
2075      * <li> If the argument is NaN, then the result is NaN.
2076      * <li> If the argument is positive or negative infinity, then the
2077      * result is positive infinity.
2078      * <li> If the argument is positive or negative zero, then the result is
2079      * {@code Double.MIN_VALUE}.
2080      * <li> If the argument is &plusmn;{@code Double.MAX_VALUE}, then
2081      * the result is equal to 2<sup>971</sup>.
2082      * </ul>
2083      *
2084      * @param d the floating-point value whose ulp is to be returned
2085      * @return the size of an ulp of the argument
2086      * @author Joseph D. Darcy
2087      * @since 1.5
2088      */
ulp(double d)2089     public static double ulp(double d) {
2090         int exp = getExponent(d);
2091 
2092         return switch(exp) {
2093             case Double.MAX_EXPONENT + 1 -> Math.abs(d);      // NaN or infinity
2094             case Double.MIN_EXPONENT - 1 -> Double.MIN_VALUE; // zero or subnormal
2095             default -> {
2096                 assert exp <= Double.MAX_EXPONENT && exp >= Double.MIN_EXPONENT;
2097 
2098                 // ulp(x) is usually 2^(SIGNIFICAND_WIDTH-1)*(2^ilogb(x))
2099                 exp = exp - (DoubleConsts.SIGNIFICAND_WIDTH - 1);
2100                 if (exp >= Double.MIN_EXPONENT) {
2101                     yield powerOfTwoD(exp);
2102                 } else {
2103                     // return a subnormal result; left shift integer
2104                     // representation of Double.MIN_VALUE appropriate
2105                     // number of positions
2106                     yield Double.longBitsToDouble(1L <<
2107                             (exp - (Double.MIN_EXPONENT - (DoubleConsts.SIGNIFICAND_WIDTH - 1))));
2108                 }
2109             }
2110         };
2111     }
2112 
2113     /**
2114      * Returns the size of an ulp of the argument.  An ulp, unit in
2115      * the last place, of a {@code float} value is the positive
2116      * distance between this floating-point value and the {@code
2117      * float} value next larger in magnitude.  Note that for non-NaN
2118      * <i>x</i>, <code>ulp(-<i>x</i>) == ulp(<i>x</i>)</code>.
2119      *
2120      * <p>Special Cases:
2121      * <ul>
2122      * <li> If the argument is NaN, then the result is NaN.
2123      * <li> If the argument is positive or negative infinity, then the
2124      * result is positive infinity.
2125      * <li> If the argument is positive or negative zero, then the result is
2126      * {@code Float.MIN_VALUE}.
2127      * <li> If the argument is &plusmn;{@code Float.MAX_VALUE}, then
2128      * the result is equal to 2<sup>104</sup>.
2129      * </ul>
2130      *
2131      * @param f the floating-point value whose ulp is to be returned
2132      * @return the size of an ulp of the argument
2133      * @author Joseph D. Darcy
2134      * @since 1.5
2135      */
ulp(float f)2136     public static float ulp(float f) {
2137         int exp = getExponent(f);
2138 
2139         return switch(exp) {
2140             case Float.MAX_EXPONENT + 1 -> Math.abs(f);     // NaN or infinity
2141             case Float.MIN_EXPONENT - 1 -> Float.MIN_VALUE; // zero or subnormal
2142             default -> {
2143                 assert exp <= Float.MAX_EXPONENT && exp >= Float.MIN_EXPONENT;
2144 
2145                 // ulp(x) is usually 2^(SIGNIFICAND_WIDTH-1)*(2^ilogb(x))
2146                 exp = exp - (FloatConsts.SIGNIFICAND_WIDTH - 1);
2147                 if (exp >= Float.MIN_EXPONENT) {
2148                     yield powerOfTwoF(exp);
2149                 } else {
2150                     // return a subnormal result; left shift integer
2151                     // representation of FloatConsts.MIN_VALUE appropriate
2152                     // number of positions
2153                     yield Float.intBitsToFloat(1 <<
2154                             (exp - (Float.MIN_EXPONENT - (FloatConsts.SIGNIFICAND_WIDTH - 1))));
2155                 }
2156             }
2157         };
2158     }
2159 
2160     /**
2161      * Returns the signum function of the argument; zero if the argument
2162      * is zero, 1.0 if the argument is greater than zero, -1.0 if the
2163      * argument is less than zero.
2164      *
2165      * <p>Special Cases:
2166      * <ul>
2167      * <li> If the argument is NaN, then the result is NaN.
2168      * <li> If the argument is positive zero or negative zero, then the
2169      *      result is the same as the argument.
2170      * </ul>
2171      *
2172      * @param d the floating-point value whose signum is to be returned
2173      * @return the signum function of the argument
2174      * @author Joseph D. Darcy
2175      * @since 1.5
2176      */
2177     @IntrinsicCandidate
2178     public static double signum(double d) {
2179         return (d == 0.0 || Double.isNaN(d))?d:copySign(1.0, d);
2180     }
2181 
2182     /**
2183      * Returns the signum function of the argument; zero if the argument
2184      * is zero, 1.0f if the argument is greater than zero, -1.0f if the
2185      * argument is less than zero.
2186      *
2187      * <p>Special Cases:
2188      * <ul>
2189      * <li> If the argument is NaN, then the result is NaN.
2190      * <li> If the argument is positive zero or negative zero, then the
2191      *      result is the same as the argument.
2192      * </ul>
2193      *
2194      * @param f the floating-point value whose signum is to be returned
2195      * @return the signum function of the argument
2196      * @author Joseph D. Darcy
2197      * @since 1.5
2198      */
2199     @IntrinsicCandidate
2200     public static float signum(float f) {
2201         return (f == 0.0f || Float.isNaN(f))?f:copySign(1.0f, f);
2202     }
2203 
2204     /**
2205      * Returns the hyperbolic sine of a {@code double} value.
2206      * The hyperbolic sine of <i>x</i> is defined to be
2207      * (<i>e<sup>x</sup>&nbsp;-&nbsp;e<sup>-x</sup></i>)/2
2208      * where <i>e</i> is {@linkplain Math#E Euler's number}.
2209      *
2210      * <p>Special cases:
2211      * <ul>
2212      *
2213      * <li>If the argument is NaN, then the result is NaN.
2214      *
2215      * <li>If the argument is infinite, then the result is an infinity
2216      * with the same sign as the argument.
2217      *
2218      * <li>If the argument is zero, then the result is a zero with the
2219      * same sign as the argument.
2220      *
2221      * </ul>
2222      *
2223      * <p>The computed result must be within 2.5 ulps of the exact result.
2224      *
2225      * @param   x The number whose hyperbolic sine is to be returned.
2226      * @return  The hyperbolic sine of {@code x}.
2227      * @since 1.5
2228      */
2229     // BEGIN Android-changed: Reimplement in native
2230     /*
2231     public static double sinh(double x) {
2232         return StrictMath.sinh(x);
2233     }
2234     */
2235     // END Android-changed: Reimplement in native
2236     @CriticalNative
2237     public static native double sinh(double x);
2238 
2239     /**
2240      * Returns the hyperbolic cosine of a {@code double} value.
2241      * The hyperbolic cosine of <i>x</i> is defined to be
2242      * (<i>e<sup>x</sup>&nbsp;+&nbsp;e<sup>-x</sup></i>)/2
2243      * where <i>e</i> is {@linkplain Math#E Euler's number}.
2244      *
2245      * <p>Special cases:
2246      * <ul>
2247      *
2248      * <li>If the argument is NaN, then the result is NaN.
2249      *
2250      * <li>If the argument is infinite, then the result is positive
2251      * infinity.
2252      *
2253      * <li>If the argument is zero, then the result is {@code 1.0}.
2254      *
2255      * </ul>
2256      *
2257      * <p>The computed result must be within 2.5 ulps of the exact result.
2258      *
2259      * @param   x The number whose hyperbolic cosine is to be returned.
2260      * @return  The hyperbolic cosine of {@code x}.
2261      * @since 1.5
2262      */
2263     // BEGIN Android-changed: Reimplement in native
2264     /*
2265     public static double cosh(double x) {
2266         return StrictMath.cosh(x);
2267     }
2268     */
2269     // END Android-changed: Reimplement in native
2270     @CriticalNative
2271     public static native double cosh(double x);
2272 
2273     /**
2274      * Returns the hyperbolic tangent of a {@code double} value.
2275      * The hyperbolic tangent of <i>x</i> is defined to be
2276      * (<i>e<sup>x</sup>&nbsp;-&nbsp;e<sup>-x</sup></i>)/(<i>e<sup>x</sup>&nbsp;+&nbsp;e<sup>-x</sup></i>),
2277      * in other words, {@linkplain Math#sinh
2278      * sinh(<i>x</i>)}/{@linkplain Math#cosh cosh(<i>x</i>)}.  Note
2279      * that the absolute value of the exact tanh is always less than
2280      * 1.
2281      *
2282      * <p>Special cases:
2283      * <ul>
2284      *
2285      * <li>If the argument is NaN, then the result is NaN.
2286      *
2287      * <li>If the argument is zero, then the result is a zero with the
2288      * same sign as the argument.
2289      *
2290      * <li>If the argument is positive infinity, then the result is
2291      * {@code +1.0}.
2292      *
2293      * <li>If the argument is negative infinity, then the result is
2294      * {@code -1.0}.
2295      *
2296      * </ul>
2297      *
2298      * <p>The computed result must be within 2.5 ulps of the exact result.
2299      * The result of {@code tanh} for any finite input must have
2300      * an absolute value less than or equal to 1.  Note that once the
2301      * exact result of tanh is within 1/2 of an ulp of the limit value
2302      * of &plusmn;1, correctly signed &plusmn;{@code 1.0} should
2303      * be returned.
2304      *
2305      * @param   x The number whose hyperbolic tangent is to be returned.
2306      * @return  The hyperbolic tangent of {@code x}.
2307      * @since 1.5
2308      */
2309     // BEGIN Android-changed: Reimplement in native
2310     /*
2311     public static double tanh(double x) {
2312         return StrictMath.tanh(x);
2313     }
2314     */
2315     // END Android-changed: Reimplement in native
2316     @CriticalNative
2317     public static native double tanh(double x);
2318 
2319     /**
2320      * Returns sqrt(<i>x</i><sup>2</sup>&nbsp;+<i>y</i><sup>2</sup>)
2321      * without intermediate overflow or underflow.
2322      *
2323      * <p>Special cases:
2324      * <ul>
2325      *
2326      * <li> If either argument is infinite, then the result
2327      * is positive infinity.
2328      *
2329      * <li> If either argument is NaN and neither argument is infinite,
2330      * then the result is NaN.
2331      *
2332      * <li> If both arguments are zero, the result is positive zero.
2333      * </ul>
2334      *
2335      * <p>The computed result must be within 1 ulp of the exact
2336      * result.  If one parameter is held constant, the results must be
2337      * semi-monotonic in the other parameter.
2338      *
2339      * @param x a value
2340      * @param y a value
2341      * @return sqrt(<i>x</i><sup>2</sup>&nbsp;+<i>y</i><sup>2</sup>)
2342      * without intermediate overflow or underflow
2343      * @since 1.5
2344      */
2345     // BEGIN Android-changed: Reimplement in native
2346     /*
2347     public static double hypot(double x, double y) {
2348         return StrictMath.hypot(x, y);
2349     }
2350     */
2351     // END Android-changed: Reimplement in native
2352     @CriticalNative
2353     public static native double hypot(double x, double y);
2354 
2355     /**
2356      * Returns <i>e</i><sup>x</sup>&nbsp;-1.  Note that for values of
2357      * <i>x</i> near 0, the exact sum of
2358      * {@code expm1(x)}&nbsp;+&nbsp;1 is much closer to the true
2359      * result of <i>e</i><sup>x</sup> than {@code exp(x)}.
2360      *
2361      * <p>Special cases:
2362      * <ul>
2363      * <li>If the argument is NaN, the result is NaN.
2364      *
2365      * <li>If the argument is positive infinity, then the result is
2366      * positive infinity.
2367      *
2368      * <li>If the argument is negative infinity, then the result is
2369      * -1.0.
2370      *
2371      * <li>If the argument is zero, then the result is a zero with the
2372      * same sign as the argument.
2373      *
2374      * </ul>
2375      *
2376      * <p>The computed result must be within 1 ulp of the exact result.
2377      * Results must be semi-monotonic.  The result of
2378      * {@code expm1} for any finite input must be greater than or
2379      * equal to {@code -1.0}.  Note that once the exact result of
2380      * <i>e</i><sup>{@code x}</sup>&nbsp;-&nbsp;1 is within 1/2
2381      * ulp of the limit value -1, {@code -1.0} should be
2382      * returned.
2383      *
2384      * @param   x   the exponent to raise <i>e</i> to in the computation of
2385      *              <i>e</i><sup>{@code x}</sup>&nbsp;-1.
2386      * @return  the value <i>e</i><sup>{@code x}</sup>&nbsp;-&nbsp;1.
2387      * @since 1.5
2388      */
2389     // BEGIN Android-changed: Reimplement in native
2390     /*
2391     public static double expm1(double x) {
2392         return StrictMath.expm1(x);
2393     }
2394     */
2395     // END Android-changed: Reimplement in native
2396     @CriticalNative
2397     public static native double expm1(double x);
2398 
2399     /**
2400      * Returns the natural logarithm of the sum of the argument and 1.
2401      * Note that for small values {@code x}, the result of
2402      * {@code log1p(x)} is much closer to the true result of ln(1
2403      * + {@code x}) than the floating-point evaluation of
2404      * {@code log(1.0+x)}.
2405      *
2406      * <p>Special cases:
2407      *
2408      * <ul>
2409      *
2410      * <li>If the argument is NaN or less than -1, then the result is
2411      * NaN.
2412      *
2413      * <li>If the argument is positive infinity, then the result is
2414      * positive infinity.
2415      *
2416      * <li>If the argument is negative one, then the result is
2417      * negative infinity.
2418      *
2419      * <li>If the argument is zero, then the result is a zero with the
2420      * same sign as the argument.
2421      *
2422      * </ul>
2423      *
2424      * <p>The computed result must be within 1 ulp of the exact result.
2425      * Results must be semi-monotonic.
2426      *
2427      * @param   x   a value
2428      * @return the value ln({@code x}&nbsp;+&nbsp;1), the natural
2429      * log of {@code x}&nbsp;+&nbsp;1
2430      * @since 1.5
2431      */
2432     // BEGIN Android-changed: Reimplement in native
2433     /*
2434     public static double log1p(double x) {
2435         return StrictMath.log1p(x);
2436     }
2437     */
2438     // END Android-changed: Reimplement in native
2439     @CriticalNative
2440     public static native double log1p(double x);
2441 
2442     /**
2443      * Returns the first floating-point argument with the sign of the
2444      * second floating-point argument.  Note that unlike the {@link
2445      * StrictMath#copySign(double, double) StrictMath.copySign}
2446      * method, this method does not require NaN {@code sign}
2447      * arguments to be treated as positive values; implementations are
2448      * permitted to treat some NaN arguments as positive and other NaN
2449      * arguments as negative to allow greater performance.
2450      *
2451      * @param magnitude  the parameter providing the magnitude of the result
2452      * @param sign   the parameter providing the sign of the result
2453      * @return a value with the magnitude of {@code magnitude}
2454      * and the sign of {@code sign}.
2455      * @since 1.6
2456      */
2457     @IntrinsicCandidate
2458     public static double copySign(double magnitude, double sign) {
2459         return Double.longBitsToDouble((Double.doubleToRawLongBits(sign) &
2460                                         (DoubleConsts.SIGN_BIT_MASK)) |
2461                                        (Double.doubleToRawLongBits(magnitude) &
2462                                         (DoubleConsts.EXP_BIT_MASK |
2463                                          DoubleConsts.SIGNIF_BIT_MASK)));
2464     }
2465 
2466     /**
2467      * Returns the first floating-point argument with the sign of the
2468      * second floating-point argument.  Note that unlike the {@link
2469      * StrictMath#copySign(float, float) StrictMath.copySign}
2470      * method, this method does not require NaN {@code sign}
2471      * arguments to be treated as positive values; implementations are
2472      * permitted to treat some NaN arguments as positive and other NaN
2473      * arguments as negative to allow greater performance.
2474      *
2475      * @param magnitude  the parameter providing the magnitude of the result
2476      * @param sign   the parameter providing the sign of the result
2477      * @return a value with the magnitude of {@code magnitude}
2478      * and the sign of {@code sign}.
2479      * @since 1.6
2480      */
2481     @IntrinsicCandidate
2482     public static float copySign(float magnitude, float sign) {
2483         return Float.intBitsToFloat((Float.floatToRawIntBits(sign) &
2484                                      (FloatConsts.SIGN_BIT_MASK)) |
2485                                     (Float.floatToRawIntBits(magnitude) &
2486                                      (FloatConsts.EXP_BIT_MASK |
2487                                       FloatConsts.SIGNIF_BIT_MASK)));
2488     }
2489 
2490     /**
2491      * Returns the unbiased exponent used in the representation of a
2492      * {@code float}.  Special cases:
2493      *
2494      * <ul>
2495      * <li>If the argument is NaN or infinite, then the result is
2496      * {@link Float#MAX_EXPONENT} + 1.
2497      * <li>If the argument is zero or subnormal, then the result is
2498      * {@link Float#MIN_EXPONENT} -1.
2499      * </ul>
2500      * @param f a {@code float} value
2501      * @return the unbiased exponent of the argument
2502      * @since 1.6
2503      */
2504     public static int getExponent(float f) {
2505         /*
2506          * Bitwise convert f to integer, mask out exponent bits, shift
2507          * to the right and then subtract out float's bias adjust to
2508          * get true exponent value
2509          */
2510         return ((Float.floatToRawIntBits(f) & FloatConsts.EXP_BIT_MASK) >>
2511                 (FloatConsts.SIGNIFICAND_WIDTH - 1)) - FloatConsts.EXP_BIAS;
2512     }
2513 
2514     /**
2515      * Returns the unbiased exponent used in the representation of a
2516      * {@code double}.  Special cases:
2517      *
2518      * <ul>
2519      * <li>If the argument is NaN or infinite, then the result is
2520      * {@link Double#MAX_EXPONENT} + 1.
2521      * <li>If the argument is zero or subnormal, then the result is
2522      * {@link Double#MIN_EXPONENT} -1.
2523      * </ul>
2524      * @param d a {@code double} value
2525      * @return the unbiased exponent of the argument
2526      * @since 1.6
2527      */
2528     public static int getExponent(double d) {
2529         /*
2530          * Bitwise convert d to long, mask out exponent bits, shift
2531          * to the right and then subtract out double's bias adjust to
2532          * get true exponent value.
2533          */
2534         return (int)(((Double.doubleToRawLongBits(d) & DoubleConsts.EXP_BIT_MASK) >>
2535                       (DoubleConsts.SIGNIFICAND_WIDTH - 1)) - DoubleConsts.EXP_BIAS);
2536     }
2537 
2538     /**
2539      * Returns the floating-point number adjacent to the first
2540      * argument in the direction of the second argument.  If both
2541      * arguments compare as equal the second argument is returned.
2542      *
2543      * <p>
2544      * Special cases:
2545      * <ul>
2546      * <li> If either argument is a NaN, then NaN is returned.
2547      *
2548      * <li> If both arguments are signed zeros, {@code direction}
2549      * is returned unchanged (as implied by the requirement of
2550      * returning the second argument if the arguments compare as
2551      * equal).
2552      *
2553      * <li> If {@code start} is
2554      * &plusmn;{@link Double#MIN_VALUE} and {@code direction}
2555      * has a value such that the result should have a smaller
2556      * magnitude, then a zero with the same sign as {@code start}
2557      * is returned.
2558      *
2559      * <li> If {@code start} is infinite and
2560      * {@code direction} has a value such that the result should
2561      * have a smaller magnitude, {@link Double#MAX_VALUE} with the
2562      * same sign as {@code start} is returned.
2563      *
2564      * <li> If {@code start} is equal to &plusmn;
2565      * {@link Double#MAX_VALUE} and {@code direction} has a
2566      * value such that the result should have a larger magnitude, an
2567      * infinity with same sign as {@code start} is returned.
2568      * </ul>
2569      *
2570      * @param start  starting floating-point value
2571      * @param direction value indicating which of
2572      * {@code start}'s neighbors or {@code start} should
2573      * be returned
2574      * @return The floating-point number adjacent to {@code start} in the
2575      * direction of {@code direction}.
2576      * @since 1.6
2577      */
2578     public static double nextAfter(double start, double direction) {
2579         /*
2580          * The cases:
2581          *
2582          * nextAfter(+infinity, 0)  == MAX_VALUE
2583          * nextAfter(+infinity, +infinity)  == +infinity
2584          * nextAfter(-infinity, 0)  == -MAX_VALUE
2585          * nextAfter(-infinity, -infinity)  == -infinity
2586          *
2587          * are naturally handled without any additional testing
2588          */
2589 
2590         /*
2591          * IEEE 754 floating-point numbers are lexicographically
2592          * ordered if treated as signed-magnitude integers.
2593          * Since Java's integers are two's complement,
2594          * incrementing the two's complement representation of a
2595          * logically negative floating-point value *decrements*
2596          * the signed-magnitude representation. Therefore, when
2597          * the integer representation of a floating-point value
2598          * is negative, the adjustment to the representation is in
2599          * the opposite direction from what would initially be expected.
2600          */
2601 
2602         // Branch to descending case first as it is more costly than ascending
2603         // case due to start != 0.0d conditional.
2604         if (start > direction) { // descending
2605             if (start != 0.0d) {
2606                 final long transducer = Double.doubleToRawLongBits(start);
2607                 return Double.longBitsToDouble(transducer + ((transducer > 0L) ? -1L : 1L));
2608             } else { // start == 0.0d && direction < 0.0d
2609                 return -Double.MIN_VALUE;
2610             }
2611         } else if (start < direction) { // ascending
2612             // Add +0.0 to get rid of a -0.0 (+0.0 + -0.0 => +0.0)
2613             // then bitwise convert start to integer.
2614             final long transducer = Double.doubleToRawLongBits(start + 0.0d);
2615             return Double.longBitsToDouble(transducer + ((transducer >= 0L) ? 1L : -1L));
2616         } else if (start == direction) {
2617             return direction;
2618         } else { // isNaN(start) || isNaN(direction)
2619             return start + direction;
2620         }
2621     }
2622 
2623     /**
2624      * Returns the floating-point number adjacent to the first
2625      * argument in the direction of the second argument.  If both
2626      * arguments compare as equal a value equivalent to the second argument
2627      * is returned.
2628      *
2629      * <p>
2630      * Special cases:
2631      * <ul>
2632      * <li> If either argument is a NaN, then NaN is returned.
2633      *
2634      * <li> If both arguments are signed zeros, a value equivalent
2635      * to {@code direction} is returned.
2636      *
2637      * <li> If {@code start} is
2638      * &plusmn;{@link Float#MIN_VALUE} and {@code direction}
2639      * has a value such that the result should have a smaller
2640      * magnitude, then a zero with the same sign as {@code start}
2641      * is returned.
2642      *
2643      * <li> If {@code start} is infinite and
2644      * {@code direction} has a value such that the result should
2645      * have a smaller magnitude, {@link Float#MAX_VALUE} with the
2646      * same sign as {@code start} is returned.
2647      *
2648      * <li> If {@code start} is equal to &plusmn;
2649      * {@link Float#MAX_VALUE} and {@code direction} has a
2650      * value such that the result should have a larger magnitude, an
2651      * infinity with same sign as {@code start} is returned.
2652      * </ul>
2653      *
2654      * @param start  starting floating-point value
2655      * @param direction value indicating which of
2656      * {@code start}'s neighbors or {@code start} should
2657      * be returned
2658      * @return The floating-point number adjacent to {@code start} in the
2659      * direction of {@code direction}.
2660      * @since 1.6
2661      */
2662     public static float nextAfter(float start, double direction) {
2663         /*
2664          * The cases:
2665          *
2666          * nextAfter(+infinity, 0)  == MAX_VALUE
2667          * nextAfter(+infinity, +infinity)  == +infinity
2668          * nextAfter(-infinity, 0)  == -MAX_VALUE
2669          * nextAfter(-infinity, -infinity)  == -infinity
2670          *
2671          * are naturally handled without any additional testing
2672          */
2673 
2674         /*
2675          * IEEE 754 floating-point numbers are lexicographically
2676          * ordered if treated as signed-magnitude integers.
2677          * Since Java's integers are two's complement,
2678          * incrementing the two's complement representation of a
2679          * logically negative floating-point value *decrements*
2680          * the signed-magnitude representation. Therefore, when
2681          * the integer representation of a floating-point value
2682          * is negative, the adjustment to the representation is in
2683          * the opposite direction from what would initially be expected.
2684          */
2685 
2686         // Branch to descending case first as it is more costly than ascending
2687         // case due to start != 0.0f conditional.
2688         if (start > direction) { // descending
2689             if (start != 0.0f) {
2690                 final int transducer = Float.floatToRawIntBits(start);
2691                 return Float.intBitsToFloat(transducer + ((transducer > 0) ? -1 : 1));
2692             } else { // start == 0.0f && direction < 0.0f
2693                 return -Float.MIN_VALUE;
2694             }
2695         } else if (start < direction) { // ascending
2696             // Add +0.0 to get rid of a -0.0 (+0.0 + -0.0 => +0.0)
2697             // then bitwise convert start to integer.
2698             final int transducer = Float.floatToRawIntBits(start + 0.0f);
2699             return Float.intBitsToFloat(transducer + ((transducer >= 0) ? 1 : -1));
2700         } else if (start == direction) {
2701             return (float)direction;
2702         } else { // isNaN(start) || isNaN(direction)
2703             return start + (float)direction;
2704         }
2705     }
2706 
2707     /**
2708      * Returns the floating-point value adjacent to {@code d} in
2709      * the direction of positive infinity.  This method is
2710      * semantically equivalent to {@code nextAfter(d,
2711      * Double.POSITIVE_INFINITY)}; however, a {@code nextUp}
2712      * implementation may run faster than its equivalent
2713      * {@code nextAfter} call.
2714      *
2715      * <p>Special Cases:
2716      * <ul>
2717      * <li> If the argument is NaN, the result is NaN.
2718      *
2719      * <li> If the argument is positive infinity, the result is
2720      * positive infinity.
2721      *
2722      * <li> If the argument is zero, the result is
2723      * {@link Double#MIN_VALUE}
2724      *
2725      * </ul>
2726      *
2727      * @param d starting floating-point value
2728      * @return The adjacent floating-point value closer to positive
2729      * infinity.
2730      * @since 1.6
2731      */
2732     public static double nextUp(double d) {
2733         // Use a single conditional and handle the likely cases first.
2734         if (d < Double.POSITIVE_INFINITY) {
2735             // Add +0.0 to get rid of a -0.0 (+0.0 + -0.0 => +0.0).
2736             final long transducer = Double.doubleToRawLongBits(d + 0.0D);
2737             return Double.longBitsToDouble(transducer + ((transducer >= 0L) ? 1L : -1L));
2738         } else { // d is NaN or +Infinity
2739             return d;
2740         }
2741     }
2742 
2743     /**
2744      * Returns the floating-point value adjacent to {@code f} in
2745      * the direction of positive infinity.  This method is
2746      * semantically equivalent to {@code nextAfter(f,
2747      * Float.POSITIVE_INFINITY)}; however, a {@code nextUp}
2748      * implementation may run faster than its equivalent
2749      * {@code nextAfter} call.
2750      *
2751      * <p>Special Cases:
2752      * <ul>
2753      * <li> If the argument is NaN, the result is NaN.
2754      *
2755      * <li> If the argument is positive infinity, the result is
2756      * positive infinity.
2757      *
2758      * <li> If the argument is zero, the result is
2759      * {@link Float#MIN_VALUE}
2760      *
2761      * </ul>
2762      *
2763      * @param f starting floating-point value
2764      * @return The adjacent floating-point value closer to positive
2765      * infinity.
2766      * @since 1.6
2767      */
2768     public static float nextUp(float f) {
2769         // Use a single conditional and handle the likely cases first.
2770         if (f < Float.POSITIVE_INFINITY) {
2771             // Add +0.0 to get rid of a -0.0 (+0.0 + -0.0 => +0.0).
2772             final int transducer = Float.floatToRawIntBits(f + 0.0F);
2773             return Float.intBitsToFloat(transducer + ((transducer >= 0) ? 1 : -1));
2774         } else { // f is NaN or +Infinity
2775             return f;
2776         }
2777     }
2778 
2779     /**
2780      * Returns the floating-point value adjacent to {@code d} in
2781      * the direction of negative infinity.  This method is
2782      * semantically equivalent to {@code nextAfter(d,
2783      * Double.NEGATIVE_INFINITY)}; however, a
2784      * {@code nextDown} implementation may run faster than its
2785      * equivalent {@code nextAfter} call.
2786      *
2787      * <p>Special Cases:
2788      * <ul>
2789      * <li> If the argument is NaN, the result is NaN.
2790      *
2791      * <li> If the argument is negative infinity, the result is
2792      * negative infinity.
2793      *
2794      * <li> If the argument is zero, the result is
2795      * {@code -Double.MIN_VALUE}
2796      *
2797      * </ul>
2798      *
2799      * @param d  starting floating-point value
2800      * @return The adjacent floating-point value closer to negative
2801      * infinity.
2802      * @since 1.8
2803      */
2804     public static double nextDown(double d) {
2805         if (Double.isNaN(d) || d == Double.NEGATIVE_INFINITY)
2806             return d;
2807         else {
2808             if (d == 0.0)
2809                 return -Double.MIN_VALUE;
2810             else
2811                 return Double.longBitsToDouble(Double.doubleToRawLongBits(d) +
2812                                                ((d > 0.0d)?-1L:+1L));
2813         }
2814     }
2815 
2816     /**
2817      * Returns the floating-point value adjacent to {@code f} in
2818      * the direction of negative infinity.  This method is
2819      * semantically equivalent to {@code nextAfter(f,
2820      * Float.NEGATIVE_INFINITY)}; however, a
2821      * {@code nextDown} implementation may run faster than its
2822      * equivalent {@code nextAfter} call.
2823      *
2824      * <p>Special Cases:
2825      * <ul>
2826      * <li> If the argument is NaN, the result is NaN.
2827      *
2828      * <li> If the argument is negative infinity, the result is
2829      * negative infinity.
2830      *
2831      * <li> If the argument is zero, the result is
2832      * {@code -Float.MIN_VALUE}
2833      *
2834      * </ul>
2835      *
2836      * @param f  starting floating-point value
2837      * @return The adjacent floating-point value closer to negative
2838      * infinity.
2839      * @since 1.8
2840      */
2841     public static float nextDown(float f) {
2842         if (Float.isNaN(f) || f == Float.NEGATIVE_INFINITY)
2843             return f;
2844         else {
2845             if (f == 0.0f)
2846                 return -Float.MIN_VALUE;
2847             else
2848                 return Float.intBitsToFloat(Float.floatToRawIntBits(f) +
2849                                             ((f > 0.0f)?-1:+1));
2850         }
2851     }
2852 
2853     /**
2854      * Returns {@code d} &times; 2<sup>{@code scaleFactor}</sup>
2855      * rounded as if performed by a single correctly rounded
2856      * floating-point multiply.  If the exponent of the result is
2857      * between {@link Double#MIN_EXPONENT} and {@link
2858      * Double#MAX_EXPONENT}, the answer is calculated exactly.  If the
2859      * exponent of the result would be larger than {@code
2860      * Double.MAX_EXPONENT}, an infinity is returned.  Note that if
2861      * the result is subnormal, precision may be lost; that is, when
2862      * {@code scalb(x, n)} is subnormal, {@code scalb(scalb(x, n),
2863      * -n)} may not equal <i>x</i>.  When the result is non-NaN, the
2864      * result has the same sign as {@code d}.
2865      *
2866      * <p>Special cases:
2867      * <ul>
2868      * <li> If the first argument is NaN, NaN is returned.
2869      * <li> If the first argument is infinite, then an infinity of the
2870      * same sign is returned.
2871      * <li> If the first argument is zero, then a zero of the same
2872      * sign is returned.
2873      * </ul>
2874      *
2875      * @param d number to be scaled by a power of two.
2876      * @param scaleFactor power of 2 used to scale {@code d}
2877      * @return {@code d} &times; 2<sup>{@code scaleFactor}</sup>
2878      * @since 1.6
2879      */
2880     public static double scalb(double d, int scaleFactor) {
2881         /*
2882          * When scaling up, it does not matter what order the
2883          * multiply-store operations are done; the result will be
2884          * finite or overflow regardless of the operation ordering.
2885          * However, to get the correct result when scaling down, a
2886          * particular ordering must be used.
2887          *
2888          * When scaling down, the multiply-store operations are
2889          * sequenced so that it is not possible for two consecutive
2890          * multiply-stores to return subnormal results.  If one
2891          * multiply-store result is subnormal, the next multiply will
2892          * round it away to zero.  This is done by first multiplying
2893          * by 2 ^ (scaleFactor % n) and then multiplying several
2894          * times by 2^n as needed where n is the exponent of number
2895          * that is a convenient power of two.  In this way, at most one
2896          * real rounding error occurs.
2897          */
2898 
2899         // magnitude of a power of two so large that scaling a finite
2900         // nonzero value by it would be guaranteed to over or
2901         // underflow; due to rounding, scaling down takes an
2902         // additional power of two which is reflected here
2903         final int MAX_SCALE = Double.MAX_EXPONENT + -Double.MIN_EXPONENT +
2904                               DoubleConsts.SIGNIFICAND_WIDTH + 1;
2905         int exp_adjust = 0;
2906         int scale_increment = 0;
2907         double exp_delta = Double.NaN;
2908 
2909         // Make sure scaling factor is in a reasonable range
2910 
2911         if(scaleFactor < 0) {
2912             scaleFactor = Math.max(scaleFactor, -MAX_SCALE);
2913             scale_increment = -512;
2914             exp_delta = twoToTheDoubleScaleDown;
2915         }
2916         else {
2917             scaleFactor = Math.min(scaleFactor, MAX_SCALE);
2918             scale_increment = 512;
2919             exp_delta = twoToTheDoubleScaleUp;
2920         }
2921 
2922         // Calculate (scaleFactor % +/-512), 512 = 2^9, using
2923         // technique from "Hacker's Delight" section 10-2.
2924         int t = (scaleFactor >> 9-1) >>> 32 - 9;
2925         exp_adjust = ((scaleFactor + t) & (512 -1)) - t;
2926 
2927         d *= powerOfTwoD(exp_adjust);
2928         scaleFactor -= exp_adjust;
2929 
2930         while(scaleFactor != 0) {
2931             d *= exp_delta;
2932             scaleFactor -= scale_increment;
2933         }
2934         return d;
2935     }
2936 
2937     /**
2938      * Returns {@code f} &times; 2<sup>{@code scaleFactor}</sup>
2939      * rounded as if performed by a single correctly rounded
2940      * floating-point multiply.  If the exponent of the result is
2941      * between {@link Float#MIN_EXPONENT} and {@link
2942      * Float#MAX_EXPONENT}, the answer is calculated exactly.  If the
2943      * exponent of the result would be larger than {@code
2944      * Float.MAX_EXPONENT}, an infinity is returned.  Note that if the
2945      * result is subnormal, precision may be lost; that is, when
2946      * {@code scalb(x, n)} is subnormal, {@code scalb(scalb(x, n),
2947      * -n)} may not equal <i>x</i>.  When the result is non-NaN, the
2948      * result has the same sign as {@code f}.
2949      *
2950      * <p>Special cases:
2951      * <ul>
2952      * <li> If the first argument is NaN, NaN is returned.
2953      * <li> If the first argument is infinite, then an infinity of the
2954      * same sign is returned.
2955      * <li> If the first argument is zero, then a zero of the same
2956      * sign is returned.
2957      * </ul>
2958      *
2959      * @param f number to be scaled by a power of two.
2960      * @param scaleFactor power of 2 used to scale {@code f}
2961      * @return {@code f} &times; 2<sup>{@code scaleFactor}</sup>
2962      * @since 1.6
2963      */
2964     public static float scalb(float f, int scaleFactor) {
2965         // magnitude of a power of two so large that scaling a finite
2966         // nonzero value by it would be guaranteed to over or
2967         // underflow; due to rounding, scaling down takes an
2968         // additional power of two which is reflected here
2969         final int MAX_SCALE = Float.MAX_EXPONENT + -Float.MIN_EXPONENT +
2970                               FloatConsts.SIGNIFICAND_WIDTH + 1;
2971 
2972         // Make sure scaling factor is in a reasonable range
2973         scaleFactor = Math.max(Math.min(scaleFactor, MAX_SCALE), -MAX_SCALE);
2974 
2975         /*
2976          * Since + MAX_SCALE for float fits well within the double
2977          * exponent range and + float -> double conversion is exact
2978          * the multiplication below will be exact. Therefore, the
2979          * rounding that occurs when the double product is cast to
2980          * float will be the correctly rounded float result.
2981          */
2982         return (float)((double)f*powerOfTwoD(scaleFactor));
2983     }
2984 
2985     // Constants used in scalb
2986     static double twoToTheDoubleScaleUp = powerOfTwoD(512);
2987     static double twoToTheDoubleScaleDown = powerOfTwoD(-512);
2988 
2989     /**
2990      * Returns a floating-point power of two in the normal range.
2991      */
2992     static double powerOfTwoD(int n) {
2993         assert(n >= Double.MIN_EXPONENT && n <= Double.MAX_EXPONENT);
2994         return Double.longBitsToDouble((((long)n + (long)DoubleConsts.EXP_BIAS) <<
2995                                         (DoubleConsts.SIGNIFICAND_WIDTH-1))
2996                                        & DoubleConsts.EXP_BIT_MASK);
2997     }
2998 
2999     /**
3000      * Returns a floating-point power of two in the normal range.
3001      */
3002     static float powerOfTwoF(int n) {
3003         assert(n >= Float.MIN_EXPONENT && n <= Float.MAX_EXPONENT);
3004         return Float.intBitsToFloat(((n + FloatConsts.EXP_BIAS) <<
3005                                      (FloatConsts.SIGNIFICAND_WIDTH-1))
3006                                     & FloatConsts.EXP_BIT_MASK);
3007     }
3008 }
3009