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