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