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