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