1 /* 2 * Copyright (c) 1994, 2020, 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}, {@code toIntExact}, 96 * {@code incrementExact}, {@code decrementExact} and {@code negateExact} 97 * throw an {@code ArithmeticException} when the results overflow. 98 * For the arithmetic operations divide and absolute value, overflow 99 * occurs only with a specific minimum or maximum value and 100 * should be checked against 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 */ 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 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 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 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 */ 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 */ 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 */ 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 */ 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 */ 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 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 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 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 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 */ 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 */ 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 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 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 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 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 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 */ 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 */ 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 */ 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 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 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 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 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 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 */ 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 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 * The overflow only occurs for {@linkplain Integer#MAX_VALUE the maximum value}. 959 * 960 * @param a the value to increment 961 * @return the result 962 * @throws ArithmeticException if the result overflows an int 963 * @since 1.8 964 */ 965 @HotSpotIntrinsicCandidate 966 public static int incrementExact(int a) { 967 if (a == Integer.MAX_VALUE) { 968 throw new ArithmeticException("integer overflow"); 969 } 970 971 return a + 1; 972 } 973 974 /** 975 * Returns the argument incremented by one, throwing an exception if the 976 * result overflows a {@code long}. 977 * The overflow only occurs for {@linkplain Long#MAX_VALUE the maximum value}. 978 * 979 * @param a the value to increment 980 * @return the result 981 * @throws ArithmeticException if the result overflows a long 982 * @since 1.8 983 */ 984 @HotSpotIntrinsicCandidate 985 public static long incrementExact(long a) { 986 if (a == Long.MAX_VALUE) { 987 throw new ArithmeticException("long overflow"); 988 } 989 990 return a + 1L; 991 } 992 993 /** 994 * Returns the argument decremented by one, throwing an exception if the 995 * result overflows an {@code int}. 996 * The overflow only occurs for {@linkplain Integer#MIN_VALUE the minimum value}. 997 * 998 * @param a the value to decrement 999 * @return the result 1000 * @throws ArithmeticException if the result overflows an int 1001 * @since 1.8 1002 */ 1003 @HotSpotIntrinsicCandidate 1004 public static int decrementExact(int a) { 1005 if (a == Integer.MIN_VALUE) { 1006 throw new ArithmeticException("integer overflow"); 1007 } 1008 1009 return a - 1; 1010 } 1011 1012 /** 1013 * Returns the argument decremented by one, throwing an exception if the 1014 * result overflows a {@code long}. 1015 * The overflow only occurs for {@linkplain Long#MIN_VALUE the minimum value}. 1016 * 1017 * @param a the value to decrement 1018 * @return the result 1019 * @throws ArithmeticException if the result overflows a long 1020 * @since 1.8 1021 */ 1022 @HotSpotIntrinsicCandidate 1023 public static long decrementExact(long a) { 1024 if (a == Long.MIN_VALUE) { 1025 throw new ArithmeticException("long overflow"); 1026 } 1027 1028 return a - 1L; 1029 } 1030 1031 /** 1032 * Returns the negation of the argument, throwing an exception if the 1033 * result overflows an {@code int}. 1034 * The overflow only occurs for {@linkplain Integer#MIN_VALUE the minimum value}. 1035 * 1036 * @param a the value to negate 1037 * @return the result 1038 * @throws ArithmeticException if the result overflows an int 1039 * @since 1.8 1040 */ 1041 @HotSpotIntrinsicCandidate 1042 public static int negateExact(int a) { 1043 if (a == Integer.MIN_VALUE) { 1044 throw new ArithmeticException("integer overflow"); 1045 } 1046 1047 return -a; 1048 } 1049 1050 /** 1051 * Returns the negation of the argument, throwing an exception if the 1052 * result overflows a {@code long}. 1053 * The overflow only occurs for {@linkplain Long#MIN_VALUE the minimum value}. 1054 * 1055 * @param a the value to negate 1056 * @return the result 1057 * @throws ArithmeticException if the result overflows a long 1058 * @since 1.8 1059 */ 1060 @HotSpotIntrinsicCandidate 1061 public static long negateExact(long a) { 1062 if (a == Long.MIN_VALUE) { 1063 throw new ArithmeticException("long overflow"); 1064 } 1065 1066 return -a; 1067 } 1068 1069 /** 1070 * Returns the value of the {@code long} argument, 1071 * throwing an exception if the value overflows an {@code int}. 1072 * 1073 * @param value the long value 1074 * @return the argument as an int 1075 * @throws ArithmeticException if the {@code argument} overflows an int 1076 * @since 1.8 1077 */ 1078 public static int toIntExact(long value) { 1079 if ((int)value != value) { 1080 throw new ArithmeticException("integer overflow"); 1081 } 1082 return (int)value; 1083 } 1084 1085 /** 1086 * Returns the exact mathematical product of the arguments. 1087 * 1088 * @param x the first value 1089 * @param y the second value 1090 * @return the result 1091 * @since 9 1092 */ 1093 public static long multiplyFull(int x, int y) { 1094 return (long)x * (long)y; 1095 } 1096 1097 /** 1098 * Returns as a {@code long} the most significant 64 bits of the 128-bit 1099 * product of two 64-bit factors. 1100 * 1101 * @param x the first value 1102 * @param y the second value 1103 * @return the result 1104 * @since 9 1105 */ 1106 @HotSpotIntrinsicCandidate 1107 public static long multiplyHigh(long x, long y) { 1108 if (x < 0 || y < 0) { 1109 // Use technique from section 8-2 of Henry S. Warren, Jr., 1110 // Hacker's Delight (2nd ed.) (Addison Wesley, 2013), 173-174. 1111 long x1 = x >> 32; 1112 long x2 = x & 0xFFFFFFFFL; 1113 long y1 = y >> 32; 1114 long y2 = y & 0xFFFFFFFFL; 1115 long z2 = x2 * y2; 1116 long t = x1 * y2 + (z2 >>> 32); 1117 long z1 = t & 0xFFFFFFFFL; 1118 long z0 = t >> 32; 1119 z1 += x2 * y1; 1120 return x1 * y1 + z0 + (z1 >> 32); 1121 } else { 1122 // Use Karatsuba technique with two base 2^32 digits. 1123 long x1 = x >>> 32; 1124 long y1 = y >>> 32; 1125 long x2 = x & 0xFFFFFFFFL; 1126 long y2 = y & 0xFFFFFFFFL; 1127 long A = x1 * y1; 1128 long B = x2 * y2; 1129 long C = (x1 + x2) * (y1 + y2); 1130 long K = C - A - B; 1131 return (((B >>> 32) + K) >>> 32) + A; 1132 } 1133 } 1134 1135 /** 1136 * Returns the largest (closest to positive infinity) 1137 * {@code int} value that is less than or equal to the algebraic quotient. 1138 * There is one special case, if the dividend is the 1139 * {@linkplain Integer#MIN_VALUE Integer.MIN_VALUE} and the divisor is {@code -1}, 1140 * then integer overflow occurs and 1141 * the result is equal to {@code Integer.MIN_VALUE}. 1142 * <p> 1143 * Normal integer division operates under the round to zero rounding mode 1144 * (truncation). This operation instead acts under the round toward 1145 * negative infinity (floor) rounding mode. 1146 * The floor rounding mode gives different results from truncation 1147 * when the exact result is negative. 1148 * <ul> 1149 * <li>If the signs of the arguments are the same, the results of 1150 * {@code floorDiv} and the {@code /} operator are the same. <br> 1151 * For example, {@code floorDiv(4, 3) == 1} and {@code (4 / 3) == 1}.</li> 1152 * <li>If the signs of the arguments are different, the quotient is negative and 1153 * {@code floorDiv} returns the integer less than or equal to the quotient 1154 * and the {@code /} operator returns the integer closest to zero.<br> 1155 * For example, {@code floorDiv(-4, 3) == -2}, 1156 * whereas {@code (-4 / 3) == -1}. 1157 * </li> 1158 * </ul> 1159 * 1160 * @param x the dividend 1161 * @param y the divisor 1162 * @return the largest (closest to positive infinity) 1163 * {@code int} value that is less than or equal to the algebraic quotient. 1164 * @throws ArithmeticException if the divisor {@code y} is zero 1165 * @see #floorMod(int, int) 1166 * @see #floor(double) 1167 * @since 1.8 1168 */ 1169 public static int floorDiv(int x, int y) { 1170 int r = x / y; 1171 // if the signs are different and modulo not zero, round down 1172 if ((x ^ y) < 0 && (r * y != x)) { 1173 r--; 1174 } 1175 return r; 1176 } 1177 1178 /** 1179 * Returns the largest (closest to positive infinity) 1180 * {@code long} value that is less than or equal to the algebraic quotient. 1181 * There is one special case, if the dividend is the 1182 * {@linkplain Long#MIN_VALUE Long.MIN_VALUE} and the divisor is {@code -1}, 1183 * then integer overflow occurs and 1184 * the result is equal to {@code Long.MIN_VALUE}. 1185 * <p> 1186 * Normal integer division operates under the round to zero rounding mode 1187 * (truncation). This operation instead acts under the round toward 1188 * negative infinity (floor) rounding mode. 1189 * The floor rounding mode gives different results from truncation 1190 * when the exact result is negative. 1191 * <p> 1192 * For examples, see {@link #floorDiv(int, int)}. 1193 * 1194 * @param x the dividend 1195 * @param y the divisor 1196 * @return the largest (closest to positive infinity) 1197 * {@code int} value that is less than or equal to the algebraic quotient. 1198 * @throws ArithmeticException if the divisor {@code y} is zero 1199 * @see #floorMod(long, int) 1200 * @see #floor(double) 1201 * @since 9 1202 */ 1203 public static long floorDiv(long x, int y) { 1204 return floorDiv(x, (long)y); 1205 } 1206 1207 /** 1208 * Returns the largest (closest to positive infinity) 1209 * {@code long} value that is less than or equal to the algebraic quotient. 1210 * There is one special case, if the dividend is the 1211 * {@linkplain Long#MIN_VALUE Long.MIN_VALUE} and the divisor is {@code -1}, 1212 * then integer overflow occurs and 1213 * the result is equal to {@code Long.MIN_VALUE}. 1214 * <p> 1215 * Normal integer division operates under the round to zero rounding mode 1216 * (truncation). This operation instead acts under the round toward 1217 * negative infinity (floor) rounding mode. 1218 * The floor rounding mode gives different results from truncation 1219 * when the exact result is negative. 1220 * <p> 1221 * For examples, see {@link #floorDiv(int, int)}. 1222 * 1223 * @param x the dividend 1224 * @param y the divisor 1225 * @return the largest (closest to positive infinity) 1226 * {@code long} value that is less than or equal to the algebraic quotient. 1227 * @throws ArithmeticException if the divisor {@code y} is zero 1228 * @see #floorMod(long, long) 1229 * @see #floor(double) 1230 * @since 1.8 1231 */ 1232 public static long floorDiv(long x, long y) { 1233 long r = x / y; 1234 // if the signs are different and modulo not zero, round down 1235 if ((x ^ y) < 0 && (r * y != x)) { 1236 r--; 1237 } 1238 return r; 1239 } 1240 1241 /** 1242 * Returns the floor modulus of the {@code int} arguments. 1243 * <p> 1244 * The floor modulus is {@code x - (floorDiv(x, y) * y)}, 1245 * has the same sign as the divisor {@code y}, and 1246 * is in the range of {@code -abs(y) < r < +abs(y)}. 1247 * 1248 * <p> 1249 * The relationship between {@code floorDiv} and {@code floorMod} is such that: 1250 * <ul> 1251 * <li>{@code floorDiv(x, y) * y + floorMod(x, y) == x} 1252 * </ul> 1253 * <p> 1254 * The difference in values between {@code floorMod} and 1255 * the {@code %} operator is due to the difference between 1256 * {@code floorDiv} that returns the integer less than or equal to the quotient 1257 * and the {@code /} operator that returns the integer closest to zero. 1258 * <p> 1259 * Examples: 1260 * <ul> 1261 * <li>If the signs of the arguments are the same, the results 1262 * of {@code floorMod} and the {@code %} operator are the same.<br> 1263 * <ul> 1264 * <li>{@code floorMod(+4, +3) == +1}; and {@code (+4 % +3) == +1}</li> 1265 * <li>{@code floorMod(-4, -3) == -1}; and {@code (-4 % -3) == -1}</li> 1266 * </ul> 1267 * <li>If the signs of the arguments are different, the results 1268 * differ from the {@code %} operator.<br> 1269 * <ul> 1270 * <li>{@code floorMod(+4, -3) == -2}; and {@code (+4 % -3) == +1}</li> 1271 * <li>{@code floorMod(-4, +3) == +2}; and {@code (-4 % +3) == -1}</li> 1272 * </ul> 1273 * </li> 1274 * </ul> 1275 * <p> 1276 * If the signs of arguments are unknown and a positive modulus 1277 * is needed it can be computed as {@code (floorMod(x, y) + abs(y)) % abs(y)}. 1278 * 1279 * @param x the dividend 1280 * @param y the divisor 1281 * @return the floor modulus {@code x - (floorDiv(x, y) * y)} 1282 * @throws ArithmeticException if the divisor {@code y} is zero 1283 * @see #floorDiv(int, int) 1284 * @since 1.8 1285 */ 1286 public static int floorMod(int x, int y) { 1287 int mod = x % y; 1288 // if the signs are different and modulo not zero, adjust result 1289 if ((mod ^ y) < 0 && mod != 0) { 1290 mod += y; 1291 } 1292 return mod; 1293 } 1294 1295 /** 1296 * Returns the floor modulus of the {@code long} and {@code int} arguments. 1297 * <p> 1298 * The floor modulus is {@code x - (floorDiv(x, y) * y)}, 1299 * has the same sign as the divisor {@code y}, and 1300 * is in the range of {@code -abs(y) < r < +abs(y)}. 1301 * 1302 * <p> 1303 * The relationship between {@code floorDiv} and {@code floorMod} is such that: 1304 * <ul> 1305 * <li>{@code floorDiv(x, y) * y + floorMod(x, y) == x} 1306 * </ul> 1307 * <p> 1308 * For examples, see {@link #floorMod(int, int)}. 1309 * 1310 * @param x the dividend 1311 * @param y the divisor 1312 * @return the floor modulus {@code x - (floorDiv(x, y) * y)} 1313 * @throws ArithmeticException if the divisor {@code y} is zero 1314 * @see #floorDiv(long, int) 1315 * @since 9 1316 */ 1317 public static int floorMod(long x, int y) { 1318 // Result cannot overflow the range of int. 1319 return (int)floorMod(x, (long)y); 1320 } 1321 1322 /** 1323 * Returns the floor modulus of the {@code long} arguments. 1324 * <p> 1325 * The floor modulus is {@code x - (floorDiv(x, y) * y)}, 1326 * has the same sign as the divisor {@code y}, and 1327 * is in the range of {@code -abs(y) < r < +abs(y)}. 1328 * 1329 * <p> 1330 * The relationship between {@code floorDiv} and {@code floorMod} is such that: 1331 * <ul> 1332 * <li>{@code floorDiv(x, y) * y + floorMod(x, y) == x} 1333 * </ul> 1334 * <p> 1335 * For examples, see {@link #floorMod(int, int)}. 1336 * 1337 * @param x the dividend 1338 * @param y the divisor 1339 * @return the floor modulus {@code x - (floorDiv(x, y) * y)} 1340 * @throws ArithmeticException if the divisor {@code y} is zero 1341 * @see #floorDiv(long, long) 1342 * @since 1.8 1343 */ 1344 public static long floorMod(long x, long y) { 1345 long mod = x % y; 1346 // if the signs are different and modulo not zero, adjust result 1347 if ((x ^ y) < 0 && mod != 0) { 1348 mod += y; 1349 } 1350 return mod; 1351 } 1352 1353 /** 1354 * Returns the absolute value of an {@code int} value. 1355 * If the argument is not negative, the argument is returned. 1356 * If the argument is negative, the negation of the argument is returned. 1357 * 1358 * <p>Note that if the argument is equal to the value of {@link 1359 * Integer#MIN_VALUE}, the most negative representable {@code int} 1360 * value, the result is that same value, which is negative. In 1361 * contrast, the {@link Math#absExact(int)} method throws an 1362 * {@code ArithmeticException} for this value. 1363 * 1364 * @param a the argument whose absolute value is to be determined 1365 * @return the absolute value of the argument. 1366 * @see Math#absExact(int) 1367 */ 1368 @HotSpotIntrinsicCandidate 1369 public static int abs(int a) { 1370 return (a < 0) ? -a : a; 1371 } 1372 1373 /** 1374 * Returns the mathematical absolute value of an {@code int} value 1375 * if it is exactly representable as an {@code int}, throwing 1376 * {@code ArithmeticException} if the result overflows the 1377 * positive {@code int} range. 1378 * 1379 * <p>Since the range of two's complement integers is asymmetric 1380 * with one additional negative value (JLS {@jls 4.2.1}), the 1381 * mathematical absolute value of {@link Integer#MIN_VALUE} 1382 * overflows the positive {@code int} range, so an exception is 1383 * thrown for that argument. 1384 * 1385 * @param a the argument whose absolute value is to be determined 1386 * @return the absolute value of the argument, unless overflow occurs 1387 * @throws ArithmeticException if the argument is {@link Integer#MIN_VALUE} 1388 * @see Math#abs(int) 1389 * @since 15 1390 */ 1391 public static int absExact(int a) { 1392 if (a == Integer.MIN_VALUE) 1393 throw new ArithmeticException( 1394 "Overflow to represent absolute value of Integer.MIN_VALUE"); 1395 else 1396 return abs(a); 1397 } 1398 1399 /** 1400 * Returns the absolute value of a {@code long} value. 1401 * If the argument is not negative, the argument is returned. 1402 * If the argument is negative, the negation of the argument is returned. 1403 * 1404 * <p>Note that if the argument is equal to the value of {@link 1405 * Long#MIN_VALUE}, the most negative representable {@code long} 1406 * value, the result is that same value, which is negative. In 1407 * contrast, the {@link Math#absExact(long)} method throws an 1408 * {@code ArithmeticException} for this value. 1409 * 1410 * @param a the argument whose absolute value is to be determined 1411 * @return the absolute value of the argument. 1412 * @see Math#absExact(long) 1413 */ 1414 @HotSpotIntrinsicCandidate 1415 public static long abs(long a) { 1416 return (a < 0) ? -a : a; 1417 } 1418 1419 /** 1420 * Returns the mathematical absolute value of an {@code long} value 1421 * if it is exactly representable as an {@code long}, throwing 1422 * {@code ArithmeticException} if the result overflows the 1423 * positive {@code long} range. 1424 * 1425 * <p>Since the range of two's complement integers is asymmetric 1426 * with one additional negative value (JLS {@jls 4.2.1}), the 1427 * mathematical absolute value of {@link Long#MIN_VALUE} overflows 1428 * the positive {@code long} range, so an exception is thrown for 1429 * that argument. 1430 * 1431 * @param a the argument whose absolute value is to be determined 1432 * @return the absolute value of the argument, unless overflow occurs 1433 * @throws ArithmeticException if the argument is {@link Long#MIN_VALUE} 1434 * @see Math#abs(long) 1435 * @since 15 1436 */ 1437 public static long absExact(long a) { 1438 if (a == Long.MIN_VALUE) 1439 throw new ArithmeticException( 1440 "Overflow to represent absolute value of Long.MIN_VALUE"); 1441 else 1442 return abs(a); 1443 } 1444 1445 /** 1446 * Returns the absolute value of a {@code float} value. 1447 * If the argument is not negative, the argument is returned. 1448 * If the argument is negative, the negation of the argument is returned. 1449 * Special cases: 1450 * <ul><li>If the argument is positive zero or negative zero, the 1451 * result is positive zero. 1452 * <li>If the argument is infinite, the result is positive infinity. 1453 * <li>If the argument is NaN, the result is NaN.</ul> 1454 * 1455 * @apiNote As implied by the above, one valid implementation of 1456 * this method is given by the expression below which computes a 1457 * {@code float} with the same exponent and significand as the 1458 * argument but with a guaranteed zero sign bit indicating a 1459 * positive value:<br> 1460 * {@code Float.intBitsToFloat(0x7fffffff & Float.floatToRawIntBits(a))} 1461 * 1462 * @param a the argument whose absolute value is to be determined 1463 * @return the absolute value of the argument. 1464 */ 1465 @HotSpotIntrinsicCandidate 1466 public static float abs(float a) { 1467 return (a <= 0.0F) ? 0.0F - a : a; 1468 } 1469 1470 /** 1471 * Returns the absolute value of a {@code double} value. 1472 * If the argument is not negative, the argument is returned. 1473 * If the argument is negative, the negation of the argument is returned. 1474 * Special cases: 1475 * <ul><li>If the argument is positive zero or negative zero, the result 1476 * is positive zero. 1477 * <li>If the argument is infinite, the result is positive infinity. 1478 * <li>If the argument is NaN, the result is NaN.</ul> 1479 * 1480 * @apiNote As implied by the above, one valid implementation of 1481 * this method is given by the expression below which computes a 1482 * {@code double} with the same exponent and significand as the 1483 * argument but with a guaranteed zero sign bit indicating a 1484 * positive value:<br> 1485 * {@code Double.longBitsToDouble((Double.doubleToRawLongBits(a)<<1)>>>1)} 1486 * 1487 * @param a the argument whose absolute value is to be determined 1488 * @return the absolute value of the argument. 1489 */ 1490 @HotSpotIntrinsicCandidate 1491 public static double abs(double a) { 1492 return (a <= 0.0D) ? 0.0D - a : a; 1493 } 1494 1495 /** 1496 * Returns the greater of two {@code int} values. That is, the 1497 * result is the argument closer to the value of 1498 * {@link Integer#MAX_VALUE}. If the arguments have the same value, 1499 * the result is that same value. 1500 * 1501 * @param a an argument. 1502 * @param b another argument. 1503 * @return the larger of {@code a} and {@code b}. 1504 */ 1505 @HotSpotIntrinsicCandidate 1506 public static int max(int a, int b) { 1507 return (a >= b) ? a : b; 1508 } 1509 1510 /** 1511 * Returns the greater of two {@code long} values. That is, the 1512 * result is the argument closer to the value of 1513 * {@link Long#MAX_VALUE}. If the arguments have the same value, 1514 * the result is that same value. 1515 * 1516 * @param a an argument. 1517 * @param b another argument. 1518 * @return the larger of {@code a} and {@code b}. 1519 */ 1520 public static long max(long a, long b) { 1521 return (a >= b) ? a : b; 1522 } 1523 1524 // Use raw bit-wise conversions on guaranteed non-NaN arguments. 1525 private static final long negativeZeroFloatBits = Float.floatToRawIntBits(-0.0f); 1526 private static final long negativeZeroDoubleBits = Double.doubleToRawLongBits(-0.0d); 1527 1528 /** 1529 * Returns the greater of two {@code float} values. That is, 1530 * the result is the argument closer to positive infinity. If the 1531 * arguments have the same value, the result is that same 1532 * value. If either value is NaN, then the result is NaN. Unlike 1533 * the numerical comparison operators, this method considers 1534 * negative zero to be strictly smaller than positive zero. If one 1535 * argument is positive zero and the other negative zero, the 1536 * result is positive zero. 1537 * 1538 * @param a an argument. 1539 * @param b another argument. 1540 * @return the larger of {@code a} and {@code b}. 1541 */ 1542 @HotSpotIntrinsicCandidate 1543 public static float max(float a, float b) { 1544 if (a != a) 1545 return a; // a is NaN 1546 if ((a == 0.0f) && 1547 (b == 0.0f) && 1548 (Float.floatToRawIntBits(a) == negativeZeroFloatBits)) { 1549 // Raw conversion ok since NaN can't map to -0.0. 1550 return b; 1551 } 1552 return (a >= b) ? a : b; 1553 } 1554 1555 /** 1556 * Returns the greater of two {@code double} values. That 1557 * is, the result is the argument closer to positive infinity. If 1558 * the arguments have the same value, the result is that same 1559 * value. If either value is NaN, then the result is NaN. Unlike 1560 * the numerical comparison operators, this method considers 1561 * negative zero to be strictly smaller than positive zero. If one 1562 * argument is positive zero and the other negative zero, the 1563 * result is positive zero. 1564 * 1565 * @param a an argument. 1566 * @param b another argument. 1567 * @return the larger of {@code a} and {@code b}. 1568 */ 1569 @HotSpotIntrinsicCandidate 1570 public static double max(double a, double b) { 1571 if (a != a) 1572 return a; // a is NaN 1573 if ((a == 0.0d) && 1574 (b == 0.0d) && 1575 (Double.doubleToRawLongBits(a) == negativeZeroDoubleBits)) { 1576 // Raw conversion ok since NaN can't map to -0.0. 1577 return b; 1578 } 1579 return (a >= b) ? a : b; 1580 } 1581 1582 /** 1583 * Returns the smaller of two {@code int} values. That is, 1584 * the result the argument closer to the value of 1585 * {@link Integer#MIN_VALUE}. If the arguments have the same 1586 * value, the result is that same value. 1587 * 1588 * @param a an argument. 1589 * @param b another argument. 1590 * @return the smaller of {@code a} and {@code b}. 1591 */ 1592 @HotSpotIntrinsicCandidate 1593 public static int min(int a, int b) { 1594 return (a <= b) ? a : b; 1595 } 1596 1597 /** 1598 * Returns the smaller of two {@code long} values. That is, 1599 * the result is the argument closer to the value of 1600 * {@link Long#MIN_VALUE}. If the arguments have the same 1601 * value, the result is that same value. 1602 * 1603 * @param a an argument. 1604 * @param b another argument. 1605 * @return the smaller of {@code a} and {@code b}. 1606 */ 1607 public static long min(long a, long b) { 1608 return (a <= b) ? a : b; 1609 } 1610 1611 /** 1612 * Returns the smaller of two {@code float} values. That is, 1613 * the result is the value closer to negative infinity. If the 1614 * arguments have the same value, the result is that same 1615 * value. If either value is NaN, then the result is NaN. Unlike 1616 * the numerical comparison operators, this method considers 1617 * negative zero to be strictly smaller than positive zero. If 1618 * one argument is positive zero and the other is negative zero, 1619 * the result is negative zero. 1620 * 1621 * @param a an argument. 1622 * @param b another argument. 1623 * @return the smaller of {@code a} and {@code b}. 1624 */ 1625 @HotSpotIntrinsicCandidate 1626 public static float min(float a, float b) { 1627 if (a != a) 1628 return a; // a is NaN 1629 if ((a == 0.0f) && 1630 (b == 0.0f) && 1631 (Float.floatToRawIntBits(b) == negativeZeroFloatBits)) { 1632 // Raw conversion ok since NaN can't map to -0.0. 1633 return b; 1634 } 1635 return (a <= b) ? a : b; 1636 } 1637 1638 /** 1639 * Returns the smaller of two {@code double} values. That 1640 * is, the result is the value closer to negative infinity. If the 1641 * arguments have the same value, the result is that same 1642 * value. If either value is NaN, then the result is NaN. Unlike 1643 * the numerical comparison operators, this method considers 1644 * negative zero to be strictly smaller than positive zero. If one 1645 * argument is positive zero and the other is negative zero, the 1646 * result is negative zero. 1647 * 1648 * @param a an argument. 1649 * @param b another argument. 1650 * @return the smaller of {@code a} and {@code b}. 1651 */ 1652 @HotSpotIntrinsicCandidate 1653 public static double min(double a, double b) { 1654 if (a != a) 1655 return a; // a is NaN 1656 if ((a == 0.0d) && 1657 (b == 0.0d) && 1658 (Double.doubleToRawLongBits(b) == negativeZeroDoubleBits)) { 1659 // Raw conversion ok since NaN can't map to -0.0. 1660 return b; 1661 } 1662 return (a <= b) ? a : b; 1663 } 1664 1665 /** 1666 * Returns the fused multiply add of the three arguments; that is, 1667 * returns the exact product of the first two arguments summed 1668 * with the third argument and then rounded once to the nearest 1669 * {@code double}. 1670 * 1671 * The rounding is done using the {@linkplain 1672 * java.math.RoundingMode#HALF_EVEN round to nearest even 1673 * rounding mode}. 1674 * 1675 * In contrast, if {@code a * b + c} is evaluated as a regular 1676 * floating-point expression, two rounding errors are involved, 1677 * the first for the multiply operation, the second for the 1678 * addition operation. 1679 * 1680 * <p>Special cases: 1681 * <ul> 1682 * <li> If any argument is NaN, the result is NaN. 1683 * 1684 * <li> If one of the first two arguments is infinite and the 1685 * other is zero, the result is NaN. 1686 * 1687 * <li> If the exact product of the first two arguments is infinite 1688 * (in other words, at least one of the arguments is infinite and 1689 * the other is neither zero nor NaN) and the third argument is an 1690 * infinity of the opposite sign, the result is NaN. 1691 * 1692 * </ul> 1693 * 1694 * <p>Note that {@code fma(a, 1.0, c)} returns the same 1695 * result as ({@code a + c}). However, 1696 * {@code fma(a, b, +0.0)} does <em>not</em> always return the 1697 * same result as ({@code a * b}) since 1698 * {@code fma(-0.0, +0.0, +0.0)} is {@code +0.0} while 1699 * ({@code -0.0 * +0.0}) is {@code -0.0}; {@code fma(a, b, -0.0)} is 1700 * equivalent to ({@code a * b}) however. 1701 * 1702 * @apiNote This method corresponds to the fusedMultiplyAdd 1703 * operation defined in IEEE 754-2008. 1704 * 1705 * @param a a value 1706 * @param b a value 1707 * @param c a value 1708 * 1709 * @return (<i>a</i> × <i>b</i> + <i>c</i>) 1710 * computed, as if with unlimited range and precision, and rounded 1711 * once to the nearest {@code double} value 1712 * 1713 * @since 9 1714 */ 1715 @HotSpotIntrinsicCandidate 1716 public static double fma(double a, double b, double c) { 1717 /* 1718 * Infinity and NaN arithmetic is not quite the same with two 1719 * roundings as opposed to just one so the simple expression 1720 * "a * b + c" cannot always be used to compute the correct 1721 * result. With two roundings, the product can overflow and 1722 * if the addend is infinite, a spurious NaN can be produced 1723 * if the infinity from the overflow and the infinite addend 1724 * have opposite signs. 1725 */ 1726 1727 // First, screen for and handle non-finite input values whose 1728 // arithmetic is not supported by BigDecimal. 1729 if (Double.isNaN(a) || Double.isNaN(b) || Double.isNaN(c)) { 1730 return Double.NaN; 1731 } else { // All inputs non-NaN 1732 boolean infiniteA = Double.isInfinite(a); 1733 boolean infiniteB = Double.isInfinite(b); 1734 boolean infiniteC = Double.isInfinite(c); 1735 double result; 1736 1737 if (infiniteA || infiniteB || infiniteC) { 1738 if (infiniteA && b == 0.0 || 1739 infiniteB && a == 0.0 ) { 1740 return Double.NaN; 1741 } 1742 // Store product in a double field to cause an 1743 // overflow even if non-strictfp evaluation is being 1744 // used. 1745 double product = a * b; 1746 if (Double.isInfinite(product) && !infiniteA && !infiniteB) { 1747 // Intermediate overflow; might cause a 1748 // spurious NaN if added to infinite c. 1749 assert Double.isInfinite(c); 1750 return c; 1751 } else { 1752 result = product + c; 1753 assert !Double.isFinite(result); 1754 return result; 1755 } 1756 } else { // All inputs finite 1757 BigDecimal product = (new BigDecimal(a)).multiply(new BigDecimal(b)); 1758 if (c == 0.0) { // Positive or negative zero 1759 // If the product is an exact zero, use a 1760 // floating-point expression to compute the sign 1761 // of the zero final result. The product is an 1762 // exact zero if and only if at least one of a and 1763 // b is zero. 1764 if (a == 0.0 || b == 0.0) { 1765 return a * b + c; 1766 } else { 1767 // The sign of a zero addend doesn't matter if 1768 // the product is nonzero. The sign of a zero 1769 // addend is not factored in the result if the 1770 // exact product is nonzero but underflows to 1771 // zero; see IEEE-754 2008 section 6.3 "The 1772 // sign bit". 1773 return product.doubleValue(); 1774 } 1775 } else { 1776 return product.add(new BigDecimal(c)).doubleValue(); 1777 } 1778 } 1779 } 1780 } 1781 1782 /** 1783 * Returns the fused multiply add of the three arguments; that is, 1784 * returns the exact product of the first two arguments summed 1785 * with the third argument and then rounded once to the nearest 1786 * {@code float}. 1787 * 1788 * The rounding is done using the {@linkplain 1789 * java.math.RoundingMode#HALF_EVEN round to nearest even 1790 * rounding mode}. 1791 * 1792 * In contrast, if {@code a * b + c} is evaluated as a regular 1793 * floating-point expression, two rounding errors are involved, 1794 * the first for the multiply operation, the second for the 1795 * addition operation. 1796 * 1797 * <p>Special cases: 1798 * <ul> 1799 * <li> If any argument is NaN, the result is NaN. 1800 * 1801 * <li> If one of the first two arguments is infinite and the 1802 * other is zero, the result is NaN. 1803 * 1804 * <li> If the exact product of the first two arguments is infinite 1805 * (in other words, at least one of the arguments is infinite and 1806 * the other is neither zero nor NaN) and the third argument is an 1807 * infinity of the opposite sign, the result is NaN. 1808 * 1809 * </ul> 1810 * 1811 * <p>Note that {@code fma(a, 1.0f, c)} returns the same 1812 * result as ({@code a + c}). However, 1813 * {@code fma(a, b, +0.0f)} does <em>not</em> always return the 1814 * same result as ({@code a * b}) since 1815 * {@code fma(-0.0f, +0.0f, +0.0f)} is {@code +0.0f} while 1816 * ({@code -0.0f * +0.0f}) is {@code -0.0f}; {@code fma(a, b, -0.0f)} is 1817 * equivalent to ({@code a * b}) however. 1818 * 1819 * @apiNote This method corresponds to the fusedMultiplyAdd 1820 * operation defined in IEEE 754-2008. 1821 * 1822 * @param a a value 1823 * @param b a value 1824 * @param c a value 1825 * 1826 * @return (<i>a</i> × <i>b</i> + <i>c</i>) 1827 * computed, as if with unlimited range and precision, and rounded 1828 * once to the nearest {@code float} value 1829 * 1830 * @since 9 1831 */ 1832 @HotSpotIntrinsicCandidate 1833 public static float fma(float a, float b, float c) { 1834 /* 1835 * Since the double format has more than twice the precision 1836 * of the float format, the multiply of a * b is exact in 1837 * double. The add of c to the product then incurs one 1838 * rounding error. Since the double format moreover has more 1839 * than (2p + 2) precision bits compared to the p bits of the 1840 * float format, the two roundings of (a * b + c), first to 1841 * the double format and then secondarily to the float format, 1842 * are equivalent to rounding the intermediate result directly 1843 * to the float format. 1844 * 1845 * In terms of strictfp vs default-fp concerns related to 1846 * overflow and underflow, since 1847 * 1848 * (Float.MAX_VALUE * Float.MAX_VALUE) << Double.MAX_VALUE 1849 * (Float.MIN_VALUE * Float.MIN_VALUE) >> Double.MIN_VALUE 1850 * 1851 * neither the multiply nor add will overflow or underflow in 1852 * double. Therefore, it is not necessary for this method to 1853 * be declared strictfp to have reproducible 1854 * behavior. However, it is necessary to explicitly store down 1855 * to a float variable to avoid returning a value in the float 1856 * extended value set. 1857 */ 1858 float result = (float)(((double) a * (double) b ) + (double) c); 1859 return result; 1860 } 1861 1862 /** 1863 * Returns the size of an ulp of the argument. An ulp, unit in 1864 * the last place, of a {@code double} value is the positive 1865 * distance between this floating-point value and the {@code 1866 * double} value next larger in magnitude. Note that for non-NaN 1867 * <i>x</i>, <code>ulp(-<i>x</i>) == ulp(<i>x</i>)</code>. 1868 * 1869 * <p>Special Cases: 1870 * <ul> 1871 * <li> If the argument is NaN, then the result is NaN. 1872 * <li> If the argument is positive or negative infinity, then the 1873 * result is positive infinity. 1874 * <li> If the argument is positive or negative zero, then the result is 1875 * {@code Double.MIN_VALUE}. 1876 * <li> If the argument is ±{@code Double.MAX_VALUE}, then 1877 * the result is equal to 2<sup>971</sup>. 1878 * </ul> 1879 * 1880 * @param d the floating-point value whose ulp is to be returned 1881 * @return the size of an ulp of the argument 1882 * @author Joseph D. Darcy 1883 * @since 1.5 1884 */ 1885 public static double ulp(double d) { 1886 int exp = getExponent(d); 1887 1888 switch(exp) { 1889 case Double.MAX_EXPONENT + 1: // NaN or infinity 1890 return Math.abs(d); 1891 1892 case Double.MIN_EXPONENT - 1: // zero or subnormal 1893 return Double.MIN_VALUE; 1894 1895 default: 1896 assert exp <= Double.MAX_EXPONENT && exp >= Double.MIN_EXPONENT; 1897 1898 // ulp(x) is usually 2^(SIGNIFICAND_WIDTH-1)*(2^ilogb(x)) 1899 exp = exp - (DoubleConsts.SIGNIFICAND_WIDTH-1); 1900 if (exp >= Double.MIN_EXPONENT) { 1901 return powerOfTwoD(exp); 1902 } 1903 else { 1904 // return a subnormal result; left shift integer 1905 // representation of Double.MIN_VALUE appropriate 1906 // number of positions 1907 return Double.longBitsToDouble(1L << 1908 (exp - (Double.MIN_EXPONENT - (DoubleConsts.SIGNIFICAND_WIDTH-1)) )); 1909 } 1910 } 1911 } 1912 1913 /** 1914 * Returns the size of an ulp of the argument. An ulp, unit in 1915 * the last place, of a {@code float} value is the positive 1916 * distance between this floating-point value and the {@code 1917 * float} value next larger in magnitude. Note that for non-NaN 1918 * <i>x</i>, <code>ulp(-<i>x</i>) == ulp(<i>x</i>)</code>. 1919 * 1920 * <p>Special Cases: 1921 * <ul> 1922 * <li> If the argument is NaN, then the result is NaN. 1923 * <li> If the argument is positive or negative infinity, then the 1924 * result is positive infinity. 1925 * <li> If the argument is positive or negative zero, then the result is 1926 * {@code Float.MIN_VALUE}. 1927 * <li> If the argument is ±{@code Float.MAX_VALUE}, then 1928 * the result is equal to 2<sup>104</sup>. 1929 * </ul> 1930 * 1931 * @param f the floating-point value whose ulp is to be returned 1932 * @return the size of an ulp of the argument 1933 * @author Joseph D. Darcy 1934 * @since 1.5 1935 */ 1936 public static float ulp(float f) { 1937 int exp = getExponent(f); 1938 1939 switch(exp) { 1940 case Float.MAX_EXPONENT+1: // NaN or infinity 1941 return Math.abs(f); 1942 1943 case Float.MIN_EXPONENT-1: // zero or subnormal 1944 return Float.MIN_VALUE; 1945 1946 default: 1947 assert exp <= Float.MAX_EXPONENT && exp >= Float.MIN_EXPONENT; 1948 1949 // ulp(x) is usually 2^(SIGNIFICAND_WIDTH-1)*(2^ilogb(x)) 1950 exp = exp - (FloatConsts.SIGNIFICAND_WIDTH-1); 1951 if (exp >= Float.MIN_EXPONENT) { 1952 return powerOfTwoF(exp); 1953 } else { 1954 // return a subnormal result; left shift integer 1955 // representation of FloatConsts.MIN_VALUE appropriate 1956 // number of positions 1957 return Float.intBitsToFloat(1 << 1958 (exp - (Float.MIN_EXPONENT - (FloatConsts.SIGNIFICAND_WIDTH-1)) )); 1959 } 1960 } 1961 } 1962 1963 /** 1964 * Returns the signum function of the argument; zero if the argument 1965 * is zero, 1.0 if the argument is greater than zero, -1.0 if the 1966 * argument is less than zero. 1967 * 1968 * <p>Special Cases: 1969 * <ul> 1970 * <li> If the argument is NaN, then the result is NaN. 1971 * <li> If the argument is positive zero or negative zero, then the 1972 * result is the same as the argument. 1973 * </ul> 1974 * 1975 * @param d the floating-point value whose signum is to be returned 1976 * @return the signum function of the argument 1977 * @author Joseph D. Darcy 1978 * @since 1.5 1979 */ 1980 public static double signum(double d) { 1981 return (d == 0.0 || Double.isNaN(d))?d:copySign(1.0, d); 1982 } 1983 1984 /** 1985 * Returns the signum function of the argument; zero if the argument 1986 * is zero, 1.0f if the argument is greater than zero, -1.0f if the 1987 * argument is less than zero. 1988 * 1989 * <p>Special Cases: 1990 * <ul> 1991 * <li> If the argument is NaN, then the result is NaN. 1992 * <li> If the argument is positive zero or negative zero, then the 1993 * result is the same as the argument. 1994 * </ul> 1995 * 1996 * @param f the floating-point value whose signum is to be returned 1997 * @return the signum function of the argument 1998 * @author Joseph D. Darcy 1999 * @since 1.5 2000 */ 2001 public static float signum(float f) { 2002 return (f == 0.0f || Float.isNaN(f))?f:copySign(1.0f, f); 2003 } 2004 2005 /** 2006 * Returns the hyperbolic sine of a {@code double} value. 2007 * The hyperbolic sine of <i>x</i> is defined to be 2008 * (<i>e<sup>x</sup> - e<sup>-x</sup></i>)/2 2009 * where <i>e</i> is {@linkplain Math#E Euler's number}. 2010 * 2011 * <p>Special cases: 2012 * <ul> 2013 * 2014 * <li>If the argument is NaN, then the result is NaN. 2015 * 2016 * <li>If the argument is infinite, then the result is an infinity 2017 * with the same sign as the argument. 2018 * 2019 * <li>If the argument is zero, then the result is a zero with the 2020 * same sign as the argument. 2021 * 2022 * </ul> 2023 * 2024 * <p>The computed result must be within 2.5 ulps of the exact result. 2025 * 2026 * @param x The number whose hyperbolic sine is to be returned. 2027 * @return The hyperbolic sine of {@code x}. 2028 * @since 1.5 2029 */ 2030 public static double sinh(double x) { 2031 return StrictMath.sinh(x); 2032 } 2033 2034 /** 2035 * Returns the hyperbolic cosine of a {@code double} value. 2036 * The hyperbolic cosine of <i>x</i> is defined to be 2037 * (<i>e<sup>x</sup> + e<sup>-x</sup></i>)/2 2038 * where <i>e</i> is {@linkplain Math#E Euler's number}. 2039 * 2040 * <p>Special cases: 2041 * <ul> 2042 * 2043 * <li>If the argument is NaN, then the result is NaN. 2044 * 2045 * <li>If the argument is infinite, then the result is positive 2046 * infinity. 2047 * 2048 * <li>If the argument is zero, then the result is {@code 1.0}. 2049 * 2050 * </ul> 2051 * 2052 * <p>The computed result must be within 2.5 ulps of the exact result. 2053 * 2054 * @param x The number whose hyperbolic cosine is to be returned. 2055 * @return The hyperbolic cosine of {@code x}. 2056 * @since 1.5 2057 */ 2058 public static double cosh(double x) { 2059 return StrictMath.cosh(x); 2060 } 2061 2062 /** 2063 * Returns the hyperbolic tangent of a {@code double} value. 2064 * The hyperbolic tangent of <i>x</i> is defined to be 2065 * (<i>e<sup>x</sup> - e<sup>-x</sup></i>)/(<i>e<sup>x</sup> + e<sup>-x</sup></i>), 2066 * in other words, {@linkplain Math#sinh 2067 * sinh(<i>x</i>)}/{@linkplain Math#cosh cosh(<i>x</i>)}. Note 2068 * that the absolute value of the exact tanh is always less than 2069 * 1. 2070 * 2071 * <p>Special cases: 2072 * <ul> 2073 * 2074 * <li>If the argument is NaN, then the result is NaN. 2075 * 2076 * <li>If the argument is zero, then the result is a zero with the 2077 * same sign as the argument. 2078 * 2079 * <li>If the argument is positive infinity, then the result is 2080 * {@code +1.0}. 2081 * 2082 * <li>If the argument is negative infinity, then the result is 2083 * {@code -1.0}. 2084 * 2085 * </ul> 2086 * 2087 * <p>The computed result must be within 2.5 ulps of the exact result. 2088 * The result of {@code tanh} for any finite input must have 2089 * an absolute value less than or equal to 1. Note that once the 2090 * exact result of tanh is within 1/2 of an ulp of the limit value 2091 * of ±1, correctly signed ±{@code 1.0} should 2092 * be returned. 2093 * 2094 * @param x The number whose hyperbolic tangent is to be returned. 2095 * @return The hyperbolic tangent of {@code x}. 2096 * @since 1.5 2097 */ 2098 public static double tanh(double x) { 2099 return StrictMath.tanh(x); 2100 } 2101 2102 /** 2103 * Returns sqrt(<i>x</i><sup>2</sup> +<i>y</i><sup>2</sup>) 2104 * without intermediate overflow or underflow. 2105 * 2106 * <p>Special cases: 2107 * <ul> 2108 * 2109 * <li> If either argument is infinite, then the result 2110 * is positive infinity. 2111 * 2112 * <li> If either argument is NaN and neither argument is infinite, 2113 * then the result is NaN. 2114 * 2115 * </ul> 2116 * 2117 * <p>The computed result must be within 1 ulp of the exact 2118 * result. If one parameter is held constant, the results must be 2119 * semi-monotonic in the other parameter. 2120 * 2121 * @param x a value 2122 * @param y a value 2123 * @return sqrt(<i>x</i><sup>2</sup> +<i>y</i><sup>2</sup>) 2124 * without intermediate overflow or underflow 2125 * @since 1.5 2126 */ 2127 public static double hypot(double x, double y) { 2128 return StrictMath.hypot(x, y); 2129 } 2130 2131 /** 2132 * Returns <i>e</i><sup>x</sup> -1. Note that for values of 2133 * <i>x</i> near 0, the exact sum of 2134 * {@code expm1(x)} + 1 is much closer to the true 2135 * result of <i>e</i><sup>x</sup> than {@code exp(x)}. 2136 * 2137 * <p>Special cases: 2138 * <ul> 2139 * <li>If the argument is NaN, the result is NaN. 2140 * 2141 * <li>If the argument is positive infinity, then the result is 2142 * positive infinity. 2143 * 2144 * <li>If the argument is negative infinity, then the result is 2145 * -1.0. 2146 * 2147 * <li>If the argument is zero, then the result is a zero with the 2148 * same sign as the argument. 2149 * 2150 * </ul> 2151 * 2152 * <p>The computed result must be within 1 ulp of the exact result. 2153 * Results must be semi-monotonic. The result of 2154 * {@code expm1} for any finite input must be greater than or 2155 * equal to {@code -1.0}. Note that once the exact result of 2156 * <i>e</i><sup>{@code x}</sup> - 1 is within 1/2 2157 * ulp of the limit value -1, {@code -1.0} should be 2158 * returned. 2159 * 2160 * @param x the exponent to raise <i>e</i> to in the computation of 2161 * <i>e</i><sup>{@code x}</sup> -1. 2162 * @return the value <i>e</i><sup>{@code x}</sup> - 1. 2163 * @since 1.5 2164 */ 2165 public static double expm1(double x) { 2166 return StrictMath.expm1(x); 2167 } 2168 2169 /** 2170 * Returns the natural logarithm of the sum of the argument and 1. 2171 * Note that for small values {@code x}, the result of 2172 * {@code log1p(x)} is much closer to the true result of ln(1 2173 * + {@code x}) than the floating-point evaluation of 2174 * {@code log(1.0+x)}. 2175 * 2176 * <p>Special cases: 2177 * 2178 * <ul> 2179 * 2180 * <li>If the argument is NaN or less than -1, then the result is 2181 * NaN. 2182 * 2183 * <li>If the argument is positive infinity, then the result is 2184 * positive infinity. 2185 * 2186 * <li>If the argument is negative one, then the result is 2187 * negative infinity. 2188 * 2189 * <li>If the argument is zero, then the result is a zero with the 2190 * same sign as the argument. 2191 * 2192 * </ul> 2193 * 2194 * <p>The computed result must be within 1 ulp of the exact result. 2195 * Results must be semi-monotonic. 2196 * 2197 * @param x a value 2198 * @return the value ln({@code x} + 1), the natural 2199 * log of {@code x} + 1 2200 * @since 1.5 2201 */ 2202 public static double log1p(double x) { 2203 return StrictMath.log1p(x); 2204 } 2205 2206 /** 2207 * Returns the first floating-point argument with the sign of the 2208 * second floating-point argument. Note that unlike the {@link 2209 * StrictMath#copySign(double, double) StrictMath.copySign} 2210 * method, this method does not require NaN {@code sign} 2211 * arguments to be treated as positive values; implementations are 2212 * permitted to treat some NaN arguments as positive and other NaN 2213 * arguments as negative to allow greater performance. 2214 * 2215 * @param magnitude the parameter providing the magnitude of the result 2216 * @param sign the parameter providing the sign of the result 2217 * @return a value with the magnitude of {@code magnitude} 2218 * and the sign of {@code sign}. 2219 * @since 1.6 2220 */ 2221 public static double copySign(double magnitude, double sign) { 2222 return Double.longBitsToDouble((Double.doubleToRawLongBits(sign) & 2223 (DoubleConsts.SIGN_BIT_MASK)) | 2224 (Double.doubleToRawLongBits(magnitude) & 2225 (DoubleConsts.EXP_BIT_MASK | 2226 DoubleConsts.SIGNIF_BIT_MASK))); 2227 } 2228 2229 /** 2230 * Returns the first floating-point argument with the sign of the 2231 * second floating-point argument. Note that unlike the {@link 2232 * StrictMath#copySign(float, float) StrictMath.copySign} 2233 * method, this method does not require NaN {@code sign} 2234 * arguments to be treated as positive values; implementations are 2235 * permitted to treat some NaN arguments as positive and other NaN 2236 * arguments as negative to allow greater performance. 2237 * 2238 * @param magnitude the parameter providing the magnitude of the result 2239 * @param sign the parameter providing the sign of the result 2240 * @return a value with the magnitude of {@code magnitude} 2241 * and the sign of {@code sign}. 2242 * @since 1.6 2243 */ 2244 public static float copySign(float magnitude, float sign) { 2245 return Float.intBitsToFloat((Float.floatToRawIntBits(sign) & 2246 (FloatConsts.SIGN_BIT_MASK)) | 2247 (Float.floatToRawIntBits(magnitude) & 2248 (FloatConsts.EXP_BIT_MASK | 2249 FloatConsts.SIGNIF_BIT_MASK))); 2250 } 2251 2252 /** 2253 * Returns the unbiased exponent used in the representation of a 2254 * {@code float}. Special cases: 2255 * 2256 * <ul> 2257 * <li>If the argument is NaN or infinite, then the result is 2258 * {@link Float#MAX_EXPONENT} + 1. 2259 * <li>If the argument is zero or subnormal, then the result is 2260 * {@link Float#MIN_EXPONENT} -1. 2261 * </ul> 2262 * @param f a {@code float} value 2263 * @return the unbiased exponent of the argument 2264 * @since 1.6 2265 */ 2266 public static int getExponent(float f) { 2267 /* 2268 * Bitwise convert f to integer, mask out exponent bits, shift 2269 * to the right and then subtract out float's bias adjust to 2270 * get true exponent value 2271 */ 2272 return ((Float.floatToRawIntBits(f) & FloatConsts.EXP_BIT_MASK) >> 2273 (FloatConsts.SIGNIFICAND_WIDTH - 1)) - FloatConsts.EXP_BIAS; 2274 } 2275 2276 /** 2277 * Returns the unbiased exponent used in the representation of a 2278 * {@code double}. Special cases: 2279 * 2280 * <ul> 2281 * <li>If the argument is NaN or infinite, then the result is 2282 * {@link Double#MAX_EXPONENT} + 1. 2283 * <li>If the argument is zero or subnormal, then the result is 2284 * {@link Double#MIN_EXPONENT} -1. 2285 * </ul> 2286 * @param d a {@code double} value 2287 * @return the unbiased exponent of the argument 2288 * @since 1.6 2289 */ 2290 public static int getExponent(double d) { 2291 /* 2292 * Bitwise convert d to long, mask out exponent bits, shift 2293 * to the right and then subtract out double's bias adjust to 2294 * get true exponent value. 2295 */ 2296 return (int)(((Double.doubleToRawLongBits(d) & DoubleConsts.EXP_BIT_MASK) >> 2297 (DoubleConsts.SIGNIFICAND_WIDTH - 1)) - DoubleConsts.EXP_BIAS); 2298 } 2299 2300 /** 2301 * Returns the floating-point number adjacent to the first 2302 * argument in the direction of the second argument. If both 2303 * arguments compare as equal the second argument is returned. 2304 * 2305 * <p> 2306 * Special cases: 2307 * <ul> 2308 * <li> If either argument is a NaN, then NaN is returned. 2309 * 2310 * <li> If both arguments are signed zeros, {@code direction} 2311 * is returned unchanged (as implied by the requirement of 2312 * returning the second argument if the arguments compare as 2313 * equal). 2314 * 2315 * <li> If {@code start} is 2316 * ±{@link Double#MIN_VALUE} and {@code direction} 2317 * has a value such that the result should have a smaller 2318 * magnitude, then a zero with the same sign as {@code start} 2319 * is returned. 2320 * 2321 * <li> If {@code start} is infinite and 2322 * {@code direction} has a value such that the result should 2323 * have a smaller magnitude, {@link Double#MAX_VALUE} with the 2324 * same sign as {@code start} is returned. 2325 * 2326 * <li> If {@code start} is equal to ± 2327 * {@link Double#MAX_VALUE} and {@code direction} has a 2328 * value such that the result should have a larger magnitude, an 2329 * infinity with same sign as {@code start} is returned. 2330 * </ul> 2331 * 2332 * @param start starting floating-point value 2333 * @param direction value indicating which of 2334 * {@code start}'s neighbors or {@code start} should 2335 * be returned 2336 * @return The floating-point number adjacent to {@code start} in the 2337 * direction of {@code direction}. 2338 * @since 1.6 2339 */ 2340 public static double nextAfter(double start, double direction) { 2341 /* 2342 * The cases: 2343 * 2344 * nextAfter(+infinity, 0) == MAX_VALUE 2345 * nextAfter(+infinity, +infinity) == +infinity 2346 * nextAfter(-infinity, 0) == -MAX_VALUE 2347 * nextAfter(-infinity, -infinity) == -infinity 2348 * 2349 * are naturally handled without any additional testing 2350 */ 2351 2352 /* 2353 * IEEE 754 floating-point numbers are lexicographically 2354 * ordered if treated as signed-magnitude integers. 2355 * Since Java's integers are two's complement, 2356 * incrementing the two's complement representation of a 2357 * logically negative floating-point value *decrements* 2358 * the signed-magnitude representation. Therefore, when 2359 * the integer representation of a floating-point value 2360 * is negative, the adjustment to the representation is in 2361 * the opposite direction from what would initially be expected. 2362 */ 2363 2364 // Branch to descending case first as it is more costly than ascending 2365 // case due to start != 0.0d conditional. 2366 if (start > direction) { // descending 2367 if (start != 0.0d) { 2368 final long transducer = Double.doubleToRawLongBits(start); 2369 return Double.longBitsToDouble(transducer + ((transducer > 0L) ? -1L : 1L)); 2370 } else { // start == 0.0d && direction < 0.0d 2371 return -Double.MIN_VALUE; 2372 } 2373 } else if (start < direction) { // ascending 2374 // Add +0.0 to get rid of a -0.0 (+0.0 + -0.0 => +0.0) 2375 // then bitwise convert start to integer. 2376 final long transducer = Double.doubleToRawLongBits(start + 0.0d); 2377 return Double.longBitsToDouble(transducer + ((transducer >= 0L) ? 1L : -1L)); 2378 } else if (start == direction) { 2379 return direction; 2380 } else { // isNaN(start) || isNaN(direction) 2381 return start + direction; 2382 } 2383 } 2384 2385 /** 2386 * Returns the floating-point number adjacent to the first 2387 * argument in the direction of the second argument. If both 2388 * arguments compare as equal a value equivalent to the second argument 2389 * is returned. 2390 * 2391 * <p> 2392 * Special cases: 2393 * <ul> 2394 * <li> If either argument is a NaN, then NaN is returned. 2395 * 2396 * <li> If both arguments are signed zeros, a value equivalent 2397 * to {@code direction} is returned. 2398 * 2399 * <li> If {@code start} is 2400 * ±{@link Float#MIN_VALUE} and {@code direction} 2401 * has a value such that the result should have a smaller 2402 * magnitude, then a zero with the same sign as {@code start} 2403 * is returned. 2404 * 2405 * <li> If {@code start} is infinite and 2406 * {@code direction} has a value such that the result should 2407 * have a smaller magnitude, {@link Float#MAX_VALUE} with the 2408 * same sign as {@code start} is returned. 2409 * 2410 * <li> If {@code start} is equal to ± 2411 * {@link Float#MAX_VALUE} and {@code direction} has a 2412 * value such that the result should have a larger magnitude, an 2413 * infinity with same sign as {@code start} is returned. 2414 * </ul> 2415 * 2416 * @param start starting floating-point value 2417 * @param direction value indicating which of 2418 * {@code start}'s neighbors or {@code start} should 2419 * be returned 2420 * @return The floating-point number adjacent to {@code start} in the 2421 * direction of {@code direction}. 2422 * @since 1.6 2423 */ 2424 public static float nextAfter(float start, double direction) { 2425 /* 2426 * The cases: 2427 * 2428 * nextAfter(+infinity, 0) == MAX_VALUE 2429 * nextAfter(+infinity, +infinity) == +infinity 2430 * nextAfter(-infinity, 0) == -MAX_VALUE 2431 * nextAfter(-infinity, -infinity) == -infinity 2432 * 2433 * are naturally handled without any additional testing 2434 */ 2435 2436 /* 2437 * IEEE 754 floating-point numbers are lexicographically 2438 * ordered if treated as signed-magnitude integers. 2439 * Since Java's integers are two's complement, 2440 * incrementing the two's complement representation of a 2441 * logically negative floating-point value *decrements* 2442 * the signed-magnitude representation. Therefore, when 2443 * the integer representation of a floating-point value 2444 * is negative, the adjustment to the representation is in 2445 * the opposite direction from what would initially be expected. 2446 */ 2447 2448 // Branch to descending case first as it is more costly than ascending 2449 // case due to start != 0.0f conditional. 2450 if (start > direction) { // descending 2451 if (start != 0.0f) { 2452 final int transducer = Float.floatToRawIntBits(start); 2453 return Float.intBitsToFloat(transducer + ((transducer > 0) ? -1 : 1)); 2454 } else { // start == 0.0f && direction < 0.0f 2455 return -Float.MIN_VALUE; 2456 } 2457 } else if (start < direction) { // ascending 2458 // Add +0.0 to get rid of a -0.0 (+0.0 + -0.0 => +0.0) 2459 // then bitwise convert start to integer. 2460 final int transducer = Float.floatToRawIntBits(start + 0.0f); 2461 return Float.intBitsToFloat(transducer + ((transducer >= 0) ? 1 : -1)); 2462 } else if (start == direction) { 2463 return (float)direction; 2464 } else { // isNaN(start) || isNaN(direction) 2465 return start + (float)direction; 2466 } 2467 } 2468 2469 /** 2470 * Returns the floating-point value adjacent to {@code d} in 2471 * the direction of positive infinity. This method is 2472 * semantically equivalent to {@code nextAfter(d, 2473 * Double.POSITIVE_INFINITY)}; however, a {@code nextUp} 2474 * implementation may run faster than its equivalent 2475 * {@code nextAfter} call. 2476 * 2477 * <p>Special Cases: 2478 * <ul> 2479 * <li> If the argument is NaN, the result is NaN. 2480 * 2481 * <li> If the argument is positive infinity, the result is 2482 * positive infinity. 2483 * 2484 * <li> If the argument is zero, the result is 2485 * {@link Double#MIN_VALUE} 2486 * 2487 * </ul> 2488 * 2489 * @param d starting floating-point value 2490 * @return The adjacent floating-point value closer to positive 2491 * infinity. 2492 * @since 1.6 2493 */ 2494 public static double nextUp(double d) { 2495 // Use a single conditional and handle the likely cases first. 2496 if (d < Double.POSITIVE_INFINITY) { 2497 // Add +0.0 to get rid of a -0.0 (+0.0 + -0.0 => +0.0). 2498 final long transducer = Double.doubleToRawLongBits(d + 0.0D); 2499 return Double.longBitsToDouble(transducer + ((transducer >= 0L) ? 1L : -1L)); 2500 } else { // d is NaN or +Infinity 2501 return d; 2502 } 2503 } 2504 2505 /** 2506 * Returns the floating-point value adjacent to {@code f} in 2507 * the direction of positive infinity. This method is 2508 * semantically equivalent to {@code nextAfter(f, 2509 * Float.POSITIVE_INFINITY)}; however, a {@code nextUp} 2510 * implementation may run faster than its equivalent 2511 * {@code nextAfter} call. 2512 * 2513 * <p>Special Cases: 2514 * <ul> 2515 * <li> If the argument is NaN, the result is NaN. 2516 * 2517 * <li> If the argument is positive infinity, the result is 2518 * positive infinity. 2519 * 2520 * <li> If the argument is zero, the result is 2521 * {@link Float#MIN_VALUE} 2522 * 2523 * </ul> 2524 * 2525 * @param f starting floating-point value 2526 * @return The adjacent floating-point value closer to positive 2527 * infinity. 2528 * @since 1.6 2529 */ 2530 public static float nextUp(float f) { 2531 // Use a single conditional and handle the likely cases first. 2532 if (f < Float.POSITIVE_INFINITY) { 2533 // Add +0.0 to get rid of a -0.0 (+0.0 + -0.0 => +0.0). 2534 final int transducer = Float.floatToRawIntBits(f + 0.0F); 2535 return Float.intBitsToFloat(transducer + ((transducer >= 0) ? 1 : -1)); 2536 } else { // f is NaN or +Infinity 2537 return f; 2538 } 2539 } 2540 2541 /** 2542 * Returns the floating-point value adjacent to {@code d} in 2543 * the direction of negative infinity. This method is 2544 * semantically equivalent to {@code nextAfter(d, 2545 * Double.NEGATIVE_INFINITY)}; however, a 2546 * {@code nextDown} implementation may run faster than its 2547 * equivalent {@code nextAfter} call. 2548 * 2549 * <p>Special Cases: 2550 * <ul> 2551 * <li> If the argument is NaN, the result is NaN. 2552 * 2553 * <li> If the argument is negative infinity, the result is 2554 * negative infinity. 2555 * 2556 * <li> If the argument is zero, the result is 2557 * {@code -Double.MIN_VALUE} 2558 * 2559 * </ul> 2560 * 2561 * @param d starting floating-point value 2562 * @return The adjacent floating-point value closer to negative 2563 * infinity. 2564 * @since 1.8 2565 */ 2566 public static double nextDown(double d) { 2567 if (Double.isNaN(d) || d == Double.NEGATIVE_INFINITY) 2568 return d; 2569 else { 2570 if (d == 0.0) 2571 return -Double.MIN_VALUE; 2572 else 2573 return Double.longBitsToDouble(Double.doubleToRawLongBits(d) + 2574 ((d > 0.0d)?-1L:+1L)); 2575 } 2576 } 2577 2578 /** 2579 * Returns the floating-point value adjacent to {@code f} in 2580 * the direction of negative infinity. This method is 2581 * semantically equivalent to {@code nextAfter(f, 2582 * Float.NEGATIVE_INFINITY)}; however, a 2583 * {@code nextDown} implementation may run faster than its 2584 * equivalent {@code nextAfter} call. 2585 * 2586 * <p>Special Cases: 2587 * <ul> 2588 * <li> If the argument is NaN, the result is NaN. 2589 * 2590 * <li> If the argument is negative infinity, the result is 2591 * negative infinity. 2592 * 2593 * <li> If the argument is zero, the result is 2594 * {@code -Float.MIN_VALUE} 2595 * 2596 * </ul> 2597 * 2598 * @param f starting floating-point value 2599 * @return The adjacent floating-point value closer to negative 2600 * infinity. 2601 * @since 1.8 2602 */ 2603 public static float nextDown(float f) { 2604 if (Float.isNaN(f) || f == Float.NEGATIVE_INFINITY) 2605 return f; 2606 else { 2607 if (f == 0.0f) 2608 return -Float.MIN_VALUE; 2609 else 2610 return Float.intBitsToFloat(Float.floatToRawIntBits(f) + 2611 ((f > 0.0f)?-1:+1)); 2612 } 2613 } 2614 2615 /** 2616 * Returns {@code d} × 2617 * 2<sup>{@code scaleFactor}</sup> rounded as if performed 2618 * by a single correctly rounded floating-point multiply to a 2619 * member of the double value set. See the Java 2620 * Language Specification for a discussion of floating-point 2621 * value sets. If the exponent of the result is between {@link 2622 * Double#MIN_EXPONENT} and {@link Double#MAX_EXPONENT}, the 2623 * answer is calculated exactly. If the exponent of the result 2624 * would be larger than {@code Double.MAX_EXPONENT}, an 2625 * infinity is returned. Note that if the result is subnormal, 2626 * precision may be lost; that is, when {@code scalb(x, n)} 2627 * is subnormal, {@code scalb(scalb(x, n), -n)} may not equal 2628 * <i>x</i>. When the result is non-NaN, the result has the same 2629 * sign as {@code d}. 2630 * 2631 * <p>Special cases: 2632 * <ul> 2633 * <li> If the first argument is NaN, NaN is returned. 2634 * <li> If the first argument is infinite, then an infinity of the 2635 * same sign is returned. 2636 * <li> If the first argument is zero, then a zero of the same 2637 * sign is returned. 2638 * </ul> 2639 * 2640 * @param d number to be scaled by a power of two. 2641 * @param scaleFactor power of 2 used to scale {@code d} 2642 * @return {@code d} × 2<sup>{@code scaleFactor}</sup> 2643 * @since 1.6 2644 */ 2645 public static double scalb(double d, int scaleFactor) { 2646 /* 2647 * This method does not need to be declared strictfp to 2648 * compute the same correct result on all platforms. When 2649 * scaling up, it does not matter what order the 2650 * multiply-store operations are done; the result will be 2651 * finite or overflow regardless of the operation ordering. 2652 * However, to get the correct result when scaling down, a 2653 * particular ordering must be used. 2654 * 2655 * When scaling down, the multiply-store operations are 2656 * sequenced so that it is not possible for two consecutive 2657 * multiply-stores to return subnormal results. If one 2658 * multiply-store result is subnormal, the next multiply will 2659 * round it away to zero. This is done by first multiplying 2660 * by 2 ^ (scaleFactor % n) and then multiplying several 2661 * times by 2^n as needed where n is the exponent of number 2662 * that is a convenient power of two. In this way, at most one 2663 * real rounding error occurs. If the double value set is 2664 * being used exclusively, the rounding will occur on a 2665 * multiply. If the double-extended-exponent value set is 2666 * being used, the products will (perhaps) be exact but the 2667 * stores to d are guaranteed to round to the double value 2668 * set. 2669 * 2670 * It is _not_ a valid implementation to first multiply d by 2671 * 2^MIN_EXPONENT and then by 2 ^ (scaleFactor % 2672 * MIN_EXPONENT) since even in a strictfp program double 2673 * rounding on underflow could occur; e.g. if the scaleFactor 2674 * argument was (MIN_EXPONENT - n) and the exponent of d was a 2675 * little less than -(MIN_EXPONENT - n), meaning the final 2676 * result would be subnormal. 2677 * 2678 * Since exact reproducibility of this method can be achieved 2679 * without any undue performance burden, there is no 2680 * compelling reason to allow double rounding on underflow in 2681 * scalb. 2682 */ 2683 2684 // magnitude of a power of two so large that scaling a finite 2685 // nonzero value by it would be guaranteed to over or 2686 // underflow; due to rounding, scaling down takes an 2687 // additional power of two which is reflected here 2688 final int MAX_SCALE = Double.MAX_EXPONENT + -Double.MIN_EXPONENT + 2689 DoubleConsts.SIGNIFICAND_WIDTH + 1; 2690 int exp_adjust = 0; 2691 int scale_increment = 0; 2692 double exp_delta = Double.NaN; 2693 2694 // Make sure scaling factor is in a reasonable range 2695 2696 if(scaleFactor < 0) { 2697 scaleFactor = Math.max(scaleFactor, -MAX_SCALE); 2698 scale_increment = -512; 2699 exp_delta = twoToTheDoubleScaleDown; 2700 } 2701 else { 2702 scaleFactor = Math.min(scaleFactor, MAX_SCALE); 2703 scale_increment = 512; 2704 exp_delta = twoToTheDoubleScaleUp; 2705 } 2706 2707 // Calculate (scaleFactor % +/-512), 512 = 2^9, using 2708 // technique from "Hacker's Delight" section 10-2. 2709 int t = (scaleFactor >> 9-1) >>> 32 - 9; 2710 exp_adjust = ((scaleFactor + t) & (512 -1)) - t; 2711 2712 d *= powerOfTwoD(exp_adjust); 2713 scaleFactor -= exp_adjust; 2714 2715 while(scaleFactor != 0) { 2716 d *= exp_delta; 2717 scaleFactor -= scale_increment; 2718 } 2719 return d; 2720 } 2721 2722 /** 2723 * Returns {@code f} × 2724 * 2<sup>{@code scaleFactor}</sup> rounded as if performed 2725 * by a single correctly rounded floating-point multiply to a 2726 * member of the float value set. See the Java 2727 * Language Specification for a discussion of floating-point 2728 * value sets. If the exponent of the result is between {@link 2729 * Float#MIN_EXPONENT} and {@link Float#MAX_EXPONENT}, the 2730 * answer is calculated exactly. If the exponent of the result 2731 * would be larger than {@code Float.MAX_EXPONENT}, an 2732 * infinity is returned. Note that if the result is subnormal, 2733 * precision may be lost; that is, when {@code scalb(x, n)} 2734 * is subnormal, {@code scalb(scalb(x, n), -n)} may not equal 2735 * <i>x</i>. When the result is non-NaN, the result has the same 2736 * sign as {@code f}. 2737 * 2738 * <p>Special cases: 2739 * <ul> 2740 * <li> If the first argument is NaN, NaN is returned. 2741 * <li> If the first argument is infinite, then an infinity of the 2742 * same sign is returned. 2743 * <li> If the first argument is zero, then a zero of the same 2744 * sign is returned. 2745 * </ul> 2746 * 2747 * @param f number to be scaled by a power of two. 2748 * @param scaleFactor power of 2 used to scale {@code f} 2749 * @return {@code f} × 2<sup>{@code scaleFactor}</sup> 2750 * @since 1.6 2751 */ 2752 public static float scalb(float f, int scaleFactor) { 2753 // magnitude of a power of two so large that scaling a finite 2754 // nonzero value by it would be guaranteed to over or 2755 // underflow; due to rounding, scaling down takes an 2756 // additional power of two which is reflected here 2757 final int MAX_SCALE = Float.MAX_EXPONENT + -Float.MIN_EXPONENT + 2758 FloatConsts.SIGNIFICAND_WIDTH + 1; 2759 2760 // Make sure scaling factor is in a reasonable range 2761 scaleFactor = Math.max(Math.min(scaleFactor, MAX_SCALE), -MAX_SCALE); 2762 2763 /* 2764 * Since + MAX_SCALE for float fits well within the double 2765 * exponent range and + float -> double conversion is exact 2766 * the multiplication below will be exact. Therefore, the 2767 * rounding that occurs when the double product is cast to 2768 * float will be the correctly rounded float result. Since 2769 * all operations other than the final multiply will be exact, 2770 * it is not necessary to declare this method strictfp. 2771 */ 2772 return (float)((double)f*powerOfTwoD(scaleFactor)); 2773 } 2774 2775 // Constants used in scalb 2776 static double twoToTheDoubleScaleUp = powerOfTwoD(512); 2777 static double twoToTheDoubleScaleDown = powerOfTwoD(-512); 2778 2779 /** 2780 * Returns a floating-point power of two in the normal range. 2781 */ 2782 static double powerOfTwoD(int n) { 2783 assert(n >= Double.MIN_EXPONENT && n <= Double.MAX_EXPONENT); 2784 return Double.longBitsToDouble((((long)n + (long)DoubleConsts.EXP_BIAS) << 2785 (DoubleConsts.SIGNIFICAND_WIDTH-1)) 2786 & DoubleConsts.EXP_BIT_MASK); 2787 } 2788 2789 /** 2790 * Returns a floating-point power of two in the normal range. 2791 */ 2792 static float powerOfTwoF(int n) { 2793 assert(n >= Float.MIN_EXPONENT && n <= Float.MAX_EXPONENT); 2794 return Float.intBitsToFloat(((n + FloatConsts.EXP_BIAS) << 2795 (FloatConsts.SIGNIFICAND_WIDTH-1)) 2796 & FloatConsts.EXP_BIT_MASK); 2797 } 2798 }