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